]> git.saurik.com Git - cycript.git/blame - Console.cpp
Add initial support for -arch armv6.
[cycript.git] / Console.cpp
CommitLineData
b3378a02
JF
1/* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2010 Jay Freeman (saurik)
b4aa79af
JF
3*/
4
b3378a02 5/* GNU Lesser General Public License, Version 3 {{{ */
b4aa79af 6/*
b3378a02
JF
7 * Cycript is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
b4aa79af 11 *
b3378a02
JF
12 * Cycript is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
b4aa79af 16 *
b3378a02
JF
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
19**/
b4aa79af
JF
20/* }}} */
21
30ddc20c 22#include "cycript.hpp"
057f943f 23
9cad30fa
JF
24#ifdef CY_EXECUTE
25#include "JavaScript.hpp"
26#endif
27
057f943f
JF
28#include <cstdio>
29#include <sstream>
30
31#include <setjmp.h>
32
aff87425
DWT
33#ifdef HAVE_READLINE_H
34#include <readline.h>
35#else
057f943f 36#include <readline/readline.h>
aff87425
DWT
37#endif
38
39#ifdef HAVE_HISTORY_H
40#include <history.h>
41#else
057f943f 42#include <readline/history.h>
aff87425 43#endif
057f943f 44
b09da87b
JF
45#include <sys/mman.h>
46
47#include <errno.h>
48#include <unistd.h>
49
50#include <sys/types.h>
51#include <sys/stat.h>
52#include <fcntl.h>
53
057f943f
JF
54#include "Cycript.tab.hh"
55
967067aa
JF
56#include <sys/types.h>
57#include <sys/socket.h>
58#include <netinet/in.h>
59#include <sys/un.h>
b1589845 60#include <pwd.h>
967067aa 61
06edab7d
JF
62#include <apr_getopt.h>
63
da858962
JF
64#include <dlfcn.h>
65
7e5391fd
JF
66#include "Replace.hpp"
67
4e39dc0b
JF
68static volatile enum {
69 Working,
70 Parsing,
71 Running,
72 Sending,
73 Waiting,
74} mode_;
75
057f943f
JF
76static jmp_buf ctrlc_;
77
579ed526 78static void sigint(int) {
4e39dc0b
JF
79 switch (mode_) {
80 case Working:
81 return;
82 case Parsing:
83 longjmp(ctrlc_, 1);
84 case Running:
85 throw "*** Ctrl-C";
86 case Sending:
87 return;
88 case Waiting:
89 return;
90 }
057f943f
JF
91}
92
cac61857
JF
93#if YYDEBUG
94static bool bison_;
95#endif
b10bd496 96static bool strict_;
11c1cc16 97static bool pretty_;
cac61857 98
b10bd496 99void Setup(CYDriver &driver, cy::parser &parser) {
cac61857
JF
100#if YYDEBUG
101 if (bison_)
102 parser.set_debug_level(1);
103#endif
b10bd496
JF
104 if (strict_)
105 driver.strict_ = true;
cac61857
JF
106}
107
de9fc71b 108void Setup(CYOutput &out, CYDriver &driver, CYOptions &options) {
11c1cc16 109 out.pretty_ = pretty_;
2eb8215d 110 CYContext context(options);
3b52fd1a 111 driver.program_->Replace(context);
11c1cc16
JF
112}
113
7e5391fd 114static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
967067aa 115 const char *json;
7e5391fd
JF
116 size_t size;
117
b166b11b 118 if (client == -1) {
4e39dc0b 119 mode_ = Running;
2aa77fd8 120#ifdef CY_EXECUTE
0ced2e47 121 json = CYExecute(pool, code);
2aa77fd8
JF
122#else
123 json = NULL;
124#endif
4e39dc0b 125 mode_ = Working;
dd221c6b
JF
126 if (json == NULL)
127 size = 0;
128 else
6ec85c5b
JF
129 size = strlen(json);
130 } else {
4e39dc0b 131 mode_ = Sending;
0ced2e47 132 size = code.size;
b166b11b 133 CYSendAll(client, &size, sizeof(size));
0ced2e47 134 CYSendAll(client, code.data, code.size);
4e39dc0b 135 mode_ = Waiting;
b166b11b 136 CYRecvAll(client, &size, sizeof(size));
967067aa
JF
137 if (size == _not(size_t))
138 json = NULL;
139 else {
140 char *temp(new(pool) char[size + 1]);
b166b11b 141 CYRecvAll(client, temp, size);
967067aa
JF
142 temp[size] = '\0';
143 json = temp;
144 }
4e39dc0b 145 mode_ = Working;
4cf49641 146 }
b09da87b 147
7e5391fd
JF
148 return CYUTF8String(json, size);
149}
150
151static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
152 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
153}
154
a3f4a8e1
JF
155FILE *fout_;
156
157static void Output(CYUTF8String json, FILE *fout, bool expand = false) {
158 const char *data(json.data);
159 size_t size(json.size);
160
161 if (data == NULL || fout == NULL)
162 return;
163
164 if (!expand || data[0] != '"' && data[0] != '\'')
165 fputs(data, fout);
166 else for (size_t i(0); i != size; ++i)
167 if (data[i] != '\\')
168 fputc(data[i], fout);
169 else switch(data[++i]) {
170 case '\0': goto done;
171 case '\\': fputc('\\', fout); break;
172 case '\'': fputc('\'', fout); break;
173 case '"': fputc('"', fout); break;
174 case 'b': fputc('\b', fout); break;
175 case 'f': fputc('\f', fout); break;
176 case 'n': fputc('\n', fout); break;
177 case 'r': fputc('\r', fout); break;
178 case 't': fputc('\t', fout); break;
179 case 'v': fputc('\v', fout); break;
180 default: fputc('\\', fout); --i; break;
181 }
6ec85c5b 182
a3f4a8e1
JF
183 done:
184 fputs("\n", fout);
185 fflush(fout);
186}
187
188static void Run(int client, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
189 CYPool pool;
190 Output(Run(pool, client, CYUTF8String(data, size)), fout, expand);
b09da87b
JF
191}
192
7e5391fd 193static void Run(int client, std::string &code, FILE *fout = NULL, bool expand = false) {
b166b11b 194 Run(client, code.c_str(), code.size(), fout, expand);
fcc64bb5
JF
195}
196
da858962
JF
197int (*append_history$)(int, const char *);
198
7e5391fd
JF
199static std::string command_;
200
2eb8215d 201static CYExpression *ParseExpression(CYUTF8String code) {
7e5391fd
JF
202 std::ostringstream str;
203 str << '(' << code << ')';
204 std::string string(str.str());
205
2eb8215d 206 CYDriver driver;
7e5391fd
JF
207 driver.data_ = string.c_str();
208 driver.size_ = string.size();
209
210 cy::parser parser(driver);
211 Setup(driver, parser);
212
213 if (parser.parse() != 0 || !driver.errors_.empty())
214 _assert(false);
215
216 CYExpress *express(dynamic_cast<CYExpress *>(driver.program_->statements_));
217 _assert(express != NULL);
218 return express->expression_;
219}
220
221static int client_;
222
223static char **Complete(const char *word, int start, int end) {
224 rl_attempted_completion_over = TRUE;
225
2eb8215d
JF
226 CYLocalPool pool;
227 CYDriver driver;
7e5391fd
JF
228 cy::parser parser(driver);
229 Setup(driver, parser);
230
231 std::string line(rl_line_buffer, start);
232 std::string command(command_ + line);
233
234 driver.data_ = command.c_str();
235 driver.size_ = command.size();
236
237 driver.auto_ = true;
238
239 if (parser.parse() != 0 || !driver.errors_.empty())
240 return NULL;
241
242 if (driver.mode_ == CYDriver::AutoNone)
243 return NULL;
244
245 CYExpression *expression;
246
247 CYOptions options;
2eb8215d 248 CYContext context(options);
7e5391fd
JF
249
250 std::ostringstream prefix;
251
252 switch (driver.mode_) {
253 case CYDriver::AutoPrimary:
254 expression = $ CYThis();
255 break;
256
257 case CYDriver::AutoDirect:
258 expression = driver.context_;
259 break;
260
261 case CYDriver::AutoIndirect:
262 expression = $ CYIndirect(driver.context_);
263 break;
264
265 case CYDriver::AutoMessage: {
266 CYDriver::Context &thing(driver.contexts_.back());
267 expression = $M($M($ CYIndirect(thing.context_), $S("isa")), $S("messages"));
268 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
269 prefix << (*part)->word_ << ':';
270 } break;
271
272 default:
273 _assert(false);
274 }
275
2a18313c 276 std::string begin(prefix.str());
7e5391fd 277
2eb8215d 278 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
2a18313c 279 " function(object, prefix, word) {\n"
7e5391fd 280 " var names = [];\n"
2a18313c
JF
281 " var pattern = '^' + prefix + word;\n"
282 " var length = prefix.length;\n"
7e5391fd
JF
283 " for (name in object)\n"
284 " if (name.match(pattern) != null)\n"
2a18313c 285 " names.push(name.substr(length));\n"
7e5391fd
JF
286 " return names;\n"
287 " }\n"
2a18313c 288 ), expression, $S(begin.c_str()), $S(word))));
7e5391fd
JF
289
290 driver.program_->Replace(context);
291
292 std::ostringstream str;
293 CYOutput out(str, options);
294 out << *driver.program_;
295
296 std::string code(str.str());
297 CYUTF8String json(Run(pool, client_, code));
298
2eb8215d 299 CYExpression *result(ParseExpression(json));
7e5391fd 300 CYArray *array(dynamic_cast<CYArray *>(result));
a3f4a8e1
JF
301
302 if (array == NULL) {
303 fprintf(fout_, "\n");
304 Output(json, fout_);
305 rl_forced_update_display();
306 return NULL;
307 }
7e5391fd
JF
308
309 // XXX: use an std::set?
310 typedef std::vector<std::string> Completions;
311 Completions completions;
312
313 std::string common;
314 bool rest(false);
315
c2c9f509 316 CYForEach (element, array->elements_) {
7e5391fd
JF
317 CYString *string(dynamic_cast<CYString *>(element->value_));
318 _assert(string != NULL);
319
763aa499
JF
320 std::string completion;
321 if (string->size_ != 0)
322 completion.assign(string->value_, string->size_);
323 else if (driver.mode_ == CYDriver::AutoMessage)
324 completion = "]";
325 else
326 continue;
327
7e5391fd
JF
328 completions.push_back(completion);
329
330 if (!rest) {
331 common = completion;
332 rest = true;
333 } else {
334 size_t limit(completion.size()), size(common.size());
335 if (size > limit)
336 common = common.substr(0, limit);
337 else
338 limit = size;
339 for (limit = 0; limit != size; ++limit)
340 if (common[limit] != completion[limit])
341 break;
342 if (limit != size)
343 common = common.substr(0, limit);
344 }
345 }
346
347 size_t count(completions.size());
348 if (count == 0)
349 return NULL;
350
c41590b2
JF
351 size_t colon(common.find(':'));
352 if (colon != std::string::npos)
353 common = common.substr(0, colon + 1);
6dccefa9
JF
354 if (completions.size() == 1)
355 common += ' ';
c41590b2 356
7e5391fd
JF
357 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
358
359 results[0] = strdup(common.c_str());
360 size_t index(0);
361 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
362 results[++index] = strdup(i->c_str());
363 results[count + 1] = NULL;
364
365 return results;
366}
367
368// need char *, not const char *
369static char name_[] = "cycript";
108c5fc8 370static char break_[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
7e5391fd 371
2eb8215d
JF
372static void Console(CYOptions &options) {
373 CYPool pool;
374
b1589845
JF
375 passwd *passwd;
376 if (const char *username = getenv("LOGNAME"))
377 passwd = getpwnam(username);
378 else
379 passwd = getpwuid(getuid());
380
381 const char *basedir(apr_psprintf(pool, "%s/.cycript", passwd->pw_dir));
382 const char *histfile(apr_psprintf(pool, "%s/history", basedir));
383 size_t histlines(0);
384
7e5391fd
JF
385 rl_initialize();
386 rl_readline_name = name_;
387
b1589845
JF
388 mkdir(basedir, 0700);
389 read_history(histfile);
390
1f8eae40
JF
391 bool bypass(false);
392 bool debug(false);
6ec85c5b 393 bool expand(false);
1f8eae40 394
a3f4a8e1 395 fout_ = stdout;
057f943f 396
7e5391fd
JF
397 // rl_completer_word_break_characters is broken in libedit
398 rl_basic_word_break_characters = break_;
bc1e87aa
JF
399
400 rl_completer_word_break_characters = break_;
7e5391fd
JF
401 rl_attempted_completion_function = &Complete;
402 rl_bind_key('\t', rl_complete);
057f943f
JF
403
404 struct sigaction action;
405 sigemptyset(&action.sa_mask);
406 action.sa_handler = &sigint;
407 action.sa_flags = 0;
408 sigaction(SIGINT, &action, NULL);
409
410 restart: for (;;) {
7e5391fd 411 command_.clear();
057f943f
JF
412 std::vector<std::string> lines;
413
931b816a
JF
414 bool extra(false);
415 const char *prompt("cy# ");
416
057f943f 417 if (setjmp(ctrlc_) != 0) {
4e39dc0b 418 mode_ = Working;
a3f4a8e1
JF
419 fputs("\n", fout_);
420 fflush(fout_);
057f943f
JF
421 goto restart;
422 }
423
057f943f 424 read:
4e39dc0b 425 mode_ = Parsing;
057f943f 426 char *line(readline(prompt));
4e39dc0b 427 mode_ = Working;
057f943f
JF
428 if (line == NULL)
429 break;
67f1fc6b
JF
430 if (line[0] == '\0')
431 goto read;
931b816a
JF
432
433 if (!extra) {
434 extra = true;
6ec85c5b 435 if (line[0] == '?') {
1f8eae40
JF
436 std::string data(line + 1);
437 if (data == "bypass") {
438 bypass = !bypass;
a3f4a8e1
JF
439 fprintf(fout_, "bypass == %s\n", bypass ? "true" : "false");
440 fflush(fout_);
1f8eae40
JF
441 } else if (data == "debug") {
442 debug = !debug;
a3f4a8e1
JF
443 fprintf(fout_, "debug == %s\n", debug ? "true" : "false");
444 fflush(fout_);
6ec85c5b
JF
445 } else if (data == "expand") {
446 expand = !expand;
a3f4a8e1
JF
447 fprintf(fout_, "expand == %s\n", expand ? "true" : "false");
448 fflush(fout_);
1f8eae40 449 }
d35a3b07 450 add_history(line);
b1589845 451 ++histlines;
931b816a
JF
452 goto restart;
453 }
454 }
455
7e5391fd 456 command_ += line;
e818f0e0
JF
457
458 char *begin(line), *end(line + strlen(line));
459 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
460 *nl = '\0';
461 lines.push_back(begin);
462 begin = nl + 1;
463 }
464
465 lines.push_back(begin);
466
057f943f
JF
467 free(line);
468
1f8eae40
JF
469 std::string code;
470
471 if (bypass)
7e5391fd 472 code = command_;
1f8eae40 473 else {
2eb8215d 474 CYLocalPool pool;
7e5391fd 475 CYDriver driver;
1f8eae40 476 cy::parser parser(driver);
b10bd496 477 Setup(driver, parser);
1f8eae40 478
7e5391fd
JF
479 driver.data_ = command_.c_str();
480 driver.size_ = command_.size();
1f8eae40
JF
481
482 if (parser.parse() != 0 || !driver.errors_.empty()) {
f0360d51
JF
483 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
484 cy::position begin(error->location_.begin);
b10bd496 485 if (begin.line != lines.size() || begin.column - 1 != lines.back().size() || error->warning_) {
f0360d51 486 cy::position end(error->location_.end);
48e3be8a 487
f0360d51
JF
488 if (begin.line != lines.size()) {
489 std::cerr << " | ";
490 std::cerr << lines[begin.line - 1] << std::endl;
491 }
48e3be8a 492
c52a09b8 493 std::cerr << "....";
f0360d51
JF
494 for (size_t i(0); i != begin.column - 1; ++i)
495 std::cerr << '.';
48e3be8a 496 if (begin.line != end.line || begin.column == end.column)
f0360d51
JF
497 std::cerr << '^';
498 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
499 std::cerr << '^';
500 std::cerr << std::endl;
48e3be8a 501
f0360d51
JF
502 std::cerr << " | ";
503 std::cerr << error->message_ << std::endl;
48e3be8a 504
7e5391fd 505 add_history(command_.c_str());
b1589845 506 ++histlines;
1f8eae40
JF
507 goto restart;
508 }
509 }
057f943f 510
1f8eae40 511 driver.errors_.clear();
057f943f 512
7e5391fd 513 command_ += '\n';
1f8eae40
JF
514 prompt = "cy> ";
515 goto read;
057f943f
JF
516 }
517
b10bd496 518 if (driver.program_ == NULL)
1f8eae40 519 goto restart;
057f943f 520
7e5391fd
JF
521 if (client_ != -1)
522 code = command_;
967067aa
JF
523 else {
524 std::ostringstream str;
029bc65b 525 CYOutput out(str, options);
de9fc71b 526 Setup(out, driver, options);
3b52fd1a 527 out << *driver.program_;
967067aa
JF
528 code = str.str();
529 }
057f943f
JF
530 }
531
7e5391fd 532 add_history(command_.c_str());
b1589845 533 ++histlines;
057f943f 534
1f8eae40
JF
535 if (debug)
536 std::cout << code << std::endl;
057f943f 537
a3f4a8e1 538 Run(client_, code, fout_, expand);
b09da87b 539 }
057f943f 540
da858962
JF
541 if (append_history$ != NULL) {
542 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
543 (*append_history$)(histlines, histfile);
544 } else {
545 write_history(histfile);
546 }
b1589845 547
a3f4a8e1
JF
548 fputs("\n", fout_);
549 fflush(fout_);
b09da87b 550}
057f943f 551
579ed526 552static void *Map(const char *path, size_t *psize) {
b09da87b
JF
553 int fd;
554 _syscall(fd = open(path, O_RDONLY));
057f943f 555
b09da87b
JF
556 struct stat stat;
557 _syscall(fstat(fd, &stat));
558 size_t size(stat.st_size);
057f943f 559
b09da87b 560 *psize = size;
057f943f 561
b09da87b
JF
562 void *base;
563 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
057f943f 564
b09da87b
JF
565 _syscall(close(fd));
566 return base;
567}
057f943f 568
b6961e53 569void InjectLibrary(pid_t pid);
06edab7d 570
b6961e53 571int Main(int argc, char const * const argv[], char const * const envp[]) {
48e3be8a 572 bool tty(isatty(STDIN_FILENO));
75b0a457 573 bool compile(false);
de9fc71b 574 CYOptions options;
967067aa 575
da858962
JF
576 append_history$ = reinterpret_cast<int (*)(int, const char *)>(dlsym(RTLD_DEFAULT, "append_history"));
577
2aa77fd8
JF
578#ifdef CY_ATTACH
579 pid_t pid(_not(pid_t));
580#endif
581
06edab7d
JF
582 CYPool pool;
583 apr_getopt_t *state;
584 _aprcall(apr_getopt_init(&state, pool, argc, argv));
585
586 for (;;) {
587 char opt;
588 const char *arg;
589
590 apr_status_t status(apr_getopt(state,
591 "cg:n:"
2aa77fd8 592#ifdef CY_ATTACH
06edab7d 593 "p:"
2aa77fd8 594#endif
06edab7d
JF
595 "s"
596 , &opt, &arg));
597
598 switch (status) {
599 case APR_EOF:
600 goto getopt;
601 case APR_BADCH:
602 case APR_BADARG:
603 fprintf(stderr,
604 "usage: cycript [-c]"
2aa77fd8 605#ifdef CY_ATTACH
69caa5be 606 " [-p <pid|name>]"
2aa77fd8 607#endif
06edab7d
JF
608 " [<script> [<arg>...]]\n"
609 );
610 return 1;
611 default:
612 _aprcall(status);
613 }
967067aa 614
06edab7d
JF
615 switch (opt) {
616 case 'c':
617 compile = true;
618 break;
75b0a457 619
06edab7d
JF
620 case 'g':
621 if (false);
de9fc71b
JF
622 else if (strcmp(arg, "rename") == 0)
623 options.verbose_ = true;
cac61857 624#if YYDEBUG
5ef46cc0 625 else if (strcmp(arg, "bison") == 0)
06edab7d 626 bison_ = true;
cac61857 627#endif
06edab7d
JF
628 else {
629 fprintf(stderr, "invalid name for -g\n");
630 return 1;
631 }
632 break;
cac61857 633
06edab7d
JF
634 case 'n':
635 if (false);
5ef46cc0 636 else if (strcmp(arg, "minify") == 0)
06edab7d
JF
637 pretty_ = true;
638 else {
639 fprintf(stderr, "invalid name for -n\n");
640 return 1;
641 }
642 break;
11c1cc16 643
2aa77fd8 644#ifdef CY_ATTACH
06edab7d 645 case 'p': {
5ef46cc0 646 size_t size(strlen(arg));
06edab7d 647 char *end;
69caa5be 648
5ef46cc0
JF
649 pid = strtoul(arg, &end, 0);
650 if (arg + size != end) {
69caa5be
JF
651 // XXX: arg needs to be escaped in some horrendous way of doom
652 const char *command(apr_psprintf(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg));
653
654 if (FILE *pids = popen(command, "r")) {
655 char value[32];
656 size = 0;
657
658 for (;;) {
659 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
660 if (read == 0)
661 break;
662 else {
663 size += read;
664 if (size == sizeof(value)) {
665 pid = _not(pid_t);
b166b11b 666 goto fail;
69caa5be
JF
667 }
668 }
669 }
670
671 size:
672 if (size == 0)
b166b11b 673 goto fail;
69caa5be
JF
674 if (value[size - 1] == '\n') {
675 --size;
676 goto size;
677 }
678
679 value[size] = '\0';
680 size = strlen(value);
681 pid = strtoul(value, &end, 0);
b166b11b 682 if (value + size != end) fail:
69caa5be 683 pid = _not(pid_t);
69caa5be
JF
684 _syscall(pclose(pids));
685 }
686
687 if (pid == _not(pid_t)) {
688 fprintf(stderr, "invalid pid for -p\n");
689 return 1;
690 }
06edab7d
JF
691 }
692 } break;
2aa77fd8 693#endif
b10bd496 694
06edab7d
JF
695 case 's':
696 strict_ = true;
697 break;
698 }
967067aa
JF
699 } getopt:;
700
b09da87b 701 const char *script;
5ef46cc0 702 int ind(state->ind);
b09da87b 703
2aa77fd8 704#ifdef CY_ATTACH
5ef46cc0 705 if (pid != _not(pid_t) && ind < argc - 1) {
fcc64bb5
JF
706 fprintf(stderr, "-p cannot set argv\n");
707 return 1;
708 }
709
75b0a457
JF
710 if (pid != _not(pid_t) && compile) {
711 fprintf(stderr, "-p conflicts with -c\n");
712 return 1;
713 }
2aa77fd8 714#endif
75b0a457 715
5ef46cc0 716 if (ind == argc)
b09da87b
JF
717 script = NULL;
718 else {
9185d5ef 719#ifdef CY_EXECUTE
967067aa 720 // XXX: const_cast?! wtf gcc :(
5ef46cc0 721 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
9185d5ef 722#endif
5ef46cc0 723 script = argv[ind];
967067aa
JF
724 if (strcmp(script, "-") == 0)
725 script = NULL;
b09da87b
JF
726 }
727
2aa77fd8
JF
728#ifdef CY_ATTACH
729 if (pid != _not(pid_t) && script == NULL && !tty) {
730 fprintf(stderr, "non-terminal attaching to remote console\n");
48e3be8a
JF
731 return 1;
732 }
2aa77fd8 733#endif
48e3be8a 734
2aa77fd8 735#ifdef CY_ATTACH
967067aa 736 if (pid == _not(pid_t))
7e5391fd 737 client_ = -1;
967067aa 738 else {
b166b11b
JF
739 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
740 struct sockaddr_un address;
741 memset(&address, 0, sizeof(address));
742 address.sun_family = AF_UNIX;
743
744 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
745
746 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
747 _syscall(chmod(address.sun_path, 0777));
748
749 try {
750 _syscall(listen(server, 1));
751 InjectLibrary(pid);
7e5391fd 752 client_ = _syscall(accept(server, NULL, NULL));
b166b11b
JF
753 } catch (...) {
754 // XXX: exception?
755 unlink(address.sun_path);
756 throw;
757 }
758 } catch (...) {
759 _syscall(close(server));
95678376 760 throw;
b166b11b 761 }
967067aa 762 }
2aa77fd8 763#else
7e5391fd 764 client_ = -1;
2aa77fd8 765#endif
579ed526 766
48e3be8a 767 if (script == NULL && tty)
2eb8215d 768 Console(options);
b09da87b 769 else {
2eb8215d
JF
770 CYLocalPool pool;
771 CYDriver driver(script ?: "<stdin>");
b09da87b 772 cy::parser parser(driver);
b10bd496 773 Setup(driver, parser);
b09da87b 774
48e3be8a 775 char *start, *end;
b09da87b 776
48e3be8a
JF
777 if (script == NULL) {
778 start = NULL;
779 end = NULL;
2b1245e4 780
48e3be8a
JF
781 driver.file_ = stdin;
782 } else {
783 size_t size;
784 start = reinterpret_cast<char *>(Map(script, &size));
785 end = start + size;
786
787 if (size >= 2 && start[0] == '#' && start[1] == '!') {
788 start += 2;
057f943f 789
48e3be8a
JF
790 if (void *line = memchr(start, '\n', end - start))
791 start = reinterpret_cast<char *>(line);
792 else
793 start = end;
794 }
795
796 driver.data_ = start;
797 driver.size_ = end - start;
798 }
62ca2b82 799
b09da87b
JF
800 if (parser.parse() != 0 || !driver.errors_.empty()) {
801 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
802 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
b10bd496 803 } else if (driver.program_ != NULL)
7e5391fd 804 if (client_ != -1) {
e934f827 805 std::string code(start, end-start);
7e5391fd 806 Run(client_, code, stdout);
e934f827 807 } else {
fcc64bb5 808 std::ostringstream str;
029bc65b 809 CYOutput out(str, options);
de9fc71b 810 Setup(out, driver, options);
3b52fd1a 811 out << *driver.program_;
fcc64bb5 812 std::string code(str.str());
75b0a457
JF
813 if (compile)
814 std::cout << code;
98ea05a3 815 else
7e5391fd 816 Run(client_, code, stdout);
fcc64bb5 817 }
057f943f 818 }
62ca2b82 819
057f943f 820 return 0;
62ca2b82 821}
b6961e53
JF
822
823int main(int argc, char const * const argv[], char const * const envp[]) {
824 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
da858962 825
b6961e53
JF
826 if (status != APR_SUCCESS) {
827 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
828 return 1;
829 } else try {
830 return Main(argc, argv, envp);
831 } catch (const CYException &error) {
832 CYPool pool;
833 fprintf(stderr, "%s\n", error.PoolCString(pool));
834 return 1;
835 }
836}