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