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