]> git.saurik.com Git - cycript.git/blame_incremental - Console.cpp
Port Objective-C/Replace to C++.
[cycript.git] / Console.cpp
... / ...
CommitLineData
1/* Cycript - Inlining/Optimizing JavaScript Compiler
2 * Copyright (C) 2009 Jay Freeman (saurik)
3*/
4
5/* Modified BSD License {{{ */
6/*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37*/
38/* }}} */
39
40#include "cycript.hpp"
41
42#ifdef CY_EXECUTE
43#include "JavaScript.hpp"
44#endif
45
46#include <cstdio>
47#include <sstream>
48
49#include <setjmp.h>
50
51#ifdef HAVE_READLINE_H
52#include <readline.h>
53#else
54#include <readline/readline.h>
55#endif
56
57#ifdef HAVE_HISTORY_H
58#include <history.h>
59#else
60#include <readline/history.h>
61#endif
62
63#include <sys/mman.h>
64
65#include <errno.h>
66#include <unistd.h>
67
68#include <sys/types.h>
69#include <sys/stat.h>
70#include <fcntl.h>
71
72#include "Cycript.tab.hh"
73
74#include <sys/types.h>
75#include <sys/socket.h>
76#include <netinet/in.h>
77#include <sys/un.h>
78#include <pwd.h>
79
80#include <apr_getopt.h>
81
82#include <dlfcn.h>
83
84#include "Replace.hpp"
85
86static volatile enum {
87 Working,
88 Parsing,
89 Running,
90 Sending,
91 Waiting,
92} mode_;
93
94static jmp_buf ctrlc_;
95
96static void sigint(int) {
97 switch (mode_) {
98 case Working:
99 return;
100 case Parsing:
101 longjmp(ctrlc_, 1);
102 case Running:
103 throw "*** Ctrl-C";
104 case Sending:
105 return;
106 case Waiting:
107 return;
108 }
109}
110
111#if YYDEBUG
112static bool bison_;
113#endif
114static bool strict_;
115static bool pretty_;
116
117void Setup(CYDriver &driver, cy::parser &parser) {
118#if YYDEBUG
119 if (bison_)
120 parser.set_debug_level(1);
121#endif
122 if (strict_)
123 driver.strict_ = true;
124}
125
126void Setup(CYOutput &out, CYDriver &driver, CYOptions &options) {
127 out.pretty_ = pretty_;
128 CYContext context(options);
129 driver.program_->Replace(context);
130}
131
132static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
133 const char *json;
134 size_t size;
135
136 if (client == -1) {
137 mode_ = Running;
138#ifdef CY_EXECUTE
139 json = CYExecute(pool, code);
140#else
141 json = NULL;
142#endif
143 mode_ = Working;
144 if (json == NULL)
145 size = 0;
146 else
147 size = strlen(json);
148 } else {
149 mode_ = Sending;
150 size = code.size;
151 CYSendAll(client, &size, sizeof(size));
152 CYSendAll(client, code.data, code.size);
153 mode_ = Waiting;
154 CYRecvAll(client, &size, sizeof(size));
155 if (size == _not(size_t))
156 json = NULL;
157 else {
158 char *temp(new(pool) char[size + 1]);
159 CYRecvAll(client, temp, size);
160 temp[size] = '\0';
161 json = temp;
162 }
163 mode_ = Working;
164 }
165
166 return CYUTF8String(json, size);
167}
168
169static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
170 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
171}
172
173FILE *fout_;
174
175static void Output(CYUTF8String json, FILE *fout, bool expand = false) {
176 const char *data(json.data);
177 size_t size(json.size);
178
179 if (data == NULL || fout == NULL)
180 return;
181
182 if (!expand || data[0] != '"' && data[0] != '\'')
183 fputs(data, fout);
184 else for (size_t i(0); i != size; ++i)
185 if (data[i] != '\\')
186 fputc(data[i], fout);
187 else switch(data[++i]) {
188 case '\0': goto done;
189 case '\\': fputc('\\', fout); break;
190 case '\'': fputc('\'', fout); break;
191 case '"': fputc('"', fout); break;
192 case 'b': fputc('\b', fout); break;
193 case 'f': fputc('\f', fout); break;
194 case 'n': fputc('\n', fout); break;
195 case 'r': fputc('\r', fout); break;
196 case 't': fputc('\t', fout); break;
197 case 'v': fputc('\v', fout); break;
198 default: fputc('\\', fout); --i; break;
199 }
200
201 done:
202 fputs("\n", fout);
203 fflush(fout);
204}
205
206static void Run(int client, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
207 CYPool pool;
208 Output(Run(pool, client, CYUTF8String(data, size)), fout, expand);
209}
210
211static void Run(int client, std::string &code, FILE *fout = NULL, bool expand = false) {
212 Run(client, code.c_str(), code.size(), fout, expand);
213}
214
215int (*append_history$)(int, const char *);
216
217static std::string command_;
218
219static CYExpression *ParseExpression(CYUTF8String code) {
220 std::ostringstream str;
221 str << '(' << code << ')';
222 std::string string(str.str());
223
224 CYDriver driver;
225 driver.data_ = string.c_str();
226 driver.size_ = string.size();
227
228 cy::parser parser(driver);
229 Setup(driver, parser);
230
231 if (parser.parse() != 0 || !driver.errors_.empty())
232 _assert(false);
233
234 CYExpress *express(dynamic_cast<CYExpress *>(driver.program_->statements_));
235 _assert(express != NULL);
236 return express->expression_;
237}
238
239static int client_;
240
241static char **Complete(const char *word, int start, int end) {
242 rl_attempted_completion_over = TRUE;
243
244 CYLocalPool pool;
245 CYDriver driver;
246 cy::parser parser(driver);
247 Setup(driver, parser);
248
249 std::string line(rl_line_buffer, start);
250 std::string command(command_ + line);
251
252 driver.data_ = command.c_str();
253 driver.size_ = command.size();
254
255 driver.auto_ = true;
256
257 if (parser.parse() != 0 || !driver.errors_.empty())
258 return NULL;
259
260 if (driver.mode_ == CYDriver::AutoNone)
261 return NULL;
262
263 CYExpression *expression;
264
265 CYOptions options;
266 CYContext context(options);
267
268 std::ostringstream prefix;
269
270 switch (driver.mode_) {
271 case CYDriver::AutoPrimary:
272 expression = $ CYThis();
273 break;
274
275 case CYDriver::AutoDirect:
276 expression = driver.context_;
277 break;
278
279 case CYDriver::AutoIndirect:
280 expression = $ CYIndirect(driver.context_);
281 break;
282
283 case CYDriver::AutoMessage: {
284 CYDriver::Context &thing(driver.contexts_.back());
285 expression = $M($M($ CYIndirect(thing.context_), $S("isa")), $S("messages"));
286 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
287 prefix << (*part)->word_ << ':';
288 } break;
289
290 default:
291 _assert(false);
292 }
293
294 std::string begin(prefix.str());
295
296 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
297 " function(object, prefix, word) {\n"
298 " var names = [];\n"
299 " var pattern = '^' + prefix + word;\n"
300 " var length = prefix.length;\n"
301 " for (name in object)\n"
302 " if (name.match(pattern) != null)\n"
303 " names.push(name.substr(length));\n"
304 " return names;\n"
305 " }\n"
306 ), expression, $S(begin.c_str()), $S(word))));
307
308 driver.program_->Replace(context);
309
310 std::ostringstream str;
311 CYOutput out(str, options);
312 out << *driver.program_;
313
314 std::string code(str.str());
315 CYUTF8String json(Run(pool, client_, code));
316
317 CYExpression *result(ParseExpression(json));
318 CYArray *array(dynamic_cast<CYArray *>(result));
319
320 if (array == NULL) {
321 fprintf(fout_, "\n");
322 Output(json, fout_);
323 rl_forced_update_display();
324 return NULL;
325 }
326
327 // XXX: use an std::set?
328 typedef std::vector<std::string> Completions;
329 Completions completions;
330
331 std::string common;
332 bool rest(false);
333
334 for (CYElement *element(array->elements_); element != NULL; element = element->next_) {
335 CYString *string(dynamic_cast<CYString *>(element->value_));
336 _assert(string != NULL);
337
338 std::string completion;
339 if (string->size_ != 0)
340 completion.assign(string->value_, string->size_);
341 else if (driver.mode_ == CYDriver::AutoMessage)
342 completion = "]";
343 else
344 continue;
345
346 completions.push_back(completion);
347
348 if (!rest) {
349 common = completion;
350 rest = true;
351 } else {
352 size_t limit(completion.size()), size(common.size());
353 if (size > limit)
354 common = common.substr(0, limit);
355 else
356 limit = size;
357 for (limit = 0; limit != size; ++limit)
358 if (common[limit] != completion[limit])
359 break;
360 if (limit != size)
361 common = common.substr(0, limit);
362 }
363 }
364
365 size_t count(completions.size());
366 if (count == 0)
367 return NULL;
368
369 size_t colon(common.find(':'));
370 if (colon != std::string::npos)
371 common = common.substr(0, colon + 1);
372 if (completions.size() == 1)
373 common += ' ';
374
375 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
376
377 results[0] = strdup(common.c_str());
378 size_t index(0);
379 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
380 results[++index] = strdup(i->c_str());
381 results[count + 1] = NULL;
382
383 return results;
384}
385
386// need char *, not const char *
387static char name_[] = "cycript";
388static char break_[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
389
390static void Console(CYOptions &options) {
391 CYPool pool;
392
393 passwd *passwd;
394 if (const char *username = getenv("LOGNAME"))
395 passwd = getpwnam(username);
396 else
397 passwd = getpwuid(getuid());
398
399 const char *basedir(apr_psprintf(pool, "%s/.cycript", passwd->pw_dir));
400 const char *histfile(apr_psprintf(pool, "%s/history", basedir));
401 size_t histlines(0);
402
403 rl_initialize();
404 rl_readline_name = name_;
405
406 mkdir(basedir, 0700);
407 read_history(histfile);
408
409 bool bypass(false);
410 bool debug(false);
411 bool expand(false);
412
413 fout_ = stdout;
414
415 // rl_completer_word_break_characters is broken in libedit
416 rl_basic_word_break_characters = break_;
417
418 rl_completer_word_break_characters = break_;
419 rl_attempted_completion_function = &Complete;
420 rl_bind_key('\t', rl_complete);
421
422 struct sigaction action;
423 sigemptyset(&action.sa_mask);
424 action.sa_handler = &sigint;
425 action.sa_flags = 0;
426 sigaction(SIGINT, &action, NULL);
427
428 restart: for (;;) {
429 command_.clear();
430 std::vector<std::string> lines;
431
432 bool extra(false);
433 const char *prompt("cy# ");
434
435 if (setjmp(ctrlc_) != 0) {
436 mode_ = Working;
437 fputs("\n", fout_);
438 fflush(fout_);
439 goto restart;
440 }
441
442 read:
443 mode_ = Parsing;
444 char *line(readline(prompt));
445 mode_ = Working;
446 if (line == NULL)
447 break;
448 if (line[0] == '\0')
449 goto read;
450
451 if (!extra) {
452 extra = true;
453 if (line[0] == '?') {
454 std::string data(line + 1);
455 if (data == "bypass") {
456 bypass = !bypass;
457 fprintf(fout_, "bypass == %s\n", bypass ? "true" : "false");
458 fflush(fout_);
459 } else if (data == "debug") {
460 debug = !debug;
461 fprintf(fout_, "debug == %s\n", debug ? "true" : "false");
462 fflush(fout_);
463 } else if (data == "expand") {
464 expand = !expand;
465 fprintf(fout_, "expand == %s\n", expand ? "true" : "false");
466 fflush(fout_);
467 }
468 add_history(line);
469 ++histlines;
470 goto restart;
471 }
472 }
473
474 command_ += line;
475
476 char *begin(line), *end(line + strlen(line));
477 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
478 *nl = '\0';
479 lines.push_back(begin);
480 begin = nl + 1;
481 }
482
483 lines.push_back(begin);
484
485 free(line);
486
487 std::string code;
488
489 if (bypass)
490 code = command_;
491 else {
492 CYLocalPool pool;
493 CYDriver driver;
494 cy::parser parser(driver);
495 Setup(driver, parser);
496
497 driver.data_ = command_.c_str();
498 driver.size_ = command_.size();
499
500 if (parser.parse() != 0 || !driver.errors_.empty()) {
501 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
502 cy::position begin(error->location_.begin);
503 if (begin.line != lines.size() || begin.column - 1 != lines.back().size() || error->warning_) {
504 cy::position end(error->location_.end);
505
506 if (begin.line != lines.size()) {
507 std::cerr << " | ";
508 std::cerr << lines[begin.line - 1] << std::endl;
509 }
510
511 std::cerr << "....";
512 for (size_t i(0); i != begin.column - 1; ++i)
513 std::cerr << '.';
514 if (begin.line != end.line || begin.column == end.column)
515 std::cerr << '^';
516 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
517 std::cerr << '^';
518 std::cerr << std::endl;
519
520 std::cerr << " | ";
521 std::cerr << error->message_ << std::endl;
522
523 add_history(command_.c_str());
524 ++histlines;
525 goto restart;
526 }
527 }
528
529 driver.errors_.clear();
530
531 command_ += '\n';
532 prompt = "cy> ";
533 goto read;
534 }
535
536 if (driver.program_ == NULL)
537 goto restart;
538
539 if (client_ != -1)
540 code = command_;
541 else {
542 std::ostringstream str;
543 CYOutput out(str, options);
544 Setup(out, driver, options);
545 out << *driver.program_;
546 code = str.str();
547 }
548 }
549
550 add_history(command_.c_str());
551 ++histlines;
552
553 if (debug)
554 std::cout << code << std::endl;
555
556 Run(client_, code, fout_, expand);
557 }
558
559 if (append_history$ != NULL) {
560 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
561 (*append_history$)(histlines, histfile);
562 } else {
563 write_history(histfile);
564 }
565
566 fputs("\n", fout_);
567 fflush(fout_);
568}
569
570static void *Map(const char *path, size_t *psize) {
571 int fd;
572 _syscall(fd = open(path, O_RDONLY));
573
574 struct stat stat;
575 _syscall(fstat(fd, &stat));
576 size_t size(stat.st_size);
577
578 *psize = size;
579
580 void *base;
581 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
582
583 _syscall(close(fd));
584 return base;
585}
586
587void InjectLibrary(pid_t pid);
588
589int Main(int argc, char const * const argv[], char const * const envp[]) {
590 bool tty(isatty(STDIN_FILENO));
591 bool compile(false);
592 CYOptions options;
593
594 append_history$ = reinterpret_cast<int (*)(int, const char *)>(dlsym(RTLD_DEFAULT, "append_history"));
595
596#ifdef CY_ATTACH
597 pid_t pid(_not(pid_t));
598#endif
599
600 CYPool pool;
601 apr_getopt_t *state;
602 _aprcall(apr_getopt_init(&state, pool, argc, argv));
603
604 for (;;) {
605 char opt;
606 const char *arg;
607
608 apr_status_t status(apr_getopt(state,
609 "cg:n:"
610#ifdef CY_ATTACH
611 "p:"
612#endif
613 "s"
614 , &opt, &arg));
615
616 switch (status) {
617 case APR_EOF:
618 goto getopt;
619 case APR_BADCH:
620 case APR_BADARG:
621 fprintf(stderr,
622 "usage: cycript [-c]"
623#ifdef CY_ATTACH
624 " [-p <pid|name>]"
625#endif
626 " [<script> [<arg>...]]\n"
627 );
628 return 1;
629 default:
630 _aprcall(status);
631 }
632
633 switch (opt) {
634 case 'c':
635 compile = true;
636 break;
637
638 case 'g':
639 if (false);
640 else if (strcmp(arg, "rename") == 0)
641 options.verbose_ = true;
642#if YYDEBUG
643 else if (strcmp(arg, "bison") == 0)
644 bison_ = true;
645#endif
646 else {
647 fprintf(stderr, "invalid name for -g\n");
648 return 1;
649 }
650 break;
651
652 case 'n':
653 if (false);
654 else if (strcmp(arg, "minify") == 0)
655 pretty_ = true;
656 else {
657 fprintf(stderr, "invalid name for -n\n");
658 return 1;
659 }
660 break;
661
662#ifdef CY_ATTACH
663 case 'p': {
664 size_t size(strlen(arg));
665 char *end;
666
667 pid = strtoul(arg, &end, 0);
668 if (arg + size != end) {
669 // XXX: arg needs to be escaped in some horrendous way of doom
670 const char *command(apr_psprintf(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg));
671
672 if (FILE *pids = popen(command, "r")) {
673 char value[32];
674 size = 0;
675
676 for (;;) {
677 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
678 if (read == 0)
679 break;
680 else {
681 size += read;
682 if (size == sizeof(value)) {
683 pid = _not(pid_t);
684 goto fail;
685 }
686 }
687 }
688
689 size:
690 if (size == 0)
691 goto fail;
692 if (value[size - 1] == '\n') {
693 --size;
694 goto size;
695 }
696
697 value[size] = '\0';
698 size = strlen(value);
699 pid = strtoul(value, &end, 0);
700 if (value + size != end) fail:
701 pid = _not(pid_t);
702 _syscall(pclose(pids));
703 }
704
705 if (pid == _not(pid_t)) {
706 fprintf(stderr, "invalid pid for -p\n");
707 return 1;
708 }
709 }
710 } break;
711#endif
712
713 case 's':
714 strict_ = true;
715 break;
716 }
717 } getopt:;
718
719 const char *script;
720 int ind(state->ind);
721
722#ifdef CY_ATTACH
723 if (pid != _not(pid_t) && ind < argc - 1) {
724 fprintf(stderr, "-p cannot set argv\n");
725 return 1;
726 }
727
728 if (pid != _not(pid_t) && compile) {
729 fprintf(stderr, "-p conflicts with -c\n");
730 return 1;
731 }
732#endif
733
734 if (ind == argc)
735 script = NULL;
736 else {
737#ifdef CY_EXECUTE
738 // XXX: const_cast?! wtf gcc :(
739 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
740#endif
741 script = argv[ind];
742 if (strcmp(script, "-") == 0)
743 script = NULL;
744 }
745
746#ifdef CY_ATTACH
747 if (pid != _not(pid_t) && script == NULL && !tty) {
748 fprintf(stderr, "non-terminal attaching to remote console\n");
749 return 1;
750 }
751#endif
752
753#ifdef CY_ATTACH
754 if (pid == _not(pid_t))
755 client_ = -1;
756 else {
757 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
758 struct sockaddr_un address;
759 memset(&address, 0, sizeof(address));
760 address.sun_family = AF_UNIX;
761
762 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
763
764 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
765 _syscall(chmod(address.sun_path, 0777));
766
767 try {
768 _syscall(listen(server, 1));
769 InjectLibrary(pid);
770 client_ = _syscall(accept(server, NULL, NULL));
771 } catch (...) {
772 // XXX: exception?
773 unlink(address.sun_path);
774 throw;
775 }
776 } catch (...) {
777 _syscall(close(server));
778 throw;
779 }
780 }
781#else
782 client_ = -1;
783#endif
784
785 if (script == NULL && tty)
786 Console(options);
787 else {
788 CYLocalPool pool;
789 CYDriver driver(script ?: "<stdin>");
790 cy::parser parser(driver);
791 Setup(driver, parser);
792
793 char *start, *end;
794
795 if (script == NULL) {
796 start = NULL;
797 end = NULL;
798
799 driver.file_ = stdin;
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 driver.data_ = start;
815 driver.size_ = end - start;
816 }
817
818 if (parser.parse() != 0 || !driver.errors_.empty()) {
819 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
820 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
821 } else if (driver.program_ != NULL)
822 if (client_ != -1) {
823 std::string code(start, end-start);
824 Run(client_, code, stdout);
825 } else {
826 std::ostringstream str;
827 CYOutput out(str, options);
828 Setup(out, driver, options);
829 out << *driver.program_;
830 std::string code(str.str());
831 if (compile)
832 std::cout << code;
833 else
834 Run(client_, code, stdout);
835 }
836 }
837
838 return 0;
839}
840
841int main(int argc, char const * const argv[], char const * const envp[]) {
842 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
843
844 if (status != APR_SUCCESS) {
845 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
846 return 1;
847 } else try {
848 return Main(argc, argv, envp);
849 } catch (const CYException &error) {
850 CYPool pool;
851 fprintf(stderr, "%s\n", error.PoolCString(pool));
852 return 1;
853 }
854}