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