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