]> git.saurik.com Git - cycript.git/blob - Console.cpp
Peel away CYCompound layers to fix tab completion.
[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 FILE *fout_;
156
157 static void Output(CYUTF8String json, FILE *fout, bool expand = false) {
158 const char *data(json.data);
159 size_t size(json.size);
160
161 if (data == NULL || fout == NULL)
162 return;
163
164 if (!expand || data[0] != '"' && data[0] != '\'')
165 fputs(data, fout);
166 else for (size_t i(0); i != size; ++i)
167 if (data[i] != '\\')
168 fputc(data[i], fout);
169 else switch(data[++i]) {
170 case '\0': goto done;
171 case '\\': fputc('\\', fout); break;
172 case '\'': fputc('\'', fout); break;
173 case '"': fputc('"', fout); break;
174 case 'b': fputc('\b', fout); break;
175 case 'f': fputc('\f', fout); break;
176 case 'n': fputc('\n', fout); break;
177 case 'r': fputc('\r', fout); break;
178 case 't': fputc('\t', fout); break;
179 case 'v': fputc('\v', fout); break;
180 default: fputc('\\', fout); --i; break;
181 }
182
183 done:
184 fputs("\n", fout);
185 fflush(fout);
186 }
187
188 static void Run(int client, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
189 CYPool pool;
190 Output(Run(pool, client, CYUTF8String(data, size)), fout, expand);
191 }
192
193 static void Run(int client, std::string &code, FILE *fout = NULL, bool expand = false) {
194 Run(client, code.c_str(), code.size(), fout, expand);
195 }
196
197 int (*append_history$)(int, const char *);
198
199 static std::string command_;
200
201 static CYExpression *ParseExpression(CYUTF8String code) {
202 std::ostringstream str;
203 str << '(' << code << ')';
204 std::string string(str.str());
205
206 CYDriver driver;
207 driver.data_ = string.c_str();
208 driver.size_ = string.size();
209
210 cy::parser parser(driver);
211 Setup(driver, parser);
212
213 if (parser.parse() != 0 || !driver.errors_.empty())
214 return NULL;
215
216 CYOptions options;
217 CYContext context(options);
218
219 // XXX: this could be replaced with a CYStatement::Primitive()
220 if (CYExpress *express = dynamic_cast<CYExpress *>(driver.program_->statements_))
221 return express->expression_->Primitive(context);
222
223 return NULL;
224 }
225
226 static int client_;
227
228 static char **Complete(const char *word, int start, int end) {
229 rl_attempted_completion_over = TRUE;
230
231 CYLocalPool pool;
232 CYDriver driver;
233 cy::parser parser(driver);
234 Setup(driver, parser);
235
236 std::string line(rl_line_buffer, start);
237 std::string command(command_ + line);
238
239 driver.data_ = command.c_str();
240 driver.size_ = command.size();
241
242 driver.auto_ = true;
243
244 if (parser.parse() != 0 || !driver.errors_.empty())
245 return NULL;
246
247 if (driver.mode_ == CYDriver::AutoNone)
248 return NULL;
249
250 CYExpression *expression;
251
252 CYOptions options;
253 CYContext context(options);
254
255 std::ostringstream prefix;
256
257 switch (driver.mode_) {
258 case CYDriver::AutoPrimary:
259 expression = $ CYThis();
260 break;
261
262 case CYDriver::AutoDirect:
263 expression = driver.context_;
264 break;
265
266 case CYDriver::AutoIndirect:
267 expression = $ CYIndirect(driver.context_);
268 break;
269
270 case CYDriver::AutoMessage: {
271 CYDriver::Context &thing(driver.contexts_.back());
272 expression = $M($C1($V("object_getClass"), thing.context_), $S("messages"));
273 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
274 prefix << (*part)->word_ << ':';
275 } break;
276
277 default:
278 _assert(false);
279 }
280
281 std::string begin(prefix.str());
282
283 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
284 " function(object, prefix, word) {\n"
285 " var names = [];\n"
286 " var pattern = '^' + prefix + word;\n"
287 " var length = prefix.length;\n"
288 " for (name in object)\n"
289 " if (name.match(pattern) != null)\n"
290 " names.push(name.substr(length));\n"
291 " return names;\n"
292 " }\n"
293 ), expression, $S(begin.c_str()), $S(word))));
294
295 driver.program_->Replace(context);
296
297 std::ostringstream str;
298 CYOutput out(str, options);
299 out << *driver.program_;
300
301 std::string code(str.str());
302 CYUTF8String json(Run(pool, client_, code));
303
304 CYExpression *result(ParseExpression(json));
305 if (result == NULL)
306 return NULL;
307
308 CYArray *array(dynamic_cast<CYArray *>(result));
309
310 if (array == NULL) {
311 fprintf(fout_, "\n");
312 Output(json, fout_);
313 rl_forced_update_display();
314 return NULL;
315 }
316
317 // XXX: use an std::set?
318 typedef std::vector<std::string> Completions;
319 Completions completions;
320
321 std::string common;
322 bool rest(false);
323
324 CYForEach (element, array->elements_) {
325 CYString *string(dynamic_cast<CYString *>(element->value_));
326 _assert(string != NULL);
327
328 std::string completion;
329 if (string->size_ != 0)
330 completion.assign(string->value_, string->size_);
331 else if (driver.mode_ == CYDriver::AutoMessage)
332 completion = "]";
333 else
334 continue;
335
336 completions.push_back(completion);
337
338 if (!rest) {
339 common = completion;
340 rest = true;
341 } else {
342 size_t limit(completion.size()), size(common.size());
343 if (size > limit)
344 common = common.substr(0, limit);
345 else
346 limit = size;
347 for (limit = 0; limit != size; ++limit)
348 if (common[limit] != completion[limit])
349 break;
350 if (limit != size)
351 common = common.substr(0, limit);
352 }
353 }
354
355 size_t count(completions.size());
356 if (count == 0)
357 return NULL;
358
359 size_t colon(common.find(':'));
360 if (colon != std::string::npos)
361 common = common.substr(0, colon + 1);
362 if (completions.size() == 1)
363 common += ' ';
364
365 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
366
367 results[0] = strdup(common.c_str());
368 size_t index(0);
369 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
370 results[++index] = strdup(i->c_str());
371 results[count + 1] = NULL;
372
373 return results;
374 }
375
376 // need char *, not const char *
377 static char name_[] = "cycript";
378 static char break_[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
379
380 static void Console(CYOptions &options) {
381 CYPool pool;
382
383 passwd *passwd;
384 if (const char *username = getenv("LOGNAME"))
385 passwd = getpwnam(username);
386 else
387 passwd = getpwuid(getuid());
388
389 const char *basedir(apr_psprintf(pool, "%s/.cycript", passwd->pw_dir));
390 const char *histfile(apr_psprintf(pool, "%s/history", basedir));
391 size_t histlines(0);
392
393 rl_initialize();
394 rl_readline_name = name_;
395
396 mkdir(basedir, 0700);
397 read_history(histfile);
398
399 bool bypass(false);
400 bool debug(false);
401 bool expand(false);
402
403 fout_ = stdout;
404
405 // rl_completer_word_break_characters is broken in libedit
406 rl_basic_word_break_characters = break_;
407
408 rl_completer_word_break_characters = break_;
409 rl_attempted_completion_function = &Complete;
410 rl_bind_key('\t', rl_complete);
411
412 struct sigaction action;
413 sigemptyset(&action.sa_mask);
414 action.sa_handler = &sigint;
415 action.sa_flags = 0;
416 sigaction(SIGINT, &action, NULL);
417
418 restart: for (;;) {
419 command_.clear();
420 std::vector<std::string> lines;
421
422 bool extra(false);
423 const char *prompt("cy# ");
424
425 if (setjmp(ctrlc_) != 0) {
426 mode_ = Working;
427 fputs("\n", fout_);
428 fflush(fout_);
429 goto restart;
430 }
431
432 read:
433 mode_ = Parsing;
434 char *line(readline(prompt));
435 mode_ = Working;
436 if (line == NULL)
437 break;
438 if (line[0] == '\0')
439 goto read;
440
441 if (!extra) {
442 extra = true;
443 if (line[0] == '?') {
444 std::string data(line + 1);
445 if (data == "bypass") {
446 bypass = !bypass;
447 fprintf(fout_, "bypass == %s\n", bypass ? "true" : "false");
448 fflush(fout_);
449 } else if (data == "debug") {
450 debug = !debug;
451 fprintf(fout_, "debug == %s\n", debug ? "true" : "false");
452 fflush(fout_);
453 } else if (data == "expand") {
454 expand = !expand;
455 fprintf(fout_, "expand == %s\n", expand ? "true" : "false");
456 fflush(fout_);
457 }
458 add_history(line);
459 ++histlines;
460 goto restart;
461 }
462 }
463
464 command_ += line;
465
466 char *begin(line), *end(line + strlen(line));
467 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
468 *nl = '\0';
469 lines.push_back(begin);
470 begin = nl + 1;
471 }
472
473 lines.push_back(begin);
474
475 free(line);
476
477 std::string code;
478
479 if (bypass)
480 code = command_;
481 else {
482 CYLocalPool pool;
483 CYDriver driver;
484 cy::parser parser(driver);
485 Setup(driver, parser);
486
487 driver.data_ = command_.c_str();
488 driver.size_ = command_.size();
489
490 if (parser.parse() != 0 || !driver.errors_.empty()) {
491 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
492 cy::position begin(error->location_.begin);
493 if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) {
494 cy::position end(error->location_.end);
495
496 if (begin.line != lines.size()) {
497 std::cerr << " | ";
498 std::cerr << lines[begin.line - 1] << std::endl;
499 }
500
501 std::cerr << "....";
502 for (size_t i(0); i != begin.column; ++i)
503 std::cerr << '.';
504 if (begin.line != end.line || begin.column == end.column)
505 std::cerr << '^';
506 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
507 std::cerr << '^';
508 std::cerr << std::endl;
509
510 std::cerr << " | ";
511 std::cerr << error->message_ << std::endl;
512
513 add_history(command_.c_str());
514 ++histlines;
515 goto restart;
516 }
517 }
518
519 driver.errors_.clear();
520
521 command_ += '\n';
522 prompt = "cy> ";
523 goto read;
524 }
525
526 if (driver.program_ == NULL)
527 goto restart;
528
529 if (client_ != -1)
530 code = command_;
531 else {
532 std::ostringstream str;
533 CYOutput out(str, options);
534 Setup(out, driver, options);
535 out << *driver.program_;
536 code = str.str();
537 }
538 }
539
540 add_history(command_.c_str());
541 ++histlines;
542
543 if (debug)
544 std::cout << code << std::endl;
545
546 Run(client_, code, fout_, expand);
547 }
548
549 if (append_history$ != NULL) {
550 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
551 (*append_history$)(histlines, histfile);
552 } else {
553 write_history(histfile);
554 }
555
556 fputs("\n", fout_);
557 fflush(fout_);
558 }
559
560 static void *Map(const char *path, size_t *psize) {
561 int fd;
562 _syscall(fd = open(path, O_RDONLY));
563
564 struct stat stat;
565 _syscall(fstat(fd, &stat));
566 size_t size(stat.st_size);
567
568 *psize = size;
569
570 void *base;
571 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
572
573 _syscall(close(fd));
574 return base;
575 }
576
577 void InjectLibrary(pid_t pid);
578
579 int Main(int argc, char const * const argv[], char const * const envp[]) {
580 bool tty(isatty(STDIN_FILENO));
581 bool compile(false);
582 CYOptions options;
583
584 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
585
586 #ifdef CY_ATTACH
587 pid_t pid(_not(pid_t));
588 #endif
589
590 CYPool pool;
591 apr_getopt_t *state;
592 _aprcall(apr_getopt_init(&state, pool, argc, argv));
593
594 for (;;) {
595 char opt;
596 const char *arg;
597
598 apr_status_t status(apr_getopt(state,
599 "cg:n:"
600 #ifdef CY_ATTACH
601 "p:"
602 #endif
603 "s"
604 , &opt, &arg));
605
606 switch (status) {
607 case APR_EOF:
608 goto getopt;
609 case APR_BADCH:
610 case APR_BADARG:
611 fprintf(stderr,
612 "usage: cycript [-c]"
613 #ifdef CY_ATTACH
614 " [-p <pid|name>]"
615 #endif
616 " [<script> [<arg>...]]\n"
617 );
618 return 1;
619 default:
620 _aprcall(status);
621 }
622
623 switch (opt) {
624 case 'c':
625 compile = true;
626 break;
627
628 case 'g':
629 if (false);
630 else if (strcmp(arg, "rename") == 0)
631 options.verbose_ = true;
632 #if YYDEBUG
633 else if (strcmp(arg, "bison") == 0)
634 bison_ = true;
635 #endif
636 else {
637 fprintf(stderr, "invalid name for -g\n");
638 return 1;
639 }
640 break;
641
642 case 'n':
643 if (false);
644 else if (strcmp(arg, "minify") == 0)
645 pretty_ = true;
646 else {
647 fprintf(stderr, "invalid name for -n\n");
648 return 1;
649 }
650 break;
651
652 #ifdef CY_ATTACH
653 case 'p': {
654 size_t size(strlen(arg));
655 char *end;
656
657 pid = strtoul(arg, &end, 0);
658 if (arg + size != end) {
659 // XXX: arg needs to be escaped in some horrendous way of doom
660 const char *command(apr_psprintf(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg));
661
662 if (FILE *pids = popen(command, "r")) {
663 char value[32];
664 size = 0;
665
666 for (;;) {
667 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
668 if (read == 0)
669 break;
670 else {
671 size += read;
672 if (size == sizeof(value)) {
673 pid = _not(pid_t);
674 goto fail;
675 }
676 }
677 }
678
679 size:
680 if (size == 0)
681 goto fail;
682 if (value[size - 1] == '\n') {
683 --size;
684 goto size;
685 }
686
687 value[size] = '\0';
688 size = strlen(value);
689 pid = strtoul(value, &end, 0);
690 if (value + size != end) fail:
691 pid = _not(pid_t);
692 _syscall(pclose(pids));
693 }
694
695 if (pid == _not(pid_t)) {
696 fprintf(stderr, "invalid pid for -p\n");
697 return 1;
698 }
699 }
700 } break;
701 #endif
702
703 case 's':
704 strict_ = true;
705 break;
706 }
707 } getopt:;
708
709 const char *script;
710 int ind(state->ind);
711
712 #ifdef CY_ATTACH
713 if (pid != _not(pid_t) && ind < argc - 1) {
714 fprintf(stderr, "-p cannot set argv\n");
715 return 1;
716 }
717
718 if (pid != _not(pid_t) && compile) {
719 fprintf(stderr, "-p conflicts with -c\n");
720 return 1;
721 }
722 #endif
723
724 if (ind == argc)
725 script = NULL;
726 else {
727 #ifdef CY_EXECUTE
728 // XXX: const_cast?! wtf gcc :(
729 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
730 #endif
731 script = argv[ind];
732 if (strcmp(script, "-") == 0)
733 script = NULL;
734 }
735
736 #ifdef CY_ATTACH
737 if (pid != _not(pid_t) && script == NULL && !tty) {
738 fprintf(stderr, "non-terminal attaching to remote console\n");
739 return 1;
740 }
741 #endif
742
743 #ifdef CY_ATTACH
744 if (pid == _not(pid_t))
745 client_ = -1;
746 else {
747 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
748 struct sockaddr_un address;
749 memset(&address, 0, sizeof(address));
750 address.sun_family = AF_UNIX;
751
752 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
753
754 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
755 _syscall(chmod(address.sun_path, 0777));
756
757 try {
758 _syscall(listen(server, 1));
759 InjectLibrary(pid);
760 client_ = _syscall(accept(server, NULL, NULL));
761 } catch (...) {
762 // XXX: exception?
763 unlink(address.sun_path);
764 throw;
765 }
766 } catch (...) {
767 _syscall(close(server));
768 throw;
769 }
770 }
771 #else
772 client_ = -1;
773 #endif
774
775 if (script == NULL && tty)
776 Console(options);
777 else {
778 CYLocalPool pool;
779 CYDriver driver(script ?: "<stdin>");
780 cy::parser parser(driver);
781 Setup(driver, parser);
782
783 char *start, *end;
784
785 if (script == NULL) {
786 start = NULL;
787 end = NULL;
788
789 driver.file_ = stdin;
790 } else {
791 size_t size;
792 start = reinterpret_cast<char *>(Map(script, &size));
793 end = start + size;
794
795 if (size >= 2 && start[0] == '#' && start[1] == '!') {
796 start += 2;
797
798 if (void *line = memchr(start, '\n', end - start))
799 start = reinterpret_cast<char *>(line);
800 else
801 start = end;
802 }
803
804 driver.data_ = start;
805 driver.size_ = end - start;
806 }
807
808 if (parser.parse() != 0 || !driver.errors_.empty()) {
809 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
810 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
811 } else if (driver.program_ != NULL)
812 if (client_ != -1) {
813 std::string code(start, end-start);
814 Run(client_, code, stdout);
815 } else {
816 std::ostringstream str;
817 CYOutput out(str, options);
818 Setup(out, driver, options);
819 out << *driver.program_;
820 std::string code(str.str());
821 if (compile)
822 std::cout << code;
823 else
824 Run(client_, code, stdout);
825 }
826 }
827
828 return 0;
829 }
830
831 int main(int argc, char const * const argv[], char const * const envp[]) {
832 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
833
834 if (status != APR_SUCCESS) {
835 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
836 return 1;
837 } else try {
838 return Main(argc, argv, envp);
839 } catch (const CYException &error) {
840 CYPool pool;
841 fprintf(stderr, "%s\n", error.PoolCString(pool));
842 return 1;
843 }
844 }