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