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