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