]> git.saurik.com Git - cycript.git/blob - Console.cpp
Fixed a simple build error on Mac OS X.
[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 CYOptions options;
119 CYContext context(driver.pool_, options);
120 driver.program_->Replace(context);
121 }
122
123 void Run(int client, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
124 CYPool pool;
125
126 const char *json;
127 if (client == -1) {
128 mode_ = Running;
129 #ifdef CY_EXECUTE
130 json = CYExecute(pool, data);
131 #else
132 json = NULL;
133 #endif
134 mode_ = Working;
135 if (json != NULL)
136 size = strlen(json);
137 } else {
138 mode_ = Sending;
139 CYSendAll(client, &size, sizeof(size));
140 CYSendAll(client, data, size);
141 mode_ = Waiting;
142 CYRecvAll(client, &size, sizeof(size));
143 if (size == _not(size_t))
144 json = NULL;
145 else {
146 char *temp(new(pool) char[size + 1]);
147 CYRecvAll(client, temp, size);
148 temp[size] = '\0';
149 json = temp;
150 }
151 mode_ = Working;
152 }
153
154 if (json != NULL && fout != NULL) {
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:
175 fputs("\n", fout);
176 fflush(fout);
177 }
178 }
179
180 void Run(int client, std::string &code, FILE *fout = NULL, bool expand = false) {
181 Run(client, code.c_str(), code.size(), fout, expand);
182 }
183
184 int (*append_history$)(int, const char *);
185
186 static void Console(apr_pool_t *pool, int client) {
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
200 bool bypass(false);
201 bool debug(false);
202 bool expand(false);
203
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
218 bool extra(false);
219 const char *prompt("cy# ");
220
221 if (setjmp(ctrlc_) != 0) {
222 mode_ = Working;
223 fputs("\n", fout);
224 fflush(fout);
225 goto restart;
226 }
227
228 read:
229 mode_ = Parsing;
230 char *line(readline(prompt));
231 mode_ = Working;
232 if (line == NULL)
233 break;
234 if (line[0] == '\0')
235 goto read;
236
237 if (!extra) {
238 extra = true;
239 if (line[0] == '?') {
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);
249 } else if (data == "expand") {
250 expand = !expand;
251 fprintf(fout, "expand == %s\n", expand ? "true" : "false");
252 fflush(fout);
253 }
254 add_history(line);
255 ++histlines;
256 goto restart;
257 }
258 }
259
260 command += line;
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
271 free(line);
272
273 std::string code;
274
275 if (bypass)
276 code = command;
277 else {
278 CYDriver driver("");
279 cy::parser parser(driver);
280 Setup(driver, parser);
281
282 driver.data_ = command.c_str();
283 driver.size_ = command.size();
284
285 if (parser.parse() != 0 || !driver.errors_.empty()) {
286 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
287 cy::position begin(error->location_.begin);
288 if (begin.line != lines.size() || begin.column - 1 != lines.back().size() || error->warning_) {
289 cy::position end(error->location_.end);
290
291 if (begin.line != lines.size()) {
292 std::cerr << " | ";
293 std::cerr << lines[begin.line - 1] << std::endl;
294 }
295
296 std::cerr << "....";
297 for (size_t i(0); i != begin.column - 1; ++i)
298 std::cerr << '.';
299 if (begin.line != end.line || begin.column == end.column)
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;
304
305 std::cerr << " | ";
306 std::cerr << error->message_ << std::endl;
307
308 add_history(command.c_str());
309 ++histlines;
310 goto restart;
311 }
312 }
313
314 driver.errors_.clear();
315
316 command += '\n';
317 prompt = "cy> ";
318 goto read;
319 }
320
321 if (driver.program_ == NULL)
322 goto restart;
323
324 if (client != -1)
325 code = command;
326 else {
327 std::ostringstream str;
328 CYOptions options;
329 CYOutput out(str, options);
330 Setup(out, driver);
331 out << *driver.program_;
332 code = str.str();
333 }
334 }
335
336 add_history(command.c_str());
337 ++histlines;
338
339 if (debug)
340 std::cout << code << std::endl;
341
342 Run(client, code, fout, expand);
343 }
344
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 }
351
352 fputs("\n", fout);
353 fflush(fout);
354 }
355
356 static void *Map(const char *path, size_t *psize) {
357 int fd;
358 _syscall(fd = open(path, O_RDONLY));
359
360 struct stat stat;
361 _syscall(fstat(fd, &stat));
362 size_t size(stat.st_size);
363
364 *psize = size;
365
366 void *base;
367 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
368
369 _syscall(close(fd));
370 return base;
371 }
372
373 void InjectLibrary(pid_t pid);
374
375 int Main(int argc, char const * const argv[], char const * const envp[]) {
376 bool tty(isatty(STDIN_FILENO));
377 bool compile(false);
378
379 append_history$ = reinterpret_cast<int (*)(int, const char *)>(dlsym(RTLD_DEFAULT, "append_history"));
380
381 #ifdef CY_ATTACH
382 pid_t pid(_not(pid_t));
383 #endif
384
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:"
395 #ifdef CY_ATTACH
396 "p:"
397 #endif
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]"
408 #ifdef CY_ATTACH
409 " [-p <pid|name>]"
410 #endif
411 " [<script> [<arg>...]]\n"
412 );
413 return 1;
414 default:
415 _aprcall(status);
416 }
417
418 switch (opt) {
419 case 'c':
420 compile = true;
421 break;
422
423 case 'g':
424 if (false);
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);
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 CYOptions options;
612 CYOutput out(str, options);
613 Setup(out, driver);
614 out << *driver.program_;
615 std::string code(str.str());
616 if (compile)
617 std::cout << code;
618 else
619 Run(client, code, stdout);
620 }
621 }
622
623 return 0;
624 }
625
626 int main(int argc, char const * const argv[], char const * const envp[]) {
627 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
628
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 }