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