]> git.saurik.com Git - cycript.git/blob - Console.cpp
Replace use of FILE* with std::ostream* in Console.
[cycript.git] / Console.cpp
1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2012 Jay Freeman (saurik)
3 */
4
5 /* GNU Lesser General Public License, Version 3 {{{ */
6 /*
7 * Cycript is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * Cycript is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #include "cycript.hpp"
23
24 #ifdef CY_EXECUTE
25 #include "JavaScript.hpp"
26 #endif
27
28 #include <cstdio>
29 #include <sstream>
30
31 #include <setjmp.h>
32
33 #ifdef HAVE_READLINE_H
34 #include <readline.h>
35 #else
36 #include <readline/readline.h>
37 #endif
38
39 #ifdef HAVE_HISTORY_H
40 #include <history.h>
41 #else
42 #include <readline/history.h>
43 #endif
44
45 #include <sys/mman.h>
46
47 #include <errno.h>
48 #include <unistd.h>
49
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 #include <fcntl.h>
53
54 #include "Cycript.tab.hh"
55
56 #include <sys/types.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <sys/un.h>
60 #include <pwd.h>
61
62 #include <apr_getopt.h>
63
64 #include <dlfcn.h>
65
66 #include "Replace.hpp"
67
68 static volatile enum {
69 Working,
70 Parsing,
71 Running,
72 Sending,
73 Waiting,
74 } mode_;
75
76 static jmp_buf ctrlc_;
77
78 static void sigint(int) {
79 switch (mode_) {
80 case Working:
81 return;
82 case Parsing:
83 longjmp(ctrlc_, 1);
84 case Running:
85 throw "*** Ctrl-C";
86 case Sending:
87 return;
88 case Waiting:
89 return;
90 }
91 }
92
93 #if YYDEBUG
94 static bool bison_;
95 #endif
96 static bool strict_;
97 static bool pretty_;
98
99 void Setup(CYDriver &driver, cy::parser &parser) {
100 #if YYDEBUG
101 if (bison_)
102 parser.set_debug_level(1);
103 #endif
104 if (strict_)
105 driver.strict_ = true;
106 }
107
108 void Setup(CYOutput &out, CYDriver &driver, CYOptions &options) {
109 out.pretty_ = pretty_;
110 CYContext context(options);
111 driver.program_->Replace(context);
112 }
113
114 static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
115 const char *json;
116 size_t size;
117
118 if (client == -1) {
119 mode_ = Running;
120 #ifdef CY_EXECUTE
121 json = CYExecute(pool, code);
122 #else
123 json = NULL;
124 #endif
125 mode_ = Working;
126 if (json == NULL)
127 size = 0;
128 else
129 size = strlen(json);
130 } else {
131 mode_ = Sending;
132 size = code.size;
133 CYSendAll(client, &size, sizeof(size));
134 CYSendAll(client, code.data, code.size);
135 mode_ = Waiting;
136 CYRecvAll(client, &size, sizeof(size));
137 if (size == _not(size_t))
138 json = NULL;
139 else {
140 char *temp(new(pool) char[size + 1]);
141 CYRecvAll(client, temp, size);
142 temp[size] = '\0';
143 json = temp;
144 }
145 mode_ = Working;
146 }
147
148 return CYUTF8String(json, size);
149 }
150
151 static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
152 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
153 }
154
155 static std::ostream *out_;
156
157 static void Output(CYUTF8String json, std::ostream *out, bool expand = false) {
158 const char *data(json.data);
159 size_t size(json.size);
160
161 if (data == NULL || out == NULL)
162 return;
163
164 if (!expand ||
165 data[0] != '@' && data[0] != '"' && data[0] != '\'' ||
166 data[0] == '@' && data[1] != '"' && data[1] != '\''
167 )
168 out->write(data, size);
169 else for (size_t i(0); i != size; ++i)
170 if (data[i] != '\\')
171 *out << data[i];
172 else switch(data[++i]) {
173 case '\0': goto done;
174 case '\\': *out << '\\'; break;
175 case '\'': *out << '\''; break;
176 case '"': *out << '"'; break;
177 case 'b': *out << '\b'; break;
178 case 'f': *out << '\f'; break;
179 case 'n': *out << '\n'; break;
180 case 'r': *out << '\r'; break;
181 case 't': *out << '\t'; break;
182 case 'v': *out << '\v'; break;
183 default: *out << '\\'; --i; break;
184 }
185
186 done:
187 *out << std::endl;
188 }
189
190 static void Run(int client, const char *data, size_t size, std::ostream *out = NULL, bool expand = false) {
191 CYPool pool;
192 Output(Run(pool, client, CYUTF8String(data, size)), out, expand);
193 }
194
195 static void Run(int client, std::string &code, std::ostream *out = NULL, bool expand = false) {
196 Run(client, code.c_str(), code.size(), out, expand);
197 }
198
199 int (*append_history$)(int, const char *);
200
201 static std::string command_;
202
203 static CYExpression *ParseExpression(CYUTF8String code) {
204 std::stringstream stream;
205 stream << '(' << code << ')';
206 CYDriver driver(stream);
207
208 cy::parser parser(driver);
209 Setup(driver, parser);
210
211 if (parser.parse() != 0 || !driver.errors_.empty())
212 return NULL;
213
214 CYOptions options;
215 CYContext context(options);
216
217 // XXX: this could be replaced with a CYStatement::Primitive()
218 if (CYExpress *express = dynamic_cast<CYExpress *>(driver.program_->statements_))
219 return express->expression_->Primitive(context);
220
221 return NULL;
222 }
223
224 static int client_;
225
226 static char **Complete(const char *word, int start, int end) {
227 rl_attempted_completion_over = TRUE;
228
229 CYLocalPool pool;
230
231 std::string line(rl_line_buffer, start);
232 std::istringstream stream(command_ + line);
233 CYDriver driver(stream);
234
235 driver.auto_ = true;
236
237 cy::parser parser(driver);
238 Setup(driver, parser);
239
240 if (parser.parse() != 0 || !driver.errors_.empty())
241 return NULL;
242
243 if (driver.mode_ == CYDriver::AutoNone)
244 return NULL;
245
246 CYExpression *expression;
247
248 CYOptions options;
249 CYContext context(options);
250
251 std::ostringstream prefix;
252
253 switch (driver.mode_) {
254 case CYDriver::AutoPrimary:
255 expression = $ CYThis();
256 break;
257
258 case CYDriver::AutoDirect:
259 expression = driver.context_;
260 break;
261
262 case CYDriver::AutoIndirect:
263 expression = $ CYIndirect(driver.context_);
264 break;
265
266 case CYDriver::AutoMessage: {
267 CYDriver::Context &thing(driver.contexts_.back());
268 expression = $M($C1($V("object_getClass"), thing.context_), $S("messages"));
269 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
270 prefix << (*part)->word_ << ':';
271 } break;
272
273 default:
274 _assert(false);
275 }
276
277 std::string begin(prefix.str());
278
279 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
280 " function(object, prefix, word) {\n"
281 " var names = [];\n"
282 " var before = prefix.length;\n"
283 " prefix += word;\n"
284 " var entire = prefix.length;\n"
285 " for (name in object)\n"
286 " if (name.substring(0, entire) == prefix)\n"
287 " names.push(name.substr(before));\n"
288 " return names;\n"
289 " }\n"
290 ), expression, $S(begin.c_str()), $S(word))));
291
292 driver.program_->Replace(context);
293
294 std::ostringstream str;
295 CYOutput out(str, options);
296 out << *driver.program_;
297
298 std::string code(str.str());
299 CYUTF8String json(Run(pool, client_, code));
300 // XXX: if this fails we should not try to parse it
301
302 CYExpression *result(ParseExpression(json));
303 if (result == NULL)
304 return NULL;
305
306 CYArray *array(dynamic_cast<CYArray *>(result));
307
308 if (array == NULL) {
309 *out_ << '\n';
310 Output(json, out_);
311 rl_forced_update_display();
312 return NULL;
313 }
314
315 // XXX: use an std::set?
316 typedef std::vector<std::string> Completions;
317 Completions completions;
318
319 std::string common;
320 bool rest(false);
321
322 CYForEach (element, array->elements_) {
323 CYString *string(dynamic_cast<CYString *>(element->value_));
324 _assert(string != NULL);
325
326 std::string completion;
327 if (string->size_ != 0)
328 completion.assign(string->value_, string->size_);
329 else if (driver.mode_ == CYDriver::AutoMessage)
330 completion = "]";
331 else
332 continue;
333
334 completions.push_back(completion);
335
336 if (!rest) {
337 common = completion;
338 rest = true;
339 } else {
340 size_t limit(completion.size()), size(common.size());
341 if (size > limit)
342 common = common.substr(0, limit);
343 else
344 limit = size;
345 for (limit = 0; limit != size; ++limit)
346 if (common[limit] != completion[limit])
347 break;
348 if (limit != size)
349 common = common.substr(0, limit);
350 }
351 }
352
353 size_t count(completions.size());
354 if (count == 0)
355 return NULL;
356
357 size_t colon(common.find(':'));
358 if (colon != std::string::npos)
359 common = common.substr(0, colon + 1);
360 if (completions.size() == 1)
361 common += ' ';
362
363 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
364
365 results[0] = strdup(common.c_str());
366 size_t index(0);
367 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
368 results[++index] = strdup(i->c_str());
369 results[count + 1] = NULL;
370
371 return results;
372 }
373
374 // need char *, not const char *
375 static char name_[] = "cycript";
376 static char break_[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
377
378 static void Console(CYOptions &options) {
379 CYPool pool;
380
381 passwd *passwd;
382 if (const char *username = getenv("LOGNAME"))
383 passwd = getpwnam(username);
384 else
385 passwd = getpwuid(getuid());
386
387 const char *basedir(apr_psprintf(pool, "%s/.cycript", passwd->pw_dir));
388 const char *histfile(apr_psprintf(pool, "%s/history", basedir));
389 size_t histlines(0);
390
391 rl_initialize();
392 rl_readline_name = name_;
393
394 mkdir(basedir, 0700);
395 read_history(histfile);
396
397 bool bypass(false);
398 bool debug(false);
399 bool expand(false);
400
401 out_ = &std::cout;
402
403 // rl_completer_word_break_characters is broken in libedit
404 rl_basic_word_break_characters = break_;
405
406 rl_completer_word_break_characters = break_;
407 rl_attempted_completion_function = &Complete;
408 rl_bind_key('\t', rl_complete);
409
410 struct sigaction action;
411 sigemptyset(&action.sa_mask);
412 action.sa_handler = &sigint;
413 action.sa_flags = 0;
414 sigaction(SIGINT, &action, NULL);
415
416 restart: for (;;) {
417 command_.clear();
418 std::vector<std::string> lines;
419
420 bool extra(false);
421 const char *prompt("cy# ");
422
423 if (setjmp(ctrlc_) != 0) {
424 mode_ = Working;
425 *out_ << std::endl;
426 goto restart;
427 }
428
429 read:
430 mode_ = Parsing;
431 char *line(readline(prompt));
432 mode_ = Working;
433 if (line == NULL)
434 break;
435 if (line[0] == '\0')
436 goto read;
437
438 if (!extra) {
439 extra = true;
440 if (line[0] == '?') {
441 std::string data(line + 1);
442 if (data == "bypass") {
443 bypass = !bypass;
444 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
445 } else if (data == "debug") {
446 debug = !debug;
447 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
448 } else if (data == "expand") {
449 expand = !expand;
450 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
451 }
452 add_history(line);
453 ++histlines;
454 goto restart;
455 }
456 }
457
458 command_ += line;
459
460 char *begin(line), *end(line + strlen(line));
461 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
462 *nl = '\0';
463 lines.push_back(begin);
464 begin = nl + 1;
465 }
466
467 lines.push_back(begin);
468
469 free(line);
470
471 std::string code;
472
473 if (bypass)
474 code = command_;
475 else {
476 CYLocalPool pool;
477
478 std::istringstream stream(command_);
479 CYDriver driver(stream);
480
481 cy::parser parser(driver);
482 Setup(driver, parser);
483
484 if (parser.parse() != 0 || !driver.errors_.empty()) {
485 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
486 cy::position begin(error->location_.begin);
487 if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) {
488 cy::position end(error->location_.end);
489
490 if (begin.line != lines.size()) {
491 std::cerr << " | ";
492 std::cerr << lines[begin.line - 1] << std::endl;
493 }
494
495 std::cerr << "....";
496 for (size_t i(0); i != begin.column; ++i)
497 std::cerr << '.';
498 if (begin.line != end.line || begin.column == end.column)
499 std::cerr << '^';
500 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
501 std::cerr << '^';
502 std::cerr << std::endl;
503
504 std::cerr << " | ";
505 std::cerr << error->message_ << std::endl;
506
507 add_history(command_.c_str());
508 ++histlines;
509 goto restart;
510 }
511 }
512
513 driver.errors_.clear();
514
515 command_ += '\n';
516 prompt = "cy> ";
517 goto read;
518 }
519
520 if (driver.program_ == NULL)
521 goto restart;
522
523 if (client_ != -1)
524 code = command_;
525 else {
526 std::ostringstream str;
527 CYOutput out(str, options);
528 Setup(out, driver, options);
529 out << *driver.program_;
530 code = str.str();
531 }
532 }
533
534 add_history(command_.c_str());
535 ++histlines;
536
537 if (debug)
538 std::cout << code << std::endl;
539
540 Run(client_, code, out_, expand);
541 }
542
543 if (append_history$ != NULL) {
544 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
545 (*append_history$)(histlines, histfile);
546 } else {
547 write_history(histfile);
548 }
549
550 *out_ << std::endl;
551 }
552
553 static void *Map(const char *path, size_t *psize) {
554 int fd;
555 _syscall(fd = open(path, O_RDONLY));
556
557 struct stat stat;
558 _syscall(fstat(fd, &stat));
559 size_t size(stat.st_size);
560
561 *psize = size;
562
563 void *base;
564 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
565
566 _syscall(close(fd));
567 return base;
568 }
569
570 void InjectLibrary(pid_t pid);
571
572 int Main(int argc, char const * const argv[], char const * const envp[]) {
573 bool tty(isatty(STDIN_FILENO));
574 bool compile(false);
575 CYOptions options;
576
577 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
578
579 #ifdef CY_ATTACH
580 pid_t pid(_not(pid_t));
581 #endif
582
583 CYPool pool;
584 apr_getopt_t *state;
585 _aprcall(apr_getopt_init(&state, pool, argc, argv));
586
587 for (;;) {
588 char opt;
589 const char *arg;
590
591 apr_status_t status(apr_getopt(state,
592 "cg:n:"
593 #ifdef CY_ATTACH
594 "p:"
595 #endif
596 "s"
597 , &opt, &arg));
598
599 switch (status) {
600 case APR_EOF:
601 goto getopt;
602 case APR_BADCH:
603 case APR_BADARG:
604 fprintf(stderr,
605 "usage: cycript [-c]"
606 #ifdef CY_ATTACH
607 " [-p <pid|name>]"
608 #endif
609 " [<script> [<arg>...]]\n"
610 );
611 return 1;
612 default:
613 _aprcall(status);
614 }
615
616 switch (opt) {
617 case 'c':
618 compile = true;
619 break;
620
621 case 'g':
622 if (false);
623 else if (strcmp(arg, "rename") == 0)
624 options.verbose_ = true;
625 #if YYDEBUG
626 else if (strcmp(arg, "bison") == 0)
627 bison_ = true;
628 #endif
629 else {
630 fprintf(stderr, "invalid name for -g\n");
631 return 1;
632 }
633 break;
634
635 case 'n':
636 if (false);
637 else if (strcmp(arg, "minify") == 0)
638 pretty_ = true;
639 else {
640 fprintf(stderr, "invalid name for -n\n");
641 return 1;
642 }
643 break;
644
645 #ifdef CY_ATTACH
646 case 'p': {
647 size_t size(strlen(arg));
648 char *end;
649
650 pid = strtoul(arg, &end, 0);
651 if (arg + size != end) {
652 // XXX: arg needs to be escaped in some horrendous way of doom
653 const char *command(apr_psprintf(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg));
654
655 if (FILE *pids = popen(command, "r")) {
656 char value[32];
657 size = 0;
658
659 for (;;) {
660 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
661 if (read == 0)
662 break;
663 else {
664 size += read;
665 if (size == sizeof(value)) {
666 pid = _not(pid_t);
667 goto fail;
668 }
669 }
670 }
671
672 size:
673 if (size == 0)
674 goto fail;
675 if (value[size - 1] == '\n') {
676 --size;
677 goto size;
678 }
679
680 value[size] = '\0';
681 size = strlen(value);
682 pid = strtoul(value, &end, 0);
683 if (value + size != end) fail:
684 pid = _not(pid_t);
685 _syscall(pclose(pids));
686 }
687
688 if (pid == _not(pid_t)) {
689 fprintf(stderr, "invalid pid for -p\n");
690 return 1;
691 }
692 }
693 } break;
694 #endif
695
696 case 's':
697 strict_ = true;
698 break;
699 }
700 } getopt:;
701
702 const char *script;
703 int ind(state->ind);
704
705 #ifdef CY_ATTACH
706 if (pid != _not(pid_t) && ind < argc - 1) {
707 fprintf(stderr, "-p cannot set argv\n");
708 return 1;
709 }
710
711 if (pid != _not(pid_t) && compile) {
712 fprintf(stderr, "-p conflicts with -c\n");
713 return 1;
714 }
715 #endif
716
717 if (ind == argc)
718 script = NULL;
719 else {
720 #ifdef CY_EXECUTE
721 // XXX: const_cast?! wtf gcc :(
722 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
723 #endif
724 script = argv[ind];
725 if (strcmp(script, "-") == 0)
726 script = NULL;
727 }
728
729 #ifdef CY_ATTACH
730 if (pid != _not(pid_t) && script == NULL && !tty) {
731 fprintf(stderr, "non-terminal attaching to remote console\n");
732 return 1;
733 }
734 #endif
735
736 #ifdef CY_ATTACH
737 if (pid == _not(pid_t))
738 client_ = -1;
739 else {
740 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
741 struct sockaddr_un address;
742 memset(&address, 0, sizeof(address));
743 address.sun_family = AF_UNIX;
744
745 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
746
747 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
748 _syscall(chmod(address.sun_path, 0777));
749
750 try {
751 _syscall(listen(server, 1));
752 InjectLibrary(pid);
753 client_ = _syscall(accept(server, NULL, NULL));
754 } catch (...) {
755 // XXX: exception?
756 unlink(address.sun_path);
757 throw;
758 }
759 } catch (...) {
760 _syscall(close(server));
761 throw;
762 }
763 }
764 #else
765 client_ = -1;
766 #endif
767
768 if (script == NULL && tty)
769 Console(options);
770 else {
771 CYLocalPool pool;
772
773 char *start, *end;
774 std::istream *indirect;
775
776 if (script == NULL) {
777 start = NULL;
778 end = NULL;
779 indirect = &std::cin;
780 } else {
781 size_t size;
782 start = reinterpret_cast<char *>(Map(script, &size));
783 end = start + size;
784
785 if (size >= 2 && start[0] == '#' && start[1] == '!') {
786 start += 2;
787
788 if (void *line = memchr(start, '\n', end - start))
789 start = reinterpret_cast<char *>(line);
790 else
791 start = end;
792 }
793
794 indirect = NULL;
795 }
796
797 CYStream direct(start, end);
798 std::istream &stream(indirect == NULL ? direct : *indirect);
799 CYDriver driver(stream, script ?: "<stdin>");
800
801 cy::parser parser(driver);
802 Setup(driver, parser);
803
804 if (parser.parse() != 0 || !driver.errors_.empty()) {
805 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
806 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
807 } else if (driver.program_ != NULL)
808 if (client_ != -1) {
809 // XXX: this code means that you can't pipe to another process
810 std::string code(start, end-start);
811 Run(client_, code, &std::cout);
812 } else {
813 std::ostringstream str;
814 CYOutput out(str, options);
815 Setup(out, driver, options);
816 out << *driver.program_;
817 std::string code(str.str());
818 if (compile)
819 std::cout << code;
820 else
821 Run(client_, code, &std::cout);
822 }
823 }
824
825 return 0;
826 }
827
828 int main(int argc, char const * const argv[], char const * const envp[]) {
829 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
830
831 if (status != APR_SUCCESS) {
832 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
833 return 1;
834 } else try {
835 return Main(argc, argv, envp);
836 } catch (const CYException &error) {
837 CYPool pool;
838 fprintf(stderr, "%s\n", error.PoolCString(pool));
839 return 1;
840 }
841 }