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