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