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