]> git.saurik.com Git - cycript.git/blame - Console.cpp
MemberAccess is allowed Word, not just Identifier.
[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())
df24434f 214 return NULL;
7e5391fd
JF
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());
aa926c8b 267 expression = $M($C1($V("object_getClass"), thing.context_), $S("messages"));
7e5391fd
JF
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));
df24434f
JF
300 if (result == NULL)
301 return NULL;
302
7e5391fd 303 CYArray *array(dynamic_cast<CYArray *>(result));
a3f4a8e1
JF
304
305 if (array == NULL) {
306 fprintf(fout_, "\n");
307 Output(json, fout_);
308 rl_forced_update_display();
309 return NULL;
310 }
7e5391fd
JF
311
312 // XXX: use an std::set?
313 typedef std::vector<std::string> Completions;
314 Completions completions;
315
316 std::string common;
317 bool rest(false);
318
c2c9f509 319 CYForEach (element, array->elements_) {
7e5391fd
JF
320 CYString *string(dynamic_cast<CYString *>(element->value_));
321 _assert(string != NULL);
322
763aa499
JF
323 std::string completion;
324 if (string->size_ != 0)
325 completion.assign(string->value_, string->size_);
326 else if (driver.mode_ == CYDriver::AutoMessage)
327 completion = "]";
328 else
329 continue;
330
7e5391fd
JF
331 completions.push_back(completion);
332
333 if (!rest) {
334 common = completion;
335 rest = true;
336 } else {
337 size_t limit(completion.size()), size(common.size());
338 if (size > limit)
339 common = common.substr(0, limit);
340 else
341 limit = size;
342 for (limit = 0; limit != size; ++limit)
343 if (common[limit] != completion[limit])
344 break;
345 if (limit != size)
346 common = common.substr(0, limit);
347 }
348 }
349
350 size_t count(completions.size());
351 if (count == 0)
352 return NULL;
353
c41590b2
JF
354 size_t colon(common.find(':'));
355 if (colon != std::string::npos)
356 common = common.substr(0, colon + 1);
6dccefa9
JF
357 if (completions.size() == 1)
358 common += ' ';
c41590b2 359
7e5391fd
JF
360 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
361
362 results[0] = strdup(common.c_str());
363 size_t index(0);
364 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
365 results[++index] = strdup(i->c_str());
366 results[count + 1] = NULL;
367
368 return results;
369}
370
371// need char *, not const char *
372static char name_[] = "cycript";
108c5fc8 373static char break_[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
7e5391fd 374
2eb8215d
JF
375static void Console(CYOptions &options) {
376 CYPool pool;
377
b1589845
JF
378 passwd *passwd;
379 if (const char *username = getenv("LOGNAME"))
380 passwd = getpwnam(username);
381 else
382 passwd = getpwuid(getuid());
383
384 const char *basedir(apr_psprintf(pool, "%s/.cycript", passwd->pw_dir));
385 const char *histfile(apr_psprintf(pool, "%s/history", basedir));
386 size_t histlines(0);
387
7e5391fd
JF
388 rl_initialize();
389 rl_readline_name = name_;
390
b1589845
JF
391 mkdir(basedir, 0700);
392 read_history(histfile);
393
1f8eae40
JF
394 bool bypass(false);
395 bool debug(false);
6ec85c5b 396 bool expand(false);
1f8eae40 397
a3f4a8e1 398 fout_ = stdout;
057f943f 399
7e5391fd
JF
400 // rl_completer_word_break_characters is broken in libedit
401 rl_basic_word_break_characters = break_;
bc1e87aa
JF
402
403 rl_completer_word_break_characters = break_;
7e5391fd
JF
404 rl_attempted_completion_function = &Complete;
405 rl_bind_key('\t', rl_complete);
057f943f
JF
406
407 struct sigaction action;
408 sigemptyset(&action.sa_mask);
409 action.sa_handler = &sigint;
410 action.sa_flags = 0;
411 sigaction(SIGINT, &action, NULL);
412
413 restart: for (;;) {
7e5391fd 414 command_.clear();
057f943f
JF
415 std::vector<std::string> lines;
416
931b816a
JF
417 bool extra(false);
418 const char *prompt("cy# ");
419
057f943f 420 if (setjmp(ctrlc_) != 0) {
4e39dc0b 421 mode_ = Working;
a3f4a8e1
JF
422 fputs("\n", fout_);
423 fflush(fout_);
057f943f
JF
424 goto restart;
425 }
426
057f943f 427 read:
4e39dc0b 428 mode_ = Parsing;
057f943f 429 char *line(readline(prompt));
4e39dc0b 430 mode_ = Working;
057f943f
JF
431 if (line == NULL)
432 break;
67f1fc6b
JF
433 if (line[0] == '\0')
434 goto read;
931b816a
JF
435
436 if (!extra) {
437 extra = true;
6ec85c5b 438 if (line[0] == '?') {
1f8eae40
JF
439 std::string data(line + 1);
440 if (data == "bypass") {
441 bypass = !bypass;
a3f4a8e1
JF
442 fprintf(fout_, "bypass == %s\n", bypass ? "true" : "false");
443 fflush(fout_);
1f8eae40
JF
444 } else if (data == "debug") {
445 debug = !debug;
a3f4a8e1
JF
446 fprintf(fout_, "debug == %s\n", debug ? "true" : "false");
447 fflush(fout_);
6ec85c5b
JF
448 } else if (data == "expand") {
449 expand = !expand;
a3f4a8e1
JF
450 fprintf(fout_, "expand == %s\n", expand ? "true" : "false");
451 fflush(fout_);
1f8eae40 452 }
d35a3b07 453 add_history(line);
b1589845 454 ++histlines;
931b816a
JF
455 goto restart;
456 }
457 }
458
7e5391fd 459 command_ += line;
e818f0e0
JF
460
461 char *begin(line), *end(line + strlen(line));
462 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
463 *nl = '\0';
464 lines.push_back(begin);
465 begin = nl + 1;
466 }
467
468 lines.push_back(begin);
469
057f943f
JF
470 free(line);
471
1f8eae40
JF
472 std::string code;
473
474 if (bypass)
7e5391fd 475 code = command_;
1f8eae40 476 else {
2eb8215d 477 CYLocalPool pool;
7e5391fd 478 CYDriver driver;
1f8eae40 479 cy::parser parser(driver);
b10bd496 480 Setup(driver, parser);
1f8eae40 481
7e5391fd
JF
482 driver.data_ = command_.c_str();
483 driver.size_ = command_.size();
1f8eae40
JF
484
485 if (parser.parse() != 0 || !driver.errors_.empty()) {
f0360d51
JF
486 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
487 cy::position begin(error->location_.begin);
c247172c 488 if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) {
f0360d51 489 cy::position end(error->location_.end);
48e3be8a 490
f0360d51
JF
491 if (begin.line != lines.size()) {
492 std::cerr << " | ";
493 std::cerr << lines[begin.line - 1] << std::endl;
494 }
48e3be8a 495
c52a09b8 496 std::cerr << "....";
97c8a8fc 497 for (size_t i(0); i != begin.column; ++i)
f0360d51 498 std::cerr << '.';
48e3be8a 499 if (begin.line != end.line || begin.column == end.column)
f0360d51
JF
500 std::cerr << '^';
501 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
502 std::cerr << '^';
503 std::cerr << std::endl;
48e3be8a 504
f0360d51
JF
505 std::cerr << " | ";
506 std::cerr << error->message_ << std::endl;
48e3be8a 507
7e5391fd 508 add_history(command_.c_str());
b1589845 509 ++histlines;
1f8eae40
JF
510 goto restart;
511 }
512 }
057f943f 513
1f8eae40 514 driver.errors_.clear();
057f943f 515
7e5391fd 516 command_ += '\n';
1f8eae40
JF
517 prompt = "cy> ";
518 goto read;
057f943f
JF
519 }
520
b10bd496 521 if (driver.program_ == NULL)
1f8eae40 522 goto restart;
057f943f 523
7e5391fd
JF
524 if (client_ != -1)
525 code = command_;
967067aa
JF
526 else {
527 std::ostringstream str;
029bc65b 528 CYOutput out(str, options);
de9fc71b 529 Setup(out, driver, options);
3b52fd1a 530 out << *driver.program_;
967067aa
JF
531 code = str.str();
532 }
057f943f
JF
533 }
534
7e5391fd 535 add_history(command_.c_str());
b1589845 536 ++histlines;
057f943f 537
1f8eae40
JF
538 if (debug)
539 std::cout << code << std::endl;
057f943f 540
a3f4a8e1 541 Run(client_, code, fout_, expand);
b09da87b 542 }
057f943f 543
da858962
JF
544 if (append_history$ != NULL) {
545 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
546 (*append_history$)(histlines, histfile);
547 } else {
548 write_history(histfile);
549 }
b1589845 550
a3f4a8e1
JF
551 fputs("\n", fout_);
552 fflush(fout_);
b09da87b 553}
057f943f 554
579ed526 555static void *Map(const char *path, size_t *psize) {
b09da87b
JF
556 int fd;
557 _syscall(fd = open(path, O_RDONLY));
057f943f 558
b09da87b
JF
559 struct stat stat;
560 _syscall(fstat(fd, &stat));
561 size_t size(stat.st_size);
057f943f 562
b09da87b 563 *psize = size;
057f943f 564
b09da87b
JF
565 void *base;
566 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
057f943f 567
b09da87b
JF
568 _syscall(close(fd));
569 return base;
570}
057f943f 571
b6961e53 572void InjectLibrary(pid_t pid);
06edab7d 573
b6961e53 574int Main(int argc, char const * const argv[], char const * const envp[]) {
48e3be8a 575 bool tty(isatty(STDIN_FILENO));
75b0a457 576 bool compile(false);
de9fc71b 577 CYOptions options;
967067aa 578
e4676127 579 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
da858962 580
2aa77fd8
JF
581#ifdef CY_ATTACH
582 pid_t pid(_not(pid_t));
583#endif
584
06edab7d
JF
585 CYPool pool;
586 apr_getopt_t *state;
587 _aprcall(apr_getopt_init(&state, pool, argc, argv));
588
589 for (;;) {
590 char opt;
591 const char *arg;
592
593 apr_status_t status(apr_getopt(state,
594 "cg:n:"
2aa77fd8 595#ifdef CY_ATTACH
06edab7d 596 "p:"
2aa77fd8 597#endif
06edab7d
JF
598 "s"
599 , &opt, &arg));
600
601 switch (status) {
602 case APR_EOF:
603 goto getopt;
604 case APR_BADCH:
605 case APR_BADARG:
606 fprintf(stderr,
607 "usage: cycript [-c]"
2aa77fd8 608#ifdef CY_ATTACH
69caa5be 609 " [-p <pid|name>]"
2aa77fd8 610#endif
06edab7d
JF
611 " [<script> [<arg>...]]\n"
612 );
613 return 1;
614 default:
615 _aprcall(status);
616 }
967067aa 617
06edab7d
JF
618 switch (opt) {
619 case 'c':
620 compile = true;
621 break;
75b0a457 622
06edab7d
JF
623 case 'g':
624 if (false);
de9fc71b
JF
625 else if (strcmp(arg, "rename") == 0)
626 options.verbose_ = true;
cac61857 627#if YYDEBUG
5ef46cc0 628 else if (strcmp(arg, "bison") == 0)
06edab7d 629 bison_ = true;
cac61857 630#endif
06edab7d
JF
631 else {
632 fprintf(stderr, "invalid name for -g\n");
633 return 1;
634 }
635 break;
cac61857 636
06edab7d
JF
637 case 'n':
638 if (false);
5ef46cc0 639 else if (strcmp(arg, "minify") == 0)
06edab7d
JF
640 pretty_ = true;
641 else {
642 fprintf(stderr, "invalid name for -n\n");
643 return 1;
644 }
645 break;
11c1cc16 646
2aa77fd8 647#ifdef CY_ATTACH
06edab7d 648 case 'p': {
5ef46cc0 649 size_t size(strlen(arg));
06edab7d 650 char *end;
69caa5be 651
5ef46cc0
JF
652 pid = strtoul(arg, &end, 0);
653 if (arg + size != end) {
69caa5be
JF
654 // XXX: arg needs to be escaped in some horrendous way of doom
655 const char *command(apr_psprintf(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg));
656
657 if (FILE *pids = popen(command, "r")) {
658 char value[32];
659 size = 0;
660
661 for (;;) {
662 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
663 if (read == 0)
664 break;
665 else {
666 size += read;
667 if (size == sizeof(value)) {
668 pid = _not(pid_t);
b166b11b 669 goto fail;
69caa5be
JF
670 }
671 }
672 }
673
674 size:
675 if (size == 0)
b166b11b 676 goto fail;
69caa5be
JF
677 if (value[size - 1] == '\n') {
678 --size;
679 goto size;
680 }
681
682 value[size] = '\0';
683 size = strlen(value);
684 pid = strtoul(value, &end, 0);
b166b11b 685 if (value + size != end) fail:
69caa5be 686 pid = _not(pid_t);
69caa5be
JF
687 _syscall(pclose(pids));
688 }
689
690 if (pid == _not(pid_t)) {
691 fprintf(stderr, "invalid pid for -p\n");
692 return 1;
693 }
06edab7d
JF
694 }
695 } break;
2aa77fd8 696#endif
b10bd496 697
06edab7d
JF
698 case 's':
699 strict_ = true;
700 break;
701 }
967067aa
JF
702 } getopt:;
703
b09da87b 704 const char *script;
5ef46cc0 705 int ind(state->ind);
b09da87b 706
2aa77fd8 707#ifdef CY_ATTACH
5ef46cc0 708 if (pid != _not(pid_t) && ind < argc - 1) {
fcc64bb5
JF
709 fprintf(stderr, "-p cannot set argv\n");
710 return 1;
711 }
712
75b0a457
JF
713 if (pid != _not(pid_t) && compile) {
714 fprintf(stderr, "-p conflicts with -c\n");
715 return 1;
716 }
2aa77fd8 717#endif
75b0a457 718
5ef46cc0 719 if (ind == argc)
b09da87b
JF
720 script = NULL;
721 else {
9185d5ef 722#ifdef CY_EXECUTE
967067aa 723 // XXX: const_cast?! wtf gcc :(
5ef46cc0 724 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
9185d5ef 725#endif
5ef46cc0 726 script = argv[ind];
967067aa
JF
727 if (strcmp(script, "-") == 0)
728 script = NULL;
b09da87b
JF
729 }
730
2aa77fd8
JF
731#ifdef CY_ATTACH
732 if (pid != _not(pid_t) && script == NULL && !tty) {
733 fprintf(stderr, "non-terminal attaching to remote console\n");
48e3be8a
JF
734 return 1;
735 }
2aa77fd8 736#endif
48e3be8a 737
2aa77fd8 738#ifdef CY_ATTACH
967067aa 739 if (pid == _not(pid_t))
7e5391fd 740 client_ = -1;
967067aa 741 else {
b166b11b
JF
742 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
743 struct sockaddr_un address;
744 memset(&address, 0, sizeof(address));
745 address.sun_family = AF_UNIX;
746
747 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
748
749 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
750 _syscall(chmod(address.sun_path, 0777));
751
752 try {
753 _syscall(listen(server, 1));
754 InjectLibrary(pid);
7e5391fd 755 client_ = _syscall(accept(server, NULL, NULL));
b166b11b
JF
756 } catch (...) {
757 // XXX: exception?
758 unlink(address.sun_path);
759 throw;
760 }
761 } catch (...) {
762 _syscall(close(server));
95678376 763 throw;
b166b11b 764 }
967067aa 765 }
2aa77fd8 766#else
7e5391fd 767 client_ = -1;
2aa77fd8 768#endif
579ed526 769
48e3be8a 770 if (script == NULL && tty)
2eb8215d 771 Console(options);
b09da87b 772 else {
2eb8215d
JF
773 CYLocalPool pool;
774 CYDriver driver(script ?: "<stdin>");
b09da87b 775 cy::parser parser(driver);
b10bd496 776 Setup(driver, parser);
b09da87b 777
48e3be8a 778 char *start, *end;
b09da87b 779
48e3be8a
JF
780 if (script == NULL) {
781 start = NULL;
782 end = NULL;
2b1245e4 783
48e3be8a
JF
784 driver.file_ = stdin;
785 } else {
786 size_t size;
787 start = reinterpret_cast<char *>(Map(script, &size));
788 end = start + size;
789
790 if (size >= 2 && start[0] == '#' && start[1] == '!') {
791 start += 2;
057f943f 792
48e3be8a
JF
793 if (void *line = memchr(start, '\n', end - start))
794 start = reinterpret_cast<char *>(line);
795 else
796 start = end;
797 }
798
799 driver.data_ = start;
800 driver.size_ = end - start;
801 }
62ca2b82 802
b09da87b
JF
803 if (parser.parse() != 0 || !driver.errors_.empty()) {
804 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
805 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
b10bd496 806 } else if (driver.program_ != NULL)
7e5391fd 807 if (client_ != -1) {
e934f827 808 std::string code(start, end-start);
7e5391fd 809 Run(client_, code, stdout);
e934f827 810 } else {
fcc64bb5 811 std::ostringstream str;
029bc65b 812 CYOutput out(str, options);
de9fc71b 813 Setup(out, driver, options);
3b52fd1a 814 out << *driver.program_;
fcc64bb5 815 std::string code(str.str());
75b0a457
JF
816 if (compile)
817 std::cout << code;
98ea05a3 818 else
7e5391fd 819 Run(client_, code, stdout);
fcc64bb5 820 }
057f943f 821 }
62ca2b82 822
057f943f 823 return 0;
62ca2b82 824}
b6961e53
JF
825
826int main(int argc, char const * const argv[], char const * const envp[]) {
827 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
da858962 828
b6961e53
JF
829 if (status != APR_SUCCESS) {
830 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
831 return 1;
832 } else try {
833 return Main(argc, argv, envp);
834 } catch (const CYException &error) {
835 CYPool pool;
836 fprintf(stderr, "%s\n", error.PoolCString(pool));
837 return 1;
838 }
839}