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