]> git.saurik.com Git - cycript.git/blob - Console.cpp
Made drastic changes to the serializer in order to support correctly serializing...
[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 #define _GNU_SOURCE
41
42 #include <substrate.h>
43 #include "cycript.hpp"
44
45 #include <cstdio>
46 #include <sstream>
47
48 #include <setjmp.h>
49
50 #include <readline/readline.h>
51 #include <readline/history.h>
52
53 #include <sys/mman.h>
54
55 #include <errno.h>
56 #include <unistd.h>
57
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <fcntl.h>
61
62 #include "Cycript.tab.hh"
63
64 #include <sys/types.h>
65 #include <sys/socket.h>
66 #include <netinet/in.h>
67 #include <sys/un.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
99 void Setup(CYDriver &driver, cy::parser &parser) {
100 #if YYDEBUG
101 if (bison_)
102 parser.set_debug_level(1);
103 #endif
104 if (strict_)
105 driver.strict_ = true;
106 }
107
108 void Run(int socket, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
109 CYPool pool;
110
111 const char *json;
112 if (socket == -1) {
113 mode_ = Running;
114 json = CYExecute(pool, data);
115 mode_ = Working;
116 if (json != NULL)
117 size = strlen(json);
118 } else {
119 mode_ = Sending;
120 CYSendAll(socket, &size, sizeof(size));
121 CYSendAll(socket, data, size);
122 mode_ = Waiting;
123 CYRecvAll(socket, &size, sizeof(size));
124 if (size == _not(size_t))
125 json = NULL;
126 else {
127 char *temp(new(pool) char[size + 1]);
128 CYRecvAll(socket, temp, size);
129 temp[size] = '\0';
130 json = temp;
131 }
132 mode_ = Working;
133 }
134
135 if (json != NULL && fout != NULL) {
136 if (!expand || json[0] != '"' && json[0] != '\'')
137 fputs(json, fout);
138 else for (size_t i(0); i != size; ++i)
139 if (json[i] != '\\')
140 fputc(json[i], fout);
141 else switch(json[++i]) {
142 case '\0': goto done;
143 case '\\': fputc('\\', fout); break;
144 case '\'': fputc('\'', fout); break;
145 case '"': fputc('"', fout); break;
146 case 'b': fputc('\b', fout); break;
147 case 'f': fputc('\f', fout); break;
148 case 'n': fputc('\n', fout); break;
149 case 'r': fputc('\r', fout); break;
150 case 't': fputc('\t', fout); break;
151 case 'v': fputc('\v', fout); break;
152 default: fputc('\\', fout); --i; break;
153 }
154
155 done:
156 fputs("\n", fout);
157 fflush(fout);
158 }
159 }
160
161 void Run(int socket, std::string &code, FILE *fout = NULL, bool expand = false) {
162 Run(socket, code.c_str(), code.size(), fout, expand);
163 }
164
165 static void Console(int socket) {
166 bool bypass(false);
167 bool debug(false);
168 bool expand(false);
169
170 FILE *fout(stdout);
171
172 rl_bind_key('\t', rl_insert);
173
174 struct sigaction action;
175 sigemptyset(&action.sa_mask);
176 action.sa_handler = &sigint;
177 action.sa_flags = 0;
178 sigaction(SIGINT, &action, NULL);
179
180 restart: for (;;) {
181 std::string command;
182 std::vector<std::string> lines;
183
184 bool extra(false);
185 const char *prompt("cy# ");
186
187 if (setjmp(ctrlc_) != 0) {
188 mode_ = Working;
189 fputs("\n", fout);
190 fflush(fout);
191 goto restart;
192 }
193
194 read:
195 mode_ = Parsing;
196 char *line(readline(prompt));
197 mode_ = Working;
198 if (line == NULL)
199 break;
200
201 if (!extra) {
202 extra = true;
203 if (line[0] == '?') {
204 std::string data(line + 1);
205 if (data == "bypass") {
206 bypass = !bypass;
207 fprintf(fout, "bypass == %s\n", bypass ? "true" : "false");
208 fflush(fout);
209 } else if (data == "debug") {
210 debug = !debug;
211 fprintf(fout, "debug == %s\n", debug ? "true" : "false");
212 fflush(fout);
213 } else if (data == "expand") {
214 expand = !expand;
215 fprintf(fout, "expand == %s\n", expand ? "true" : "false");
216 fflush(fout);
217 }
218 add_history(line);
219 goto restart;
220 }
221 }
222
223 command += line;
224 for (char *state, *token(apr_strtok(line, "\n", &state)); token != NULL; token = apr_strtok(NULL, "\n", &state))
225 lines.push_back(token);
226 free(line);
227
228 std::string code;
229
230 if (bypass)
231 code = command;
232 else {
233 CYDriver driver("");
234 cy::parser parser(driver);
235 Setup(driver, parser);
236
237 driver.data_ = command.c_str();
238 driver.size_ = command.size();
239
240 if (parser.parse() != 0 || !driver.errors_.empty()) {
241 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
242 cy::position begin(error->location_.begin);
243 if (begin.line != lines.size() || begin.column - 1 != lines.back().size() || error->warning_) {
244 cy::position end(error->location_.end);
245
246 if (begin.line != lines.size()) {
247 std::cerr << " | ";
248 std::cerr << lines[begin.line - 1] << std::endl;
249 }
250
251 std::cerr << " | ";
252 for (size_t i(0); i != begin.column - 1; ++i)
253 std::cerr << '.';
254 if (begin.line != end.line || begin.column == end.column)
255 std::cerr << '^';
256 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
257 std::cerr << '^';
258 std::cerr << std::endl;
259
260 std::cerr << " | ";
261 std::cerr << error->message_ << std::endl;
262
263 add_history(command.c_str());
264 goto restart;
265 }
266 }
267
268 driver.errors_.clear();
269
270 command += '\n';
271 prompt = "cy> ";
272 goto read;
273 }
274
275 if (driver.program_ == NULL)
276 goto restart;
277
278 if (socket != -1)
279 code = command;
280 else {
281 std::ostringstream str;
282 CYOutput out(str);
283 driver.program_->Multiple(out);
284 code = str.str();
285 }
286 }
287
288 add_history(command.c_str());
289
290 if (debug)
291 std::cout << code << std::endl;
292
293 Run(socket, code, fout, expand);
294 }
295
296 fputs("\n", fout);
297 fflush(fout);
298 }
299
300 static void *Map(const char *path, size_t *psize) {
301 int fd;
302 _syscall(fd = open(path, O_RDONLY));
303
304 struct stat stat;
305 _syscall(fstat(fd, &stat));
306 size_t size(stat.st_size);
307
308 *psize = size;
309
310 void *base;
311 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
312
313 _syscall(close(fd));
314 return base;
315 }
316
317 int main(int argc, char *argv[]) {
318 bool tty(isatty(STDIN_FILENO));
319 pid_t pid(_not(pid_t));
320 bool compile(false);
321
322 for (;;) switch (getopt(argc, argv, "cg:p:s")) {
323 case -1:
324 goto getopt;
325 case '?':
326 fprintf(stderr, "usage: cycript [-c] [-p <pid>] [<script> [<arg>...]]\n");
327 return 1;
328
329 case 'c':
330 compile = true;
331 break;
332
333 case 'g':
334 if (false);
335 #if YYDEBUG
336 else if (strcmp(optarg, "bison") == 0)
337 bison_ = true;
338 #endif
339 else {
340 fprintf(stderr, "invalid name for -g\n");
341 return 1;
342 }
343 break;
344
345 case 'p': {
346 size_t size(strlen(optarg));
347 char *end;
348 pid = strtoul(optarg, &end, 0);
349 if (optarg + size != end) {
350 fprintf(stderr, "invalid pid for -p\n");
351 return 1;
352 }
353 } break;
354
355 case 's':
356 strict_ = true;
357 break;
358 } getopt:;
359
360 const char *script;
361
362 if (pid != _not(pid_t) && optind < argc - 1) {
363 fprintf(stderr, "-p cannot set argv\n");
364 return 1;
365 }
366
367 if (pid != _not(pid_t) && compile) {
368 fprintf(stderr, "-p conflicts with -c\n");
369 return 1;
370 }
371
372 if (optind == argc)
373 script = NULL;
374 else {
375 // XXX: const_cast?! wtf gcc :(
376 CYSetArgs(argc - optind - 1, const_cast<const char **>(argv + optind + 1));
377 script = argv[optind];
378 if (strcmp(script, "-") == 0)
379 script = NULL;
380 }
381
382 if (script == NULL && !tty && pid != _not(pid_t)) {
383 fprintf(stderr, "non-terminal attaching to remove console\n");
384 return 1;
385 }
386
387 int socket;
388
389 if (pid == _not(pid_t))
390 socket = -1;
391 else {
392 socket = _syscall(::socket(PF_UNIX, SOCK_STREAM, 0));
393
394 struct sockaddr_un address;
395 memset(&address, 0, sizeof(address));
396 address.sun_family = AF_UNIX;
397 sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
398
399 _syscall(connect(socket, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
400 }
401
402 if (script == NULL && tty)
403 Console(socket);
404 else {
405 CYDriver driver(script ?: "<stdin>");
406 cy::parser parser(driver);
407 Setup(driver, parser);
408
409 char *start, *end;
410
411 if (script == NULL) {
412 start = NULL;
413 end = NULL;
414
415 driver.file_ = stdin;
416 } else {
417 size_t size;
418 start = reinterpret_cast<char *>(Map(script, &size));
419 end = start + size;
420
421 if (size >= 2 && start[0] == '#' && start[1] == '!') {
422 start += 2;
423
424 if (void *line = memchr(start, '\n', end - start))
425 start = reinterpret_cast<char *>(line);
426 else
427 start = end;
428 }
429
430 driver.data_ = start;
431 driver.size_ = end - start;
432 }
433
434 if (parser.parse() != 0 || !driver.errors_.empty()) {
435 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
436 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
437 } else if (driver.program_ != NULL)
438 if (socket != -1)
439 Run(socket, start, end - start, stdout);
440 else {
441 std::ostringstream str;
442 CYOutput out(str);
443 driver.program_->Multiple(out);
444 std::string code(str.str());
445 if (compile)
446 std::cout << code;
447 else
448 Run(socket, code);
449 }
450 }
451
452 return 0;
453 }