]> git.saurik.com Git - cycript.git/blob - Console.cpp
Preempt accidental fall-through setting properties.
[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 before = prefix.length;\n"
287 " prefix += word;\n"
288 " var entire = prefix.length;\n"
289 " for (name in object)\n"
290 " if (name.substring(0, entire) == prefix)\n"
291 " names.push(name.substr(before));\n"
292 " return names;\n"
293 " }\n"
294 ), expression, $S(begin.c_str()), $S(word))));
295
296 driver.program_->Replace(context);
297
298 std::ostringstream str;
299 CYOutput out(str, options);
300 out << *driver.program_;
301
302 std::string code(str.str());
303 CYUTF8String json(Run(pool, client_, code));
304
305 CYExpression *result(ParseExpression(json));
306 if (result == NULL)
307 return NULL;
308
309 CYArray *array(dynamic_cast<CYArray *>(result));
310
311 if (array == NULL) {
312 fprintf(fout_, "\n");
313 Output(json, fout_);
314 rl_forced_update_display();
315 return NULL;
316 }
317
318 // XXX: use an std::set?
319 typedef std::vector<std::string> Completions;
320 Completions completions;
321
322 std::string common;
323 bool rest(false);
324
325 CYForEach (element, array->elements_) {
326 CYString *string(dynamic_cast<CYString *>(element->value_));
327 _assert(string != NULL);
328
329 std::string completion;
330 if (string->size_ != 0)
331 completion.assign(string->value_, string->size_);
332 else if (driver.mode_ == CYDriver::AutoMessage)
333 completion = "]";
334 else
335 continue;
336
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 size_t colon(common.find(':'));
361 if (colon != std::string::npos)
362 common = common.substr(0, colon + 1);
363 if (completions.size() == 1)
364 common += ' ';
365
366 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
367
368 results[0] = strdup(common.c_str());
369 size_t index(0);
370 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
371 results[++index] = strdup(i->c_str());
372 results[count + 1] = NULL;
373
374 return results;
375 }
376
377 // need char *, not const char *
378 static char name_[] = "cycript";
379 static char break_[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
380
381 static void Console(CYOptions &options) {
382 CYPool pool;
383
384 passwd *passwd;
385 if (const char *username = getenv("LOGNAME"))
386 passwd = getpwnam(username);
387 else
388 passwd = getpwuid(getuid());
389
390 const char *basedir(apr_psprintf(pool, "%s/.cycript", passwd->pw_dir));
391 const char *histfile(apr_psprintf(pool, "%s/history", basedir));
392 size_t histlines(0);
393
394 rl_initialize();
395 rl_readline_name = name_;
396
397 mkdir(basedir, 0700);
398 read_history(histfile);
399
400 bool bypass(false);
401 bool debug(false);
402 bool expand(false);
403
404 fout_ = stdout;
405
406 // rl_completer_word_break_characters is broken in libedit
407 rl_basic_word_break_characters = break_;
408
409 rl_completer_word_break_characters = break_;
410 rl_attempted_completion_function = &Complete;
411 rl_bind_key('\t', rl_complete);
412
413 struct sigaction action;
414 sigemptyset(&action.sa_mask);
415 action.sa_handler = &sigint;
416 action.sa_flags = 0;
417 sigaction(SIGINT, &action, NULL);
418
419 restart: for (;;) {
420 command_.clear();
421 std::vector<std::string> lines;
422
423 bool extra(false);
424 const char *prompt("cy# ");
425
426 if (setjmp(ctrlc_) != 0) {
427 mode_ = Working;
428 fputs("\n", fout_);
429 fflush(fout_);
430 goto restart;
431 }
432
433 read:
434 mode_ = Parsing;
435 char *line(readline(prompt));
436 mode_ = Working;
437 if (line == NULL)
438 break;
439 if (line[0] == '\0')
440 goto read;
441
442 if (!extra) {
443 extra = true;
444 if (line[0] == '?') {
445 std::string data(line + 1);
446 if (data == "bypass") {
447 bypass = !bypass;
448 fprintf(fout_, "bypass == %s\n", bypass ? "true" : "false");
449 fflush(fout_);
450 } else if (data == "debug") {
451 debug = !debug;
452 fprintf(fout_, "debug == %s\n", debug ? "true" : "false");
453 fflush(fout_);
454 } else if (data == "expand") {
455 expand = !expand;
456 fprintf(fout_, "expand == %s\n", expand ? "true" : "false");
457 fflush(fout_);
458 }
459 add_history(line);
460 ++histlines;
461 goto restart;
462 }
463 }
464
465 command_ += line;
466
467 char *begin(line), *end(line + strlen(line));
468 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
469 *nl = '\0';
470 lines.push_back(begin);
471 begin = nl + 1;
472 }
473
474 lines.push_back(begin);
475
476 free(line);
477
478 std::string code;
479
480 if (bypass)
481 code = command_;
482 else {
483 CYLocalPool pool;
484 CYDriver driver;
485 cy::parser parser(driver);
486 Setup(driver, parser);
487
488 driver.data_ = command_.c_str();
489 driver.size_ = command_.size();
490
491 if (parser.parse() != 0 || !driver.errors_.empty()) {
492 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
493 cy::position begin(error->location_.begin);
494 if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) {
495 cy::position end(error->location_.end);
496
497 if (begin.line != lines.size()) {
498 std::cerr << " | ";
499 std::cerr << lines[begin.line - 1] << std::endl;
500 }
501
502 std::cerr << "....";
503 for (size_t i(0); i != begin.column; ++i)
504 std::cerr << '.';
505 if (begin.line != end.line || begin.column == end.column)
506 std::cerr << '^';
507 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
508 std::cerr << '^';
509 std::cerr << std::endl;
510
511 std::cerr << " | ";
512 std::cerr << error->message_ << std::endl;
513
514 add_history(command_.c_str());
515 ++histlines;
516 goto restart;
517 }
518 }
519
520 driver.errors_.clear();
521
522 command_ += '\n';
523 prompt = "cy> ";
524 goto read;
525 }
526
527 if (driver.program_ == NULL)
528 goto restart;
529
530 if (client_ != -1)
531 code = command_;
532 else {
533 std::ostringstream str;
534 CYOutput out(str, options);
535 Setup(out, driver, options);
536 out << *driver.program_;
537 code = str.str();
538 }
539 }
540
541 add_history(command_.c_str());
542 ++histlines;
543
544 if (debug)
545 std::cout << code << std::endl;
546
547 Run(client_, code, fout_, expand);
548 }
549
550 if (append_history$ != NULL) {
551 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
552 (*append_history$)(histlines, histfile);
553 } else {
554 write_history(histfile);
555 }
556
557 fputs("\n", fout_);
558 fflush(fout_);
559 }
560
561 static void *Map(const char *path, size_t *psize) {
562 int fd;
563 _syscall(fd = open(path, O_RDONLY));
564
565 struct stat stat;
566 _syscall(fstat(fd, &stat));
567 size_t size(stat.st_size);
568
569 *psize = size;
570
571 void *base;
572 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
573
574 _syscall(close(fd));
575 return base;
576 }
577
578 void InjectLibrary(pid_t pid);
579
580 int Main(int argc, char const * const argv[], char const * const envp[]) {
581 bool tty(isatty(STDIN_FILENO));
582 bool compile(false);
583 CYOptions options;
584
585 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
586
587 #ifdef CY_ATTACH
588 pid_t pid(_not(pid_t));
589 #endif
590
591 CYPool pool;
592 apr_getopt_t *state;
593 _aprcall(apr_getopt_init(&state, pool, argc, argv));
594
595 for (;;) {
596 char opt;
597 const char *arg;
598
599 apr_status_t status(apr_getopt(state,
600 "cg:n:"
601 #ifdef CY_ATTACH
602 "p:"
603 #endif
604 "s"
605 , &opt, &arg));
606
607 switch (status) {
608 case APR_EOF:
609 goto getopt;
610 case APR_BADCH:
611 case APR_BADARG:
612 fprintf(stderr,
613 "usage: cycript [-c]"
614 #ifdef CY_ATTACH
615 " [-p <pid|name>]"
616 #endif
617 " [<script> [<arg>...]]\n"
618 );
619 return 1;
620 default:
621 _aprcall(status);
622 }
623
624 switch (opt) {
625 case 'c':
626 compile = true;
627 break;
628
629 case 'g':
630 if (false);
631 else if (strcmp(arg, "rename") == 0)
632 options.verbose_ = true;
633 #if YYDEBUG
634 else if (strcmp(arg, "bison") == 0)
635 bison_ = true;
636 #endif
637 else {
638 fprintf(stderr, "invalid name for -g\n");
639 return 1;
640 }
641 break;
642
643 case 'n':
644 if (false);
645 else if (strcmp(arg, "minify") == 0)
646 pretty_ = true;
647 else {
648 fprintf(stderr, "invalid name for -n\n");
649 return 1;
650 }
651 break;
652
653 #ifdef CY_ATTACH
654 case 'p': {
655 size_t size(strlen(arg));
656 char *end;
657
658 pid = strtoul(arg, &end, 0);
659 if (arg + size != end) {
660 // XXX: arg needs to be escaped in some horrendous way of doom
661 const char *command(apr_psprintf(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg));
662
663 if (FILE *pids = popen(command, "r")) {
664 char value[32];
665 size = 0;
666
667 for (;;) {
668 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
669 if (read == 0)
670 break;
671 else {
672 size += read;
673 if (size == sizeof(value)) {
674 pid = _not(pid_t);
675 goto fail;
676 }
677 }
678 }
679
680 size:
681 if (size == 0)
682 goto fail;
683 if (value[size - 1] == '\n') {
684 --size;
685 goto size;
686 }
687
688 value[size] = '\0';
689 size = strlen(value);
690 pid = strtoul(value, &end, 0);
691 if (value + size != end) fail:
692 pid = _not(pid_t);
693 _syscall(pclose(pids));
694 }
695
696 if (pid == _not(pid_t)) {
697 fprintf(stderr, "invalid pid for -p\n");
698 return 1;
699 }
700 }
701 } break;
702 #endif
703
704 case 's':
705 strict_ = true;
706 break;
707 }
708 } getopt:;
709
710 const char *script;
711 int ind(state->ind);
712
713 #ifdef CY_ATTACH
714 if (pid != _not(pid_t) && ind < argc - 1) {
715 fprintf(stderr, "-p cannot set argv\n");
716 return 1;
717 }
718
719 if (pid != _not(pid_t) && compile) {
720 fprintf(stderr, "-p conflicts with -c\n");
721 return 1;
722 }
723 #endif
724
725 if (ind == argc)
726 script = NULL;
727 else {
728 #ifdef CY_EXECUTE
729 // XXX: const_cast?! wtf gcc :(
730 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
731 #endif
732 script = argv[ind];
733 if (strcmp(script, "-") == 0)
734 script = NULL;
735 }
736
737 #ifdef CY_ATTACH
738 if (pid != _not(pid_t) && script == NULL && !tty) {
739 fprintf(stderr, "non-terminal attaching to remote console\n");
740 return 1;
741 }
742 #endif
743
744 #ifdef CY_ATTACH
745 if (pid == _not(pid_t))
746 client_ = -1;
747 else {
748 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
749 struct sockaddr_un address;
750 memset(&address, 0, sizeof(address));
751 address.sun_family = AF_UNIX;
752
753 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
754
755 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
756 _syscall(chmod(address.sun_path, 0777));
757
758 try {
759 _syscall(listen(server, 1));
760 InjectLibrary(pid);
761 client_ = _syscall(accept(server, NULL, NULL));
762 } catch (...) {
763 // XXX: exception?
764 unlink(address.sun_path);
765 throw;
766 }
767 } catch (...) {
768 _syscall(close(server));
769 throw;
770 }
771 }
772 #else
773 client_ = -1;
774 #endif
775
776 if (script == NULL && tty)
777 Console(options);
778 else {
779 CYLocalPool pool;
780 CYDriver driver(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 }