]> git.saurik.com Git - cycript.git/blob - Console.cpp
Factored out the execution engine from the compiler.
[cycript.git] / Console.cpp
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 #include <readline/readline.h>
52 #include <readline/history.h>
53
54 #include <sys/mman.h>
55
56 #include <errno.h>
57 #include <unistd.h>
58
59 #include <sys/types.h>
60 #include <sys/stat.h>
61 #include <fcntl.h>
62
63 #include "Cycript.tab.hh"
64
65 #include <sys/types.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
68 #include <sys/un.h>
69 #include <pwd.h>
70
71 #include <apr_getopt.h>
72
73 #include <dlfcn.h>
74
75 static volatile enum {
76 Working,
77 Parsing,
78 Running,
79 Sending,
80 Waiting,
81 } mode_;
82
83 static jmp_buf ctrlc_;
84
85 static void sigint(int) {
86 switch (mode_) {
87 case Working:
88 return;
89 case Parsing:
90 longjmp(ctrlc_, 1);
91 case Running:
92 throw "*** Ctrl-C";
93 case Sending:
94 return;
95 case Waiting:
96 return;
97 }
98 }
99
100 #if YYDEBUG
101 static bool bison_;
102 #endif
103 static bool strict_;
104 static bool pretty_;
105
106 void Setup(CYDriver &driver, cy::parser &parser) {
107 #if YYDEBUG
108 if (bison_)
109 parser.set_debug_level(1);
110 #endif
111 if (strict_)
112 driver.strict_ = true;
113 }
114
115 void Setup(CYOutput &out, CYDriver &driver) {
116 out.pretty_ = pretty_;
117
118 CYContext context(driver.pool_);
119 driver.program_->Replace(context);
120 }
121
122 void Run(int client, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
123 CYPool pool;
124
125 const char *json;
126 if (client == -1) {
127 mode_ = Running;
128 #ifdef CY_EXECUTE
129 json = CYExecute(pool, data);
130 #else
131 json = NULL;
132 #endif
133 mode_ = Working;
134 if (json != NULL)
135 size = strlen(json);
136 } else {
137 mode_ = Sending;
138 CYSendAll(client, &size, sizeof(size));
139 CYSendAll(client, data, size);
140 mode_ = Waiting;
141 CYRecvAll(client, &size, sizeof(size));
142 if (size == _not(size_t))
143 json = NULL;
144 else {
145 char *temp(new(pool) char[size + 1]);
146 CYRecvAll(client, temp, size);
147 temp[size] = '\0';
148 json = temp;
149 }
150 mode_ = Working;
151 }
152
153 if (json != NULL && fout != NULL) {
154 if (!expand || json[0] != '"' && json[0] != '\'')
155 fputs(json, fout);
156 else for (size_t i(0); i != size; ++i)
157 if (json[i] != '\\')
158 fputc(json[i], fout);
159 else switch(json[++i]) {
160 case '\0': goto done;
161 case '\\': fputc('\\', fout); break;
162 case '\'': fputc('\'', fout); break;
163 case '"': fputc('"', fout); break;
164 case 'b': fputc('\b', fout); break;
165 case 'f': fputc('\f', fout); break;
166 case 'n': fputc('\n', fout); break;
167 case 'r': fputc('\r', fout); break;
168 case 't': fputc('\t', fout); break;
169 case 'v': fputc('\v', fout); break;
170 default: fputc('\\', fout); --i; break;
171 }
172
173 done:
174 fputs("\n", fout);
175 fflush(fout);
176 }
177 }
178
179 void Run(int client, std::string &code, FILE *fout = NULL, bool expand = false) {
180 Run(client, code.c_str(), code.size(), fout, expand);
181 }
182
183 int (*append_history$)(int, const char *);
184
185 static void Console(apr_pool_t *pool, int client) {
186 passwd *passwd;
187 if (const char *username = getenv("LOGNAME"))
188 passwd = getpwnam(username);
189 else
190 passwd = getpwuid(getuid());
191
192 const char *basedir(apr_psprintf(pool, "%s/.cycript", passwd->pw_dir));
193 const char *histfile(apr_psprintf(pool, "%s/history", basedir));
194 size_t histlines(0);
195
196 mkdir(basedir, 0700);
197 read_history(histfile);
198
199 bool bypass(false);
200 bool debug(false);
201 bool expand(false);
202
203 FILE *fout(stdout);
204
205 rl_bind_key('\t', rl_insert);
206
207 struct sigaction action;
208 sigemptyset(&action.sa_mask);
209 action.sa_handler = &sigint;
210 action.sa_flags = 0;
211 sigaction(SIGINT, &action, NULL);
212
213 restart: for (;;) {
214 std::string command;
215 std::vector<std::string> lines;
216
217 bool extra(false);
218 const char *prompt("cy# ");
219
220 if (setjmp(ctrlc_) != 0) {
221 mode_ = Working;
222 fputs("\n", fout);
223 fflush(fout);
224 goto restart;
225 }
226
227 read:
228 mode_ = Parsing;
229 char *line(readline(prompt));
230 mode_ = Working;
231 if (line == NULL)
232 break;
233 if (line[0] == '\0')
234 goto read;
235
236 if (!extra) {
237 extra = true;
238 if (line[0] == '?') {
239 std::string data(line + 1);
240 if (data == "bypass") {
241 bypass = !bypass;
242 fprintf(fout, "bypass == %s\n", bypass ? "true" : "false");
243 fflush(fout);
244 } else if (data == "debug") {
245 debug = !debug;
246 fprintf(fout, "debug == %s\n", debug ? "true" : "false");
247 fflush(fout);
248 } else if (data == "expand") {
249 expand = !expand;
250 fprintf(fout, "expand == %s\n", expand ? "true" : "false");
251 fflush(fout);
252 }
253 add_history(line);
254 ++histlines;
255 goto restart;
256 }
257 }
258
259 command += line;
260
261 char *begin(line), *end(line + strlen(line));
262 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
263 *nl = '\0';
264 lines.push_back(begin);
265 begin = nl + 1;
266 }
267
268 lines.push_back(begin);
269
270 free(line);
271
272 std::string code;
273
274 if (bypass)
275 code = command;
276 else {
277 CYDriver driver("");
278 cy::parser parser(driver);
279 Setup(driver, parser);
280
281 driver.data_ = command.c_str();
282 driver.size_ = command.size();
283
284 if (parser.parse() != 0 || !driver.errors_.empty()) {
285 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
286 cy::position begin(error->location_.begin);
287 if (begin.line != lines.size() || begin.column - 1 != lines.back().size() || error->warning_) {
288 cy::position end(error->location_.end);
289
290 if (begin.line != lines.size()) {
291 std::cerr << " | ";
292 std::cerr << lines[begin.line - 1] << std::endl;
293 }
294
295 std::cerr << "....";
296 for (size_t i(0); i != begin.column - 1; ++i)
297 std::cerr << '.';
298 if (begin.line != end.line || begin.column == end.column)
299 std::cerr << '^';
300 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
301 std::cerr << '^';
302 std::cerr << std::endl;
303
304 std::cerr << " | ";
305 std::cerr << error->message_ << std::endl;
306
307 add_history(command.c_str());
308 ++histlines;
309 goto restart;
310 }
311 }
312
313 driver.errors_.clear();
314
315 command += '\n';
316 prompt = "cy> ";
317 goto read;
318 }
319
320 if (driver.program_ == NULL)
321 goto restart;
322
323 if (client != -1)
324 code = command;
325 else {
326 std::ostringstream str;
327 CYOutput out(str);
328 Setup(out, driver);
329 out << *driver.program_;
330 code = str.str();
331 }
332 }
333
334 add_history(command.c_str());
335 ++histlines;
336
337 if (debug)
338 std::cout << code << std::endl;
339
340 Run(client, code, fout, expand);
341 }
342
343 if (append_history$ != NULL) {
344 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
345 (*append_history$)(histlines, histfile);
346 } else {
347 write_history(histfile);
348 }
349
350 fputs("\n", fout);
351 fflush(fout);
352 }
353
354 static void *Map(const char *path, size_t *psize) {
355 int fd;
356 _syscall(fd = open(path, O_RDONLY));
357
358 struct stat stat;
359 _syscall(fstat(fd, &stat));
360 size_t size(stat.st_size);
361
362 *psize = size;
363
364 void *base;
365 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
366
367 _syscall(close(fd));
368 return base;
369 }
370
371 void InjectLibrary(pid_t pid);
372
373 int Main(int argc, char const * const argv[], char const * const envp[]) {
374 bool tty(isatty(STDIN_FILENO));
375 bool compile(false);
376
377 append_history$ = reinterpret_cast<int (*)(int, const char *)>(dlsym(RTLD_DEFAULT, "append_history"));
378
379 #ifdef CY_ATTACH
380 pid_t pid(_not(pid_t));
381 #endif
382
383 CYPool pool;
384 apr_getopt_t *state;
385 _aprcall(apr_getopt_init(&state, pool, argc, argv));
386
387 for (;;) {
388 char opt;
389 const char *arg;
390
391 apr_status_t status(apr_getopt(state,
392 "cg:n:"
393 #ifdef CY_ATTACH
394 "p:"
395 #endif
396 "s"
397 , &opt, &arg));
398
399 switch (status) {
400 case APR_EOF:
401 goto getopt;
402 case APR_BADCH:
403 case APR_BADARG:
404 fprintf(stderr,
405 "usage: cycript [-c]"
406 #ifdef CY_ATTACH
407 " [-p <pid|name>]"
408 #endif
409 " [<script> [<arg>...]]\n"
410 );
411 return 1;
412 default:
413 _aprcall(status);
414 }
415
416 switch (opt) {
417 case 'c':
418 compile = true;
419 break;
420
421 case 'g':
422 if (false);
423 #if YYDEBUG
424 else if (strcmp(arg, "bison") == 0)
425 bison_ = true;
426 #endif
427 else {
428 fprintf(stderr, "invalid name for -g\n");
429 return 1;
430 }
431 break;
432
433 case 'n':
434 if (false);
435 else if (strcmp(arg, "minify") == 0)
436 pretty_ = true;
437 else {
438 fprintf(stderr, "invalid name for -n\n");
439 return 1;
440 }
441 break;
442
443 #ifdef CY_ATTACH
444 case 'p': {
445 size_t size(strlen(arg));
446 char *end;
447
448 pid = strtoul(arg, &end, 0);
449 if (arg + size != end) {
450 // XXX: arg needs to be escaped in some horrendous way of doom
451 const char *command(apr_psprintf(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg));
452
453 if (FILE *pids = popen(command, "r")) {
454 char value[32];
455 size = 0;
456
457 for (;;) {
458 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
459 if (read == 0)
460 break;
461 else {
462 size += read;
463 if (size == sizeof(value)) {
464 pid = _not(pid_t);
465 goto fail;
466 }
467 }
468 }
469
470 size:
471 if (size == 0)
472 goto fail;
473 if (value[size - 1] == '\n') {
474 --size;
475 goto size;
476 }
477
478 value[size] = '\0';
479 size = strlen(value);
480 pid = strtoul(value, &end, 0);
481 if (value + size != end) fail:
482 pid = _not(pid_t);
483 _syscall(pclose(pids));
484 }
485
486 if (pid == _not(pid_t)) {
487 fprintf(stderr, "invalid pid for -p\n");
488 return 1;
489 }
490 }
491 } break;
492 #endif
493
494 case 's':
495 strict_ = true;
496 break;
497 }
498 } getopt:;
499
500 const char *script;
501 int ind(state->ind);
502
503 #ifdef CY_ATTACH
504 if (pid != _not(pid_t) && ind < argc - 1) {
505 fprintf(stderr, "-p cannot set argv\n");
506 return 1;
507 }
508
509 if (pid != _not(pid_t) && compile) {
510 fprintf(stderr, "-p conflicts with -c\n");
511 return 1;
512 }
513 #endif
514
515 if (ind == argc)
516 script = NULL;
517 else {
518 #ifdef CY_EXECUTE
519 // XXX: const_cast?! wtf gcc :(
520 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
521 #endif
522 script = argv[ind];
523 if (strcmp(script, "-") == 0)
524 script = NULL;
525 }
526
527 #ifdef CY_ATTACH
528 if (pid != _not(pid_t) && script == NULL && !tty) {
529 fprintf(stderr, "non-terminal attaching to remote console\n");
530 return 1;
531 }
532 #endif
533
534 int client;
535
536 #ifdef CY_ATTACH
537 if (pid == _not(pid_t))
538 client = -1;
539 else {
540 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
541 struct sockaddr_un address;
542 memset(&address, 0, sizeof(address));
543 address.sun_family = AF_UNIX;
544
545 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
546
547 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
548 _syscall(chmod(address.sun_path, 0777));
549
550 try {
551 _syscall(listen(server, 1));
552 InjectLibrary(pid);
553 client = _syscall(accept(server, NULL, NULL));
554 } catch (...) {
555 // XXX: exception?
556 unlink(address.sun_path);
557 throw;
558 }
559 } catch (...) {
560 _syscall(close(server));
561 throw;
562 }
563 }
564 #else
565 client = -1;
566 #endif
567
568 if (script == NULL && tty)
569 Console(pool, client);
570 else {
571 CYDriver driver(script ?: "<stdin>");
572 cy::parser parser(driver);
573 Setup(driver, parser);
574
575 char *start, *end;
576
577 if (script == NULL) {
578 start = NULL;
579 end = NULL;
580
581 driver.file_ = stdin;
582 } else {
583 size_t size;
584 start = reinterpret_cast<char *>(Map(script, &size));
585 end = start + size;
586
587 if (size >= 2 && start[0] == '#' && start[1] == '!') {
588 start += 2;
589
590 if (void *line = memchr(start, '\n', end - start))
591 start = reinterpret_cast<char *>(line);
592 else
593 start = end;
594 }
595
596 driver.data_ = start;
597 driver.size_ = end - start;
598 }
599
600 if (parser.parse() != 0 || !driver.errors_.empty()) {
601 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
602 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
603 } else if (driver.program_ != NULL)
604 if (client != -1) {
605 std::string code(start, end-start);
606 Run(client, code, stdout);
607 } else {
608 std::ostringstream str;
609 CYOutput out(str);
610 Setup(out, driver);
611 out << *driver.program_;
612 std::string code(str.str());
613 if (compile)
614 std::cout << code;
615 else
616 Run(client, code, stdout);
617 }
618 }
619
620 return 0;
621 }
622
623 int main(int argc, char const * const argv[], char const * const envp[]) {
624 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
625
626 if (status != APR_SUCCESS) {
627 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
628 return 1;
629 } else try {
630 return Main(argc, argv, envp);
631 } catch (const CYException &error) {
632 CYPool pool;
633 fprintf(stderr, "%s\n", error.PoolCString(pool));
634 return 1;
635 }
636 }