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