]> git.saurik.com Git - cycript.git/blob - Console.cpp
Fixed a tokenization bug that caused blank lines a the console to crash horribly.
[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
225 char *begin(line), *end(line + strlen(line));
226 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
227 *nl = '\0';
228 lines.push_back(begin);
229 begin = nl + 1;
230 }
231
232 lines.push_back(begin);
233
234 free(line);
235
236 std::string code;
237
238 if (bypass)
239 code = command;
240 else {
241 CYDriver driver("");
242 cy::parser parser(driver);
243 Setup(driver, parser);
244
245 driver.data_ = command.c_str();
246 driver.size_ = command.size();
247
248 if (parser.parse() != 0 || !driver.errors_.empty()) {
249 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
250 cy::position begin(error->location_.begin);
251 if (begin.line != lines.size() || begin.column - 1 != lines.back().size() || error->warning_) {
252 cy::position end(error->location_.end);
253
254 if (begin.line != lines.size()) {
255 std::cerr << " | ";
256 std::cerr << lines[begin.line - 1] << std::endl;
257 }
258
259 std::cerr << " | ";
260 for (size_t i(0); i != begin.column - 1; ++i)
261 std::cerr << '.';
262 if (begin.line != end.line || begin.column == end.column)
263 std::cerr << '^';
264 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
265 std::cerr << '^';
266 std::cerr << std::endl;
267
268 std::cerr << " | ";
269 std::cerr << error->message_ << std::endl;
270
271 add_history(command.c_str());
272 goto restart;
273 }
274 }
275
276 driver.errors_.clear();
277
278 command += '\n';
279 prompt = "cy> ";
280 goto read;
281 }
282
283 if (driver.program_ == NULL)
284 goto restart;
285
286 if (socket != -1)
287 code = command;
288 else {
289 std::ostringstream str;
290 CYOutput out(str);
291 driver.program_->Multiple(out);
292 code = str.str();
293 }
294 }
295
296 add_history(command.c_str());
297
298 if (debug)
299 std::cout << code << std::endl;
300
301 Run(socket, code, fout, expand);
302 }
303
304 fputs("\n", fout);
305 fflush(fout);
306 }
307
308 static void *Map(const char *path, size_t *psize) {
309 int fd;
310 _syscall(fd = open(path, O_RDONLY));
311
312 struct stat stat;
313 _syscall(fstat(fd, &stat));
314 size_t size(stat.st_size);
315
316 *psize = size;
317
318 void *base;
319 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
320
321 _syscall(close(fd));
322 return base;
323 }
324
325 int main(int argc, char *argv[]) {
326 bool tty(isatty(STDIN_FILENO));
327 pid_t pid(_not(pid_t));
328 bool compile(false);
329
330 for (;;) switch (getopt(argc, argv, "cg:p:s")) {
331 case -1:
332 goto getopt;
333 case '?':
334 fprintf(stderr, "usage: cycript [-c] [-p <pid>] [<script> [<arg>...]]\n");
335 return 1;
336
337 case 'c':
338 compile = true;
339 break;
340
341 case 'g':
342 if (false);
343 #if YYDEBUG
344 else if (strcmp(optarg, "bison") == 0)
345 bison_ = true;
346 #endif
347 else {
348 fprintf(stderr, "invalid name for -g\n");
349 return 1;
350 }
351 break;
352
353 case 'p': {
354 size_t size(strlen(optarg));
355 char *end;
356 pid = strtoul(optarg, &end, 0);
357 if (optarg + size != end) {
358 fprintf(stderr, "invalid pid for -p\n");
359 return 1;
360 }
361 } break;
362
363 case 's':
364 strict_ = true;
365 break;
366 } getopt:;
367
368 const char *script;
369
370 if (pid != _not(pid_t) && optind < argc - 1) {
371 fprintf(stderr, "-p cannot set argv\n");
372 return 1;
373 }
374
375 if (pid != _not(pid_t) && compile) {
376 fprintf(stderr, "-p conflicts with -c\n");
377 return 1;
378 }
379
380 if (optind == argc)
381 script = NULL;
382 else {
383 // XXX: const_cast?! wtf gcc :(
384 CYSetArgs(argc - optind - 1, const_cast<const char **>(argv + optind + 1));
385 script = argv[optind];
386 if (strcmp(script, "-") == 0)
387 script = NULL;
388 }
389
390 if (script == NULL && !tty && pid != _not(pid_t)) {
391 fprintf(stderr, "non-terminal attaching to remove console\n");
392 return 1;
393 }
394
395 int socket;
396
397 if (pid == _not(pid_t))
398 socket = -1;
399 else {
400 socket = _syscall(::socket(PF_UNIX, SOCK_STREAM, 0));
401
402 struct sockaddr_un address;
403 memset(&address, 0, sizeof(address));
404 address.sun_family = AF_UNIX;
405 sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
406
407 _syscall(connect(socket, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
408 }
409
410 if (script == NULL && tty)
411 Console(socket);
412 else {
413 CYDriver driver(script ?: "<stdin>");
414 cy::parser parser(driver);
415 Setup(driver, parser);
416
417 char *start, *end;
418
419 if (script == NULL) {
420 start = NULL;
421 end = NULL;
422
423 driver.file_ = stdin;
424 } else {
425 size_t size;
426 start = reinterpret_cast<char *>(Map(script, &size));
427 end = start + size;
428
429 if (size >= 2 && start[0] == '#' && start[1] == '!') {
430 start += 2;
431
432 if (void *line = memchr(start, '\n', end - start))
433 start = reinterpret_cast<char *>(line);
434 else
435 start = end;
436 }
437
438 driver.data_ = start;
439 driver.size_ = end - start;
440 }
441
442 if (parser.parse() != 0 || !driver.errors_.empty()) {
443 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
444 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
445 } else if (driver.program_ != NULL)
446 if (socket != -1)
447 Run(socket, start, end - start, stdout);
448 else {
449 std::ostringstream str;
450 CYOutput out(str);
451 driver.program_->Multiple(out);
452 std::string code(str.str());
453 if (compile)
454 std::cout << code;
455 else
456 Run(socket, code);
457 }
458 }
459
460 return 0;
461 }