]> git.saurik.com Git - cycript.git/blob - Console.cpp
Added readline history writing and fixed NoRE unary * case.
[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>]"
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 pid = strtoul(arg, &end, 0);
432 if (arg + size != end) {
433 fprintf(stderr, "invalid pid for -p\n");
434 return 1;
435 }
436 } break;
437 #endif
438
439 case 's':
440 strict_ = true;
441 break;
442 }
443 } getopt:;
444
445 const char *script;
446 int ind(state->ind);
447
448 #ifdef CY_ATTACH
449 if (pid != _not(pid_t) && ind < argc - 1) {
450 fprintf(stderr, "-p cannot set argv\n");
451 return 1;
452 }
453
454 if (pid != _not(pid_t) && compile) {
455 fprintf(stderr, "-p conflicts with -c\n");
456 return 1;
457 }
458 #endif
459
460 if (ind == argc)
461 script = NULL;
462 else {
463 #ifdef CY_EXECUTE
464 // XXX: const_cast?! wtf gcc :(
465 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
466 #endif
467 script = argv[ind];
468 if (strcmp(script, "-") == 0)
469 script = NULL;
470 }
471
472 #ifdef CY_ATTACH
473 if (pid != _not(pid_t) && script == NULL && !tty) {
474 fprintf(stderr, "non-terminal attaching to remote console\n");
475 return 1;
476 }
477 #endif
478
479 int socket;
480
481 #ifdef CY_ATTACH
482 if (pid == _not(pid_t))
483 socket = -1;
484 else {
485 socket = _syscall(::socket(PF_UNIX, SOCK_STREAM, 0));
486
487 struct sockaddr_un address;
488 memset(&address, 0, sizeof(address));
489 address.sun_family = AF_UNIX;
490 sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
491
492 _syscall(connect(socket, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
493 }
494 #else
495 socket = -1;
496 #endif
497
498 if (script == NULL && tty)
499 Console(pool, socket);
500 else {
501 CYDriver driver(script ?: "<stdin>");
502 cy::parser parser(driver);
503 Setup(driver, parser);
504
505 char *start, *end;
506
507 if (script == NULL) {
508 start = NULL;
509 end = NULL;
510
511 driver.file_ = stdin;
512 } else {
513 size_t size;
514 start = reinterpret_cast<char *>(Map(script, &size));
515 end = start + size;
516
517 if (size >= 2 && start[0] == '#' && start[1] == '!') {
518 start += 2;
519
520 if (void *line = memchr(start, '\n', end - start))
521 start = reinterpret_cast<char *>(line);
522 else
523 start = end;
524 }
525
526 driver.data_ = start;
527 driver.size_ = end - start;
528 }
529
530 if (parser.parse() != 0 || !driver.errors_.empty()) {
531 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
532 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
533 } else if (driver.program_ != NULL)
534 if (socket != -1)
535 Run(socket, start, end - start, stdout);
536 else {
537 std::ostringstream str;
538 CYOutput out(str);
539 Setup(out, driver);
540 out << *driver.program_;
541 std::string code(str.str());
542 if (compile)
543 std::cout << code;
544 else
545 Run(socket, code, stdout);
546 }
547 }
548
549 return 0;
550 }