]> git.saurik.com Git - cycript.git/blob - Console.cpp
Syntax highlight commands as the user types them.
[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 #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 #if RL_READLINE_VERSION >= 0x0600
403 rl_prep_term_function = CYDisplayStart;
404 rl_redisplay_function = CYDisplayUpdate;
405 rl_deprep_term_function = CYDisplayFinish;
406 #endif
407
408 mkdir(basedir, 0700);
409 read_history(histfile);
410
411 bool bypass(false);
412 bool debug(false);
413 bool expand(false);
414 bool syntax(false);
415
416 out_ = &std::cout;
417
418 // rl_completer_word_break_characters is broken in libedit
419 rl_basic_word_break_characters = break_;
420
421 rl_completer_word_break_characters = break_;
422 rl_attempted_completion_function = &Complete;
423 rl_bind_key('\t', rl_complete);
424
425 struct sigaction action;
426 sigemptyset(&action.sa_mask);
427 action.sa_handler = &sigint;
428 action.sa_flags = 0;
429 sigaction(SIGINT, &action, NULL);
430
431 restart: for (;;) {
432 command_.clear();
433 std::vector<std::string> lines;
434
435 bool extra(false);
436 const char *prompt("cy# ");
437
438 if (setjmp(ctrlc_) != 0) {
439 mode_ = Working;
440 *out_ << std::endl;
441 goto restart;
442 }
443
444 read:
445 mode_ = Parsing;
446 char *line(readline(prompt));
447 mode_ = Working;
448 if (line == NULL)
449 break;
450 if (line[0] == '\0')
451 goto read;
452
453 if (!extra) {
454 extra = true;
455 if (line[0] == '?') {
456 std::string data(line + 1);
457 if (data == "bypass") {
458 bypass = !bypass;
459 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
460 } else if (data == "debug") {
461 debug = !debug;
462 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
463 } else if (data == "expand") {
464 expand = !expand;
465 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
466 } else if (data == "syntax") {
467 syntax = !syntax;
468 *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl;
469 }
470 add_history(line);
471 ++histlines;
472 goto restart;
473 }
474 }
475
476 command_ += line;
477
478 char *begin(line), *end(line + strlen(line));
479 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
480 *nl = '\0';
481 lines.push_back(begin);
482 begin = nl + 1;
483 }
484
485 lines.push_back(begin);
486
487 free(line);
488
489 std::string code;
490
491 if (bypass)
492 code = command_;
493 else {
494 CYLocalPool pool;
495
496 std::istringstream stream(command_);
497 CYDriver driver(stream);
498
499 cy::parser parser(driver);
500 Setup(driver, parser);
501
502 if (parser.parse() != 0 || !driver.errors_.empty()) {
503 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
504 cy::position begin(error->location_.begin);
505 if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) {
506 cy::position end(error->location_.end);
507
508 if (begin.line != lines.size()) {
509 std::cerr << " | ";
510 std::cerr << lines[begin.line - 1] << std::endl;
511 }
512
513 std::cerr << "....";
514 for (size_t i(0); i != begin.column; ++i)
515 std::cerr << '.';
516 if (begin.line != end.line || begin.column == end.column)
517 std::cerr << '^';
518 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
519 std::cerr << '^';
520 std::cerr << std::endl;
521
522 std::cerr << " | ";
523 std::cerr << error->message_ << std::endl;
524
525 add_history(command_.c_str());
526 ++histlines;
527 goto restart;
528 }
529 }
530
531 driver.errors_.clear();
532
533 command_ += '\n';
534 prompt = "cy> ";
535 goto read;
536 }
537
538 if (driver.program_ == NULL)
539 goto restart;
540
541 if (client_ != -1)
542 code = command_;
543 else {
544 std::ostringstream str;
545 CYOutput out(str, options);
546 Setup(out, driver, options);
547 out << *driver.program_;
548 code = str.str();
549 }
550 }
551
552 add_history(command_.c_str());
553 ++histlines;
554
555 if (debug) {
556 Write(syntax, code.c_str(), code.size(), std::cout);
557 std::cout << std::endl;
558 }
559
560 Run(client_, syntax, code, out_, expand);
561 }
562
563 if (append_history$ != NULL) {
564 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
565 (*append_history$)(histlines, histfile);
566 } else {
567 write_history(histfile);
568 }
569
570 *out_ << std::endl;
571 }
572
573 static void *Map(const char *path, size_t *psize) {
574 int fd;
575 _syscall(fd = open(path, O_RDONLY));
576
577 struct stat stat;
578 _syscall(fstat(fd, &stat));
579 size_t size(stat.st_size);
580
581 *psize = size;
582
583 void *base;
584 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
585
586 _syscall(close(fd));
587 return base;
588 }
589
590 void InjectLibrary(pid_t pid);
591
592 int Main(int argc, char const * const argv[], char const * const envp[]) {
593 bool tty(isatty(STDIN_FILENO));
594 bool compile(false);
595 CYOptions options;
596
597 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
598
599 #ifdef CY_ATTACH
600 pid_t pid(_not(pid_t));
601 #endif
602
603 CYPool pool;
604 apr_getopt_t *state;
605 _aprcall(apr_getopt_init(&state, pool, argc, argv));
606
607 for (;;) {
608 char opt;
609 const char *arg;
610
611 apr_status_t status(apr_getopt(state,
612 "cg:n:"
613 #ifdef CY_ATTACH
614 "p:"
615 #endif
616 "s"
617 , &opt, &arg));
618
619 switch (status) {
620 case APR_EOF:
621 goto getopt;
622 case APR_BADCH:
623 case APR_BADARG:
624 fprintf(stderr,
625 "usage: cycript [-c]"
626 #ifdef CY_ATTACH
627 " [-p <pid|name>]"
628 #endif
629 " [<script> [<arg>...]]\n"
630 );
631 return 1;
632 default:
633 _aprcall(status);
634 }
635
636 switch (opt) {
637 case 'c':
638 compile = true;
639 break;
640
641 case 'g':
642 if (false);
643 else if (strcmp(arg, "rename") == 0)
644 options.verbose_ = true;
645 #if YYDEBUG
646 else if (strcmp(arg, "bison") == 0)
647 bison_ = true;
648 #endif
649 else {
650 fprintf(stderr, "invalid name for -g\n");
651 return 1;
652 }
653 break;
654
655 case 'n':
656 if (false);
657 else if (strcmp(arg, "minify") == 0)
658 pretty_ = true;
659 else {
660 fprintf(stderr, "invalid name for -n\n");
661 return 1;
662 }
663 break;
664
665 #ifdef CY_ATTACH
666 case 'p': {
667 size_t size(strlen(arg));
668 char *end;
669
670 pid = strtoul(arg, &end, 0);
671 if (arg + size != end) {
672 // XXX: arg needs to be escaped in some horrendous way of doom
673 const char *command(apr_psprintf(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg));
674
675 if (FILE *pids = popen(command, "r")) {
676 char value[32];
677 size = 0;
678
679 for (;;) {
680 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
681 if (read == 0)
682 break;
683 else {
684 size += read;
685 if (size == sizeof(value)) {
686 pid = _not(pid_t);
687 goto fail;
688 }
689 }
690 }
691
692 size:
693 if (size == 0)
694 goto fail;
695 if (value[size - 1] == '\n') {
696 --size;
697 goto size;
698 }
699
700 value[size] = '\0';
701 size = strlen(value);
702 pid = strtoul(value, &end, 0);
703 if (value + size != end) fail:
704 pid = _not(pid_t);
705 _syscall(pclose(pids));
706 }
707
708 if (pid == _not(pid_t)) {
709 fprintf(stderr, "invalid pid for -p\n");
710 return 1;
711 }
712 }
713 } break;
714 #endif
715
716 case 's':
717 strict_ = true;
718 break;
719 }
720 } getopt:;
721
722 const char *script;
723 int ind(state->ind);
724
725 #ifdef CY_ATTACH
726 if (pid != _not(pid_t) && ind < argc - 1) {
727 fprintf(stderr, "-p cannot set argv\n");
728 return 1;
729 }
730
731 if (pid != _not(pid_t) && compile) {
732 fprintf(stderr, "-p conflicts with -c\n");
733 return 1;
734 }
735 #endif
736
737 if (ind == argc)
738 script = NULL;
739 else {
740 #ifdef CY_EXECUTE
741 // XXX: const_cast?! wtf gcc :(
742 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
743 #endif
744 script = argv[ind];
745 if (strcmp(script, "-") == 0)
746 script = NULL;
747 }
748
749 #ifdef CY_ATTACH
750 if (pid != _not(pid_t) && script == NULL && !tty) {
751 fprintf(stderr, "non-terminal attaching to remote console\n");
752 return 1;
753 }
754 #endif
755
756 #ifdef CY_ATTACH
757 if (pid == _not(pid_t))
758 client_ = -1;
759 else {
760 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
761 struct sockaddr_un address;
762 memset(&address, 0, sizeof(address));
763 address.sun_family = AF_UNIX;
764
765 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
766
767 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
768 _syscall(chmod(address.sun_path, 0777));
769
770 try {
771 _syscall(listen(server, 1));
772 InjectLibrary(pid);
773 client_ = _syscall(accept(server, NULL, NULL));
774 } catch (...) {
775 // XXX: exception?
776 unlink(address.sun_path);
777 throw;
778 }
779 } catch (...) {
780 _syscall(close(server));
781 throw;
782 }
783 }
784 #else
785 client_ = -1;
786 #endif
787
788 if (script == NULL && tty)
789 Console(options);
790 else {
791 CYLocalPool pool;
792
793 char *start, *end;
794 std::istream *indirect;
795
796 if (script == NULL) {
797 start = NULL;
798 end = NULL;
799 indirect = &std::cin;
800 } else {
801 size_t size;
802 start = reinterpret_cast<char *>(Map(script, &size));
803 end = start + size;
804
805 if (size >= 2 && start[0] == '#' && start[1] == '!') {
806 start += 2;
807
808 if (void *line = memchr(start, '\n', end - start))
809 start = reinterpret_cast<char *>(line);
810 else
811 start = end;
812 }
813
814 indirect = NULL;
815 }
816
817 CYStream direct(start, end);
818 std::istream &stream(indirect == NULL ? direct : *indirect);
819 CYDriver driver(stream, script ?: "<stdin>");
820
821 cy::parser parser(driver);
822 Setup(driver, parser);
823
824 if (parser.parse() != 0 || !driver.errors_.empty()) {
825 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
826 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
827 } else if (driver.program_ != NULL)
828 if (client_ != -1) {
829 // XXX: this code means that you can't pipe to another process
830 std::string code(start, end-start);
831 Run(client_, false, code, &std::cout);
832 } else {
833 std::ostringstream str;
834 CYOutput out(str, options);
835 Setup(out, driver, options);
836 out << *driver.program_;
837 std::string code(str.str());
838 if (compile)
839 std::cout << code;
840 else
841 Run(client_, false, code, &std::cout);
842 }
843 }
844
845 return 0;
846 }
847
848 int main(int argc, char const * const argv[], char const * const envp[]) {
849 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
850
851 if (status != APR_SUCCESS) {
852 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
853 return 1;
854 } else try {
855 return Main(argc, argv, envp);
856 } catch (const CYException &error) {
857 CYPool pool;
858 fprintf(stderr, "%s\n", error.PoolCString(pool));
859 return 1;
860 }
861 }