]> git.saurik.com Git - cycript.git/blame - Console.cpp
Add a valueOf to Instance.
[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
de9fc71b 115void Setup(CYOutput &out, CYDriver &driver, CYOptions &options) {
11c1cc16 116 out.pretty_ = pretty_;
029bc65b 117 CYContext context(driver.pool_, options);
3b52fd1a 118 driver.program_->Replace(context);
11c1cc16
JF
119}
120
b166b11b 121void Run(int client, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
967067aa 122 CYPool pool;
b09da87b 123
967067aa 124 const char *json;
b166b11b 125 if (client == -1) {
4e39dc0b 126 mode_ = Running;
2aa77fd8 127#ifdef CY_EXECUTE
fcc64bb5 128 json = CYExecute(pool, data);
2aa77fd8
JF
129#else
130 json = NULL;
131#endif
4e39dc0b 132 mode_ = Working;
6ec85c5b
JF
133 if (json != NULL)
134 size = strlen(json);
135 } else {
4e39dc0b 136 mode_ = Sending;
b166b11b
JF
137 CYSendAll(client, &size, sizeof(size));
138 CYSendAll(client, data, size);
4e39dc0b 139 mode_ = Waiting;
b166b11b 140 CYRecvAll(client, &size, sizeof(size));
967067aa
JF
141 if (size == _not(size_t))
142 json = NULL;
143 else {
144 char *temp(new(pool) char[size + 1]);
b166b11b 145 CYRecvAll(client, temp, size);
967067aa
JF
146 temp[size] = '\0';
147 json = temp;
148 }
4e39dc0b 149 mode_ = Working;
4cf49641 150 }
b09da87b 151
967067aa 152 if (json != NULL && fout != NULL) {
6ec85c5b
JF
153 if (!expand || json[0] != '"' && json[0] != '\'')
154 fputs(json, fout);
155 else for (size_t i(0); i != size; ++i)
156 if (json[i] != '\\')
157 fputc(json[i], fout);
158 else switch(json[++i]) {
159 case '\0': goto done;
160 case '\\': fputc('\\', fout); break;
161 case '\'': fputc('\'', fout); break;
162 case '"': fputc('"', fout); break;
163 case 'b': fputc('\b', fout); break;
164 case 'f': fputc('\f', fout); break;
165 case 'n': fputc('\n', fout); break;
166 case 'r': fputc('\r', fout); break;
167 case 't': fputc('\t', fout); break;
168 case 'v': fputc('\v', fout); break;
169 default: fputc('\\', fout); --i; break;
170 }
171
172 done:
967067aa
JF
173 fputs("\n", fout);
174 fflush(fout);
b09da87b
JF
175 }
176}
177
b166b11b
JF
178void Run(int client, std::string &code, FILE *fout = NULL, bool expand = false) {
179 Run(client, code.c_str(), code.size(), fout, expand);
fcc64bb5
JF
180}
181
da858962
JF
182int (*append_history$)(int, const char *);
183
de9fc71b 184static void Console(apr_pool_t *pool, int client, CYOptions &options) {
b1589845
JF
185 passwd *passwd;
186 if (const char *username = getenv("LOGNAME"))
187 passwd = getpwnam(username);
188 else
189 passwd = getpwuid(getuid());
190
191 const char *basedir(apr_psprintf(pool, "%s/.cycript", passwd->pw_dir));
192 const char *histfile(apr_psprintf(pool, "%s/history", basedir));
193 size_t histlines(0);
194
195 mkdir(basedir, 0700);
196 read_history(histfile);
197
1f8eae40
JF
198 bool bypass(false);
199 bool debug(false);
6ec85c5b 200 bool expand(false);
1f8eae40 201
057f943f
JF
202 FILE *fout(stdout);
203
204 rl_bind_key('\t', rl_insert);
205
206 struct sigaction action;
207 sigemptyset(&action.sa_mask);
208 action.sa_handler = &sigint;
209 action.sa_flags = 0;
210 sigaction(SIGINT, &action, NULL);
211
212 restart: for (;;) {
213 std::string command;
214 std::vector<std::string> lines;
215
931b816a
JF
216 bool extra(false);
217 const char *prompt("cy# ");
218
057f943f 219 if (setjmp(ctrlc_) != 0) {
4e39dc0b 220 mode_ = Working;
057f943f
JF
221 fputs("\n", fout);
222 fflush(fout);
223 goto restart;
224 }
225
057f943f 226 read:
4e39dc0b 227 mode_ = Parsing;
057f943f 228 char *line(readline(prompt));
4e39dc0b 229 mode_ = Working;
057f943f
JF
230 if (line == NULL)
231 break;
67f1fc6b
JF
232 if (line[0] == '\0')
233 goto read;
931b816a
JF
234
235 if (!extra) {
236 extra = true;
6ec85c5b 237 if (line[0] == '?') {
1f8eae40
JF
238 std::string data(line + 1);
239 if (data == "bypass") {
240 bypass = !bypass;
241 fprintf(fout, "bypass == %s\n", bypass ? "true" : "false");
242 fflush(fout);
243 } else if (data == "debug") {
244 debug = !debug;
245 fprintf(fout, "debug == %s\n", debug ? "true" : "false");
246 fflush(fout);
6ec85c5b
JF
247 } else if (data == "expand") {
248 expand = !expand;
249 fprintf(fout, "expand == %s\n", expand ? "true" : "false");
250 fflush(fout);
1f8eae40 251 }
d35a3b07 252 add_history(line);
b1589845 253 ++histlines;
931b816a
JF
254 goto restart;
255 }
256 }
257
057f943f 258 command += line;
e818f0e0
JF
259
260 char *begin(line), *end(line + strlen(line));
261 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
262 *nl = '\0';
263 lines.push_back(begin);
264 begin = nl + 1;
265 }
266
267 lines.push_back(begin);
268
057f943f
JF
269 free(line);
270
1f8eae40
JF
271 std::string code;
272
273 if (bypass)
274 code = command;
275 else {
276 CYDriver driver("");
277 cy::parser parser(driver);
b10bd496 278 Setup(driver, parser);
1f8eae40
JF
279
280 driver.data_ = command.c_str();
281 driver.size_ = command.size();
282
283 if (parser.parse() != 0 || !driver.errors_.empty()) {
f0360d51
JF
284 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
285 cy::position begin(error->location_.begin);
b10bd496 286 if (begin.line != lines.size() || begin.column - 1 != lines.back().size() || error->warning_) {
f0360d51 287 cy::position end(error->location_.end);
48e3be8a 288
f0360d51
JF
289 if (begin.line != lines.size()) {
290 std::cerr << " | ";
291 std::cerr << lines[begin.line - 1] << std::endl;
292 }
48e3be8a 293
c52a09b8 294 std::cerr << "....";
f0360d51
JF
295 for (size_t i(0); i != begin.column - 1; ++i)
296 std::cerr << '.';
48e3be8a 297 if (begin.line != end.line || begin.column == end.column)
f0360d51
JF
298 std::cerr << '^';
299 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
300 std::cerr << '^';
301 std::cerr << std::endl;
48e3be8a 302
f0360d51
JF
303 std::cerr << " | ";
304 std::cerr << error->message_ << std::endl;
48e3be8a 305
1f8eae40 306 add_history(command.c_str());
b1589845 307 ++histlines;
1f8eae40
JF
308 goto restart;
309 }
310 }
057f943f 311
1f8eae40 312 driver.errors_.clear();
057f943f 313
1f8eae40
JF
314 command += '\n';
315 prompt = "cy> ";
316 goto read;
057f943f
JF
317 }
318
b10bd496 319 if (driver.program_ == NULL)
1f8eae40 320 goto restart;
057f943f 321
b166b11b 322 if (client != -1)
967067aa
JF
323 code = command;
324 else {
325 std::ostringstream str;
029bc65b 326 CYOutput out(str, options);
de9fc71b 327 Setup(out, driver, options);
3b52fd1a 328 out << *driver.program_;
967067aa
JF
329 code = str.str();
330 }
057f943f
JF
331 }
332
057f943f 333 add_history(command.c_str());
b1589845 334 ++histlines;
057f943f 335
1f8eae40
JF
336 if (debug)
337 std::cout << code << std::endl;
057f943f 338
b166b11b 339 Run(client, code, fout, expand);
b09da87b 340 }
057f943f 341
da858962
JF
342 if (append_history$ != NULL) {
343 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
344 (*append_history$)(histlines, histfile);
345 } else {
346 write_history(histfile);
347 }
b1589845 348
b09da87b
JF
349 fputs("\n", fout);
350 fflush(fout);
351}
057f943f 352
579ed526 353static void *Map(const char *path, size_t *psize) {
b09da87b
JF
354 int fd;
355 _syscall(fd = open(path, O_RDONLY));
057f943f 356
b09da87b
JF
357 struct stat stat;
358 _syscall(fstat(fd, &stat));
359 size_t size(stat.st_size);
057f943f 360
b09da87b 361 *psize = size;
057f943f 362
b09da87b
JF
363 void *base;
364 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
057f943f 365
b09da87b
JF
366 _syscall(close(fd));
367 return base;
368}
057f943f 369
b6961e53 370void InjectLibrary(pid_t pid);
06edab7d 371
b6961e53 372int Main(int argc, char const * const argv[], char const * const envp[]) {
48e3be8a 373 bool tty(isatty(STDIN_FILENO));
75b0a457 374 bool compile(false);
de9fc71b 375 CYOptions options;
967067aa 376
da858962
JF
377 append_history$ = reinterpret_cast<int (*)(int, const char *)>(dlsym(RTLD_DEFAULT, "append_history"));
378
2aa77fd8
JF
379#ifdef CY_ATTACH
380 pid_t pid(_not(pid_t));
381#endif
382
06edab7d
JF
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:"
2aa77fd8 393#ifdef CY_ATTACH
06edab7d 394 "p:"
2aa77fd8 395#endif
06edab7d
JF
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]"
2aa77fd8 406#ifdef CY_ATTACH
69caa5be 407 " [-p <pid|name>]"
2aa77fd8 408#endif
06edab7d
JF
409 " [<script> [<arg>...]]\n"
410 );
411 return 1;
412 default:
413 _aprcall(status);
414 }
967067aa 415
06edab7d
JF
416 switch (opt) {
417 case 'c':
418 compile = true;
419 break;
75b0a457 420
06edab7d
JF
421 case 'g':
422 if (false);
de9fc71b
JF
423 else if (strcmp(arg, "rename") == 0)
424 options.verbose_ = true;
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)
de9fc71b 571 Console(pool, client, options);
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 611 CYOutput out(str, options);
de9fc71b 612 Setup(out, driver, options);
3b52fd1a 613 out << *driver.program_;
fcc64bb5 614 std::string code(str.str());
75b0a457
JF
615 if (compile)
616 std::cout << code;
98ea05a3 617 else
b166b11b 618 Run(client, code, stdout);
fcc64bb5 619 }
057f943f 620 }
62ca2b82 621
057f943f 622 return 0;
62ca2b82 623}
b6961e53
JF
624
625int main(int argc, char const * const argv[], char const * const envp[]) {
626 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
da858962 627
b6961e53
JF
628 if (status != APR_SUCCESS) {
629 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
630 return 1;
631 } else try {
632 return Main(argc, argv, envp);
633 } catch (const CYException &error) {
634 CYPool pool;
635 fprintf(stderr, "%s\n", error.PoolCString(pool));
636 return 1;
637 }
638}