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