]> git.saurik.com Git - cycript.git/blob - Console.cpp
Fixed a few bugs in the cross-compile and a GNUstep related casting issue.
[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 client, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
117 CYPool pool;
118
119 const char *json;
120 if (client == -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(client, &size, sizeof(size));
133 CYSendAll(client, data, size);
134 mode_ = Waiting;
135 CYRecvAll(client, &size, sizeof(size));
136 if (size == _not(size_t))
137 json = NULL;
138 else {
139 char *temp(new(pool) char[size + 1]);
140 CYRecvAll(client, 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 client, std::string &code, FILE *fout = NULL, bool expand = false) {
174 Run(client, code.c_str(), code.size(), fout, expand);
175 }
176
177 static void Console(apr_pool_t *pool, int client) {
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 (client != -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(client, 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 void InjectLibrary(pid_t pid);
358
359 int Main(int argc, char const * const argv[], char const * const envp[]) {
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 fail;
450 }
451 }
452 }
453
454 size:
455 if (size == 0)
456 goto fail;
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) fail:
466 pid = _not(pid_t);
467 _syscall(pclose(pids));
468 }
469
470 if (pid == _not(pid_t)) {
471 fprintf(stderr, "invalid pid for -p\n");
472 return 1;
473 }
474 }
475 } break;
476 #endif
477
478 case 's':
479 strict_ = true;
480 break;
481 }
482 } getopt:;
483
484 const char *script;
485 int ind(state->ind);
486
487 #ifdef CY_ATTACH
488 if (pid != _not(pid_t) && ind < argc - 1) {
489 fprintf(stderr, "-p cannot set argv\n");
490 return 1;
491 }
492
493 if (pid != _not(pid_t) && compile) {
494 fprintf(stderr, "-p conflicts with -c\n");
495 return 1;
496 }
497 #endif
498
499 if (ind == argc)
500 script = NULL;
501 else {
502 #ifdef CY_EXECUTE
503 // XXX: const_cast?! wtf gcc :(
504 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
505 #endif
506 script = argv[ind];
507 if (strcmp(script, "-") == 0)
508 script = NULL;
509 }
510
511 #ifdef CY_ATTACH
512 if (pid != _not(pid_t) && script == NULL && !tty) {
513 fprintf(stderr, "non-terminal attaching to remote console\n");
514 return 1;
515 }
516 #endif
517
518 int client;
519
520 #ifdef CY_ATTACH
521 if (pid == _not(pid_t))
522 client = -1;
523 else {
524 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
525 struct sockaddr_un address;
526 memset(&address, 0, sizeof(address));
527 address.sun_family = AF_UNIX;
528
529 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
530
531 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
532 _syscall(chmod(address.sun_path, 0777));
533
534 try {
535 _syscall(listen(server, 1));
536 InjectLibrary(pid);
537 client = _syscall(accept(server, NULL, NULL));
538 } catch (...) {
539 // XXX: exception?
540 unlink(address.sun_path);
541 throw;
542 }
543 } catch (...) {
544 _syscall(close(server));
545 throw;
546 }
547 }
548 #else
549 client = -1;
550 #endif
551
552 if (script == NULL && tty)
553 Console(pool, client);
554 else {
555 CYDriver driver(script ?: "<stdin>");
556 cy::parser parser(driver);
557 Setup(driver, parser);
558
559 char *start, *end;
560
561 if (script == NULL) {
562 start = NULL;
563 end = NULL;
564
565 driver.file_ = stdin;
566 } else {
567 size_t size;
568 start = reinterpret_cast<char *>(Map(script, &size));
569 end = start + size;
570
571 if (size >= 2 && start[0] == '#' && start[1] == '!') {
572 start += 2;
573
574 if (void *line = memchr(start, '\n', end - start))
575 start = reinterpret_cast<char *>(line);
576 else
577 start = end;
578 }
579
580 driver.data_ = start;
581 driver.size_ = end - start;
582 }
583
584 if (parser.parse() != 0 || !driver.errors_.empty()) {
585 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
586 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
587 } else if (driver.program_ != NULL)
588 if (client != -1)
589 Run(client, start, end - start, stdout);
590 else {
591 std::ostringstream str;
592 CYOutput out(str);
593 Setup(out, driver);
594 out << *driver.program_;
595 std::string code(str.str());
596 if (compile)
597 std::cout << code;
598 else
599 Run(client, code, stdout);
600 }
601 }
602
603 return 0;
604 }
605
606 int main(int argc, char const * const argv[], char const * const envp[]) {
607 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
608 if (status != APR_SUCCESS) {
609 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
610 return 1;
611 } else try {
612 return Main(argc, argv, envp);
613 } catch (const CYException &error) {
614 CYPool pool;
615 fprintf(stderr, "%s\n", error.PoolCString(pool));
616 return 1;
617 }
618 }