]> git.saurik.com Git - cycript.git/blob - Console.cpp
Proper install/uninstall targets; don't use dpkg in test target thanks to libtool...
[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, CYOptions &options) {
116 out.pretty_ = pretty_;
117 CYContext context(driver.pool_, options);
118 driver.program_->Replace(context);
119 }
120
121 void Run(int client, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
122 CYPool pool;
123
124 const char *json;
125 if (client == -1) {
126 mode_ = Running;
127 #ifdef CY_EXECUTE
128 json = CYExecute(pool, data);
129 #else
130 json = NULL;
131 #endif
132 mode_ = Working;
133 if (json != NULL)
134 size = strlen(json);
135 } else {
136 mode_ = Sending;
137 CYSendAll(client, &size, sizeof(size));
138 CYSendAll(client, data, size);
139 mode_ = Waiting;
140 CYRecvAll(client, &size, sizeof(size));
141 if (size == _not(size_t))
142 json = NULL;
143 else {
144 char *temp(new(pool) char[size + 1]);
145 CYRecvAll(client, temp, size);
146 temp[size] = '\0';
147 json = temp;
148 }
149 mode_ = Working;
150 }
151
152 if (json != NULL && fout != NULL) {
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:
173 fputs("\n", fout);
174 fflush(fout);
175 }
176 }
177
178 void Run(int client, std::string &code, FILE *fout = NULL, bool expand = false) {
179 Run(client, code.c_str(), code.size(), fout, expand);
180 }
181
182 int (*append_history$)(int, const char *);
183
184 static void Console(apr_pool_t *pool, int client, CYOptions &options) {
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
198 bool bypass(false);
199 bool debug(false);
200 bool expand(false);
201
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
216 bool extra(false);
217 const char *prompt("cy# ");
218
219 if (setjmp(ctrlc_) != 0) {
220 mode_ = Working;
221 fputs("\n", fout);
222 fflush(fout);
223 goto restart;
224 }
225
226 read:
227 mode_ = Parsing;
228 char *line(readline(prompt));
229 mode_ = Working;
230 if (line == NULL)
231 break;
232 if (line[0] == '\0')
233 goto read;
234
235 if (!extra) {
236 extra = true;
237 if (line[0] == '?') {
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);
247 } else if (data == "expand") {
248 expand = !expand;
249 fprintf(fout, "expand == %s\n", expand ? "true" : "false");
250 fflush(fout);
251 }
252 add_history(line);
253 ++histlines;
254 goto restart;
255 }
256 }
257
258 command += line;
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
269 free(line);
270
271 std::string code;
272
273 if (bypass)
274 code = command;
275 else {
276 CYDriver driver("");
277 cy::parser parser(driver);
278 Setup(driver, parser);
279
280 driver.data_ = command.c_str();
281 driver.size_ = command.size();
282
283 if (parser.parse() != 0 || !driver.errors_.empty()) {
284 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
285 cy::position begin(error->location_.begin);
286 if (begin.line != lines.size() || begin.column - 1 != lines.back().size() || error->warning_) {
287 cy::position end(error->location_.end);
288
289 if (begin.line != lines.size()) {
290 std::cerr << " | ";
291 std::cerr << lines[begin.line - 1] << std::endl;
292 }
293
294 std::cerr << "....";
295 for (size_t i(0); i != begin.column - 1; ++i)
296 std::cerr << '.';
297 if (begin.line != end.line || begin.column == end.column)
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;
302
303 std::cerr << " | ";
304 std::cerr << error->message_ << std::endl;
305
306 add_history(command.c_str());
307 ++histlines;
308 goto restart;
309 }
310 }
311
312 driver.errors_.clear();
313
314 command += '\n';
315 prompt = "cy> ";
316 goto read;
317 }
318
319 if (driver.program_ == NULL)
320 goto restart;
321
322 if (client != -1)
323 code = command;
324 else {
325 std::ostringstream str;
326 CYOutput out(str, options);
327 Setup(out, driver, options);
328 out << *driver.program_;
329 code = str.str();
330 }
331 }
332
333 add_history(command.c_str());
334 ++histlines;
335
336 if (debug)
337 std::cout << code << std::endl;
338
339 Run(client, code, fout, expand);
340 }
341
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 }
348
349 fputs("\n", fout);
350 fflush(fout);
351 }
352
353 static void *Map(const char *path, size_t *psize) {
354 int fd;
355 _syscall(fd = open(path, O_RDONLY));
356
357 struct stat stat;
358 _syscall(fstat(fd, &stat));
359 size_t size(stat.st_size);
360
361 *psize = size;
362
363 void *base;
364 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
365
366 _syscall(close(fd));
367 return base;
368 }
369
370 void InjectLibrary(pid_t pid);
371
372 int Main(int argc, char const * const argv[], char const * const envp[]) {
373 bool tty(isatty(STDIN_FILENO));
374 bool compile(false);
375 CYOptions options;
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 else if (strcmp(arg, "rename") == 0)
424 options.verbose_ = true;
425 #if YYDEBUG
426 else if (strcmp(arg, "bison") == 0)
427 bison_ = true;
428 #endif
429 else {
430 fprintf(stderr, "invalid name for -g\n");
431 return 1;
432 }
433 break;
434
435 case 'n':
436 if (false);
437 else if (strcmp(arg, "minify") == 0)
438 pretty_ = true;
439 else {
440 fprintf(stderr, "invalid name for -n\n");
441 return 1;
442 }
443 break;
444
445 #ifdef CY_ATTACH
446 case 'p': {
447 size_t size(strlen(arg));
448 char *end;
449
450 pid = strtoul(arg, &end, 0);
451 if (arg + size != end) {
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);
467 goto fail;
468 }
469 }
470 }
471
472 size:
473 if (size == 0)
474 goto fail;
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);
483 if (value + size != end) fail:
484 pid = _not(pid_t);
485 _syscall(pclose(pids));
486 }
487
488 if (pid == _not(pid_t)) {
489 fprintf(stderr, "invalid pid for -p\n");
490 return 1;
491 }
492 }
493 } break;
494 #endif
495
496 case 's':
497 strict_ = true;
498 break;
499 }
500 } getopt:;
501
502 const char *script;
503 int ind(state->ind);
504
505 #ifdef CY_ATTACH
506 if (pid != _not(pid_t) && ind < argc - 1) {
507 fprintf(stderr, "-p cannot set argv\n");
508 return 1;
509 }
510
511 if (pid != _not(pid_t) && compile) {
512 fprintf(stderr, "-p conflicts with -c\n");
513 return 1;
514 }
515 #endif
516
517 if (ind == argc)
518 script = NULL;
519 else {
520 #ifdef CY_EXECUTE
521 // XXX: const_cast?! wtf gcc :(
522 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
523 #endif
524 script = argv[ind];
525 if (strcmp(script, "-") == 0)
526 script = NULL;
527 }
528
529 #ifdef CY_ATTACH
530 if (pid != _not(pid_t) && script == NULL && !tty) {
531 fprintf(stderr, "non-terminal attaching to remote console\n");
532 return 1;
533 }
534 #endif
535
536 int client;
537
538 #ifdef CY_ATTACH
539 if (pid == _not(pid_t))
540 client = -1;
541 else {
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));
563 throw;
564 }
565 }
566 #else
567 client = -1;
568 #endif
569
570 if (script == NULL && tty)
571 Console(pool, client, options);
572 else {
573 CYDriver driver(script ?: "<stdin>");
574 cy::parser parser(driver);
575 Setup(driver, parser);
576
577 char *start, *end;
578
579 if (script == NULL) {
580 start = NULL;
581 end = NULL;
582
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;
591
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 }
601
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;
605 } else if (driver.program_ != NULL)
606 if (client != -1) {
607 std::string code(start, end-start);
608 Run(client, code, stdout);
609 } else {
610 std::ostringstream str;
611 CYOutput out(str, options);
612 Setup(out, driver, options);
613 out << *driver.program_;
614 std::string code(str.str());
615 if (compile)
616 std::cout << code;
617 else
618 Run(client, code, stdout);
619 }
620 }
621
622 return 0;
623 }
624
625 int main(int argc, char const * const argv[], char const * const envp[]) {
626 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
627
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 }