]> git.saurik.com Git - cycript.git/blame - Console.cpp
Cobble injection into heavily sandboxed processes.
[cycript.git] / Console.cpp
CommitLineData
b3378a02 1/* Cycript - Optimizing JavaScript Compiler/Runtime
f95d2598 2 * Copyright (C) 2009-2014 Jay Freeman (saurik)
b4aa79af
JF
3*/
4
f95d2598 5/* GNU Affero General Public License, Version 3 {{{ */
b4aa79af 6/*
f95d2598
JF
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
c15969fd 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
f95d2598
JF
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
b3378a02 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 28#include <cstdio>
0df6a201 29#include <fstream>
057f943f
JF
30#include <sstream>
31
32#include <setjmp.h>
33
aff87425
DWT
34#ifdef HAVE_READLINE_H
35#include <readline.h>
36#else
057f943f 37#include <readline/readline.h>
aff87425
DWT
38#endif
39
40#ifdef HAVE_HISTORY_H
41#include <history.h>
42#else
057f943f 43#include <readline/history.h>
aff87425 44#endif
057f943f 45
b09da87b 46#include <errno.h>
10d0e915
JF
47#include <getopt.h>
48#include <signal.h>
b09da87b
JF
49#include <unistd.h>
50
666eedb9 51#include <sys/socket.h>
b09da87b
JF
52#include <sys/types.h>
53#include <sys/stat.h>
54#include <fcntl.h>
666eedb9 55#include <netdb.h>
b09da87b 56
967067aa
JF
57#include <sys/types.h>
58#include <sys/socket.h>
59#include <netinet/in.h>
60#include <sys/un.h>
b1589845 61#include <pwd.h>
967067aa 62
da858962
JF
63#include <dlfcn.h>
64
74296173 65#include "Display.hpp"
b12a9965
JF
66#include "Replace.hpp"
67
68#include "Cycript.tab.hh"
69#include "Driver.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
36bf49c4 111void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) {
11c1cc16 112 out.pretty_ = pretty_;
2eb8215d 113 CYContext context(options);
36bf49c4
JF
114 if (lower)
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
89d16b11 125 json = CYExecute(CYGetJSContext(), 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;
a1f3555e
JF
137 _assert(CYSendAll(client, &size, sizeof(size)));
138 _assert(CYSendAll(client, code.data, code.size));
4e39dc0b 139 mode_ = Waiting;
a1f3555e 140 _assert(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]);
a1f3555e 145 _assert(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
fd5cdf97
JF
228 CYStatement *statement(driver.program_->statements_);
229 _assert(statement != NULL);
230 _assert(statement->next_ == NULL);
e06e5ee1 231
fd5cdf97
JF
232 CYExpress *express(dynamic_cast<CYExpress *>(driver.program_->statements_));
233 _assert(express != NULL);
234
235 return express->expression_;
7e5391fd
JF
236}
237
238static int client_;
239
240static char **Complete(const char *word, int start, int end) {
10d0e915 241 rl_attempted_completion_over = ~0;
7e5391fd 242
2eb8215d 243 CYLocalPool pool;
7e5391fd
JF
244
245 std::string line(rl_line_buffer, start);
d3b63265
JF
246 std::istringstream stream(command_ + line);
247 CYDriver driver(stream);
7e5391fd
JF
248
249 driver.auto_ = true;
250
d3b63265
JF
251 cy::parser parser(driver);
252 Setup(driver, parser);
253
7e5391fd
JF
254 if (parser.parse() != 0 || !driver.errors_.empty())
255 return NULL;
256
257 if (driver.mode_ == CYDriver::AutoNone)
258 return NULL;
259
260 CYExpression *expression;
261
262 CYOptions options;
2eb8215d 263 CYContext context(options);
7e5391fd
JF
264
265 std::ostringstream prefix;
266
267 switch (driver.mode_) {
268 case CYDriver::AutoPrimary:
269 expression = $ CYThis();
270 break;
271
272 case CYDriver::AutoDirect:
273 expression = driver.context_;
274 break;
275
276 case CYDriver::AutoIndirect:
277 expression = $ CYIndirect(driver.context_);
278 break;
279
280 case CYDriver::AutoMessage: {
281 CYDriver::Context &thing(driver.contexts_.back());
aa926c8b 282 expression = $M($C1($V("object_getClass"), thing.context_), $S("messages"));
7e5391fd
JF
283 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
284 prefix << (*part)->word_ << ':';
285 } break;
286
287 default:
288 _assert(false);
289 }
290
2a18313c 291 std::string begin(prefix.str());
7e5391fd 292
2eb8215d 293 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
2a18313c 294 " function(object, prefix, word) {\n"
7e5391fd 295 " var names = [];\n"
5a3f7a01
JF
296 " var before = prefix.length;\n"
297 " prefix += word;\n"
298 " var entire = prefix.length;\n"
3e6377db 299 " for (var name in object)\n"
5a3f7a01
JF
300 " if (name.substring(0, entire) == prefix)\n"
301 " names.push(name.substr(before));\n"
7e5391fd
JF
302 " return names;\n"
303 " }\n"
2a18313c 304 ), expression, $S(begin.c_str()), $S(word))));
7e5391fd
JF
305
306 driver.program_->Replace(context);
307
308 std::ostringstream str;
309 CYOutput out(str, options);
310 out << *driver.program_;
311
312 std::string code(str.str());
313 CYUTF8String json(Run(pool, client_, code));
1b2613d3 314 // XXX: if this fails we should not try to parse it
7e5391fd 315
2eb8215d 316 CYExpression *result(ParseExpression(json));
df24434f
JF
317 if (result == NULL)
318 return NULL;
319
fd5cdf97 320 CYArray *array(dynamic_cast<CYArray *>(result->Primitive(context)));
a3f4a8e1 321 if (array == NULL) {
2e2ed904 322 *out_ << '\n';
82a02ede 323 Output(false, json, out_);
a3f4a8e1
JF
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
c2c9f509 335 CYForEach (element, array->elements_) {
7e5391fd
JF
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 390
da136f88
JF
391class History {
392 private:
393 std::string histfile_;
394 size_t histlines_;
395
396 public:
397 History(std::string histfile) :
398 histfile_(histfile),
399 histlines_(0)
400 {
401 read_history(histfile_.c_str());
402 }
403
404 ~History() {
405 if (append_history$ != NULL) {
f61fec22
JF
406 int fd(_syscall(open(histfile_.c_str(), O_CREAT | O_WRONLY, 0600)));
407 _syscall(close(fd));
da136f88
JF
408 _assert((*append_history$)(histlines_, histfile_.c_str()) == 0);
409 } else {
410 _assert(write_history(histfile_.c_str()) == 0);
411 }
412 }
413
414 void operator +=(const std::string &command) {
415 add_history(command_.c_str());
416 ++histlines_;
417 }
418};
419
2eb8215d 420static void Console(CYOptions &options) {
1210260f
JF
421 std::string basedir;
422 if (const char *home = getenv("HOME"))
423 basedir = home;
424 else {
425 passwd *passwd;
426 if (const char *username = getenv("LOGNAME"))
427 passwd = getpwnam(username);
428 else
429 passwd = getpwuid(getuid());
430 basedir = passwd->pw_dir;
431 }
b1589845 432
da136f88
JF
433 basedir += "/.cycript";
434 mkdir(basedir.c_str(), 0700);
b1589845 435
7e5391fd
JF
436 rl_initialize();
437 rl_readline_name = name_;
438
da136f88 439 History history(basedir + "/history");
b1589845 440
1f8eae40
JF
441 bool bypass(false);
442 bool debug(false);
6ec85c5b 443 bool expand(false);
36bf49c4 444 bool lower(true);
cd98d280 445 bool syntax(true);
1f8eae40 446
2e2ed904 447 out_ = &std::cout;
057f943f 448
7e5391fd
JF
449 // rl_completer_word_break_characters is broken in libedit
450 rl_basic_word_break_characters = break_;
bc1e87aa
JF
451
452 rl_completer_word_break_characters = break_;
7e5391fd
JF
453 rl_attempted_completion_function = &Complete;
454 rl_bind_key('\t', rl_complete);
057f943f
JF
455
456 struct sigaction action;
457 sigemptyset(&action.sa_mask);
458 action.sa_handler = &sigint;
459 action.sa_flags = 0;
460 sigaction(SIGINT, &action, NULL);
461
462 restart: for (;;) {
7e5391fd 463 command_.clear();
057f943f
JF
464 std::vector<std::string> lines;
465
931b816a
JF
466 bool extra(false);
467 const char *prompt("cy# ");
468
057f943f 469 if (setjmp(ctrlc_) != 0) {
4e39dc0b 470 mode_ = Working;
2e2ed904 471 *out_ << std::endl;
057f943f
JF
472 goto restart;
473 }
474
057f943f 475 read:
cd98d280
JF
476
477#if RL_READLINE_VERSION >= 0x0600
8a81192b 478 if (syntax)
cd98d280 479 rl_redisplay_function = CYDisplayUpdate;
8a81192b 480 else
cd98d280 481 rl_redisplay_function = rl_redisplay;
cd98d280
JF
482#endif
483
4e39dc0b 484 mode_ = Parsing;
057f943f 485 char *line(readline(prompt));
4e39dc0b 486 mode_ = Working;
cd98d280 487
79357996
JF
488 if (line == NULL) {
489 *out_ << std::endl;
057f943f 490 break;
79357996 491 } else if (line[0] == '\0')
67f1fc6b 492 goto read;
931b816a
JF
493
494 if (!extra) {
495 extra = true;
6ec85c5b 496 if (line[0] == '?') {
1f8eae40
JF
497 std::string data(line + 1);
498 if (data == "bypass") {
499 bypass = !bypass;
2e2ed904 500 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
1f8eae40
JF
501 } else if (data == "debug") {
502 debug = !debug;
2e2ed904 503 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
8fab8594
JF
504 } else if (data == "destroy") {
505 CYDestroyContext();
51b6165e 506 } else if (data == "gc") {
e7ff0158 507 *out_ << "collecting... " << std::flush;
51b6165e 508 CYGarbageCollect(CYGetJSContext());
e7ff0158 509 *out_ << "done." << std::endl;
6a5fd0d9
JF
510 } else if (data == "exit") {
511 return;
6ec85c5b
JF
512 } else if (data == "expand") {
513 expand = !expand;
2e2ed904 514 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
36bf49c4
JF
515 } else if (data == "lower") {
516 lower = !lower;
517 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
82a02ede
JF
518 } else if (data == "syntax") {
519 syntax = !syntax;
520 *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl;
1f8eae40 521 }
be8c2078
JF
522 command_ = line;
523 history += command_;
931b816a
JF
524 goto restart;
525 }
526 }
527
7e5391fd 528 command_ += line;
e818f0e0
JF
529
530 char *begin(line), *end(line + strlen(line));
531 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
532 *nl = '\0';
533 lines.push_back(begin);
534 begin = nl + 1;
535 }
536
537 lines.push_back(begin);
538
057f943f
JF
539 free(line);
540
1f8eae40
JF
541 std::string code;
542
543 if (bypass)
7e5391fd 544 code = command_;
1f8eae40 545 else {
2eb8215d 546 CYLocalPool pool;
d3b63265
JF
547
548 std::istringstream stream(command_);
549 CYDriver driver(stream);
550
1f8eae40 551 cy::parser parser(driver);
b10bd496 552 Setup(driver, parser);
1f8eae40 553
1f8eae40 554 if (parser.parse() != 0 || !driver.errors_.empty()) {
f0360d51
JF
555 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
556 cy::position begin(error->location_.begin);
c247172c 557 if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) {
f0360d51 558 cy::position end(error->location_.end);
48e3be8a 559
f0360d51
JF
560 if (begin.line != lines.size()) {
561 std::cerr << " | ";
562 std::cerr << lines[begin.line - 1] << std::endl;
563 }
48e3be8a 564
c52a09b8 565 std::cerr << "....";
97c8a8fc 566 for (size_t i(0); i != begin.column; ++i)
f0360d51 567 std::cerr << '.';
48e3be8a 568 if (begin.line != end.line || begin.column == end.column)
f0360d51
JF
569 std::cerr << '^';
570 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
571 std::cerr << '^';
572 std::cerr << std::endl;
48e3be8a 573
f0360d51
JF
574 std::cerr << " | ";
575 std::cerr << error->message_ << std::endl;
48e3be8a 576
da136f88 577 history += command_;
1f8eae40
JF
578 goto restart;
579 }
580 }
057f943f 581
1f8eae40 582 driver.errors_.clear();
057f943f 583
7e5391fd 584 command_ += '\n';
1f8eae40
JF
585 prompt = "cy> ";
586 goto read;
057f943f
JF
587 }
588
b10bd496 589 if (driver.program_ == NULL)
1f8eae40 590 goto restart;
057f943f 591
0df6a201
JF
592 std::ostringstream str;
593 CYOutput out(str, options);
36bf49c4 594 Setup(out, driver, options, lower);
0df6a201
JF
595 out << *driver.program_;
596 code = str.str();
057f943f
JF
597 }
598
da136f88 599 history += command_;
057f943f 600
82a02ede 601 if (debug) {
f43fcb85 602 std::cout << "cy= ";
82a02ede
JF
603 Write(syntax, code.c_str(), code.size(), std::cout);
604 std::cout << std::endl;
605 }
057f943f 606
82a02ede 607 Run(client_, syntax, code, out_, expand);
b09da87b 608 }
b09da87b 609}
057f943f 610
f8d45a20 611void InjectLibrary(pid_t, int, const char *[]);
06edab7d 612
10d0e915 613int Main(int argc, char * const argv[], char const * const envp[]) {
48e3be8a 614 bool tty(isatty(STDIN_FILENO));
75b0a457 615 bool compile(false);
96746747 616 bool target(false);
de9fc71b 617 CYOptions options;
967067aa 618
e4676127 619 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
da858962 620
2aa77fd8
JF
621#ifdef CY_ATTACH
622 pid_t pid(_not(pid_t));
623#endif
624
666eedb9
JF
625 const char *host(NULL);
626 const char *port(NULL);
627
10d0e915 628 optind = 1;
06edab7d
JF
629
630 for (;;) {
10d0e915
JF
631 int option(getopt_long(argc, argv,
632 "c"
633 "g:"
634 "n:"
2aa77fd8 635#ifdef CY_ATTACH
10d0e915 636 "p:"
2aa77fd8 637#endif
10d0e915
JF
638 "r:"
639 "s"
f61fec22 640 , (const struct option[]) {
10d0e915
JF
641 {NULL, no_argument, NULL, 'c'},
642 {NULL, required_argument, NULL, 'g'},
643 {NULL, required_argument, NULL, 'n'},
644#ifdef CY_ATTACH
645 {NULL, required_argument, NULL, 'p'},
646#endif
647 {NULL, required_argument, NULL, 'r'},
648 {NULL, no_argument, NULL, 's'},
649 {0, 0, 0, 0}}, NULL));
06edab7d 650
10d0e915
JF
651 switch (option) {
652 case -1:
06edab7d 653 goto getopt;
10d0e915
JF
654
655 case ':':
656 case '?':
06edab7d
JF
657 fprintf(stderr,
658 "usage: cycript [-c]"
2aa77fd8 659#ifdef CY_ATTACH
69caa5be 660 " [-p <pid|name>]"
2aa77fd8 661#endif
666eedb9 662 " [-r <host:port>]"
06edab7d
JF
663 " [<script> [<arg>...]]\n"
664 );
665 return 1;
967067aa 666
96746747
JF
667 target:
668 if (!target)
669 target = true;
670 else {
671 fprintf(stderr, "only one of -[c"
672#ifdef CY_ATTACH
673 "p"
674#endif
675 "r] may be used at a time\n");
676 return 1;
677 }
678 break;
679
06edab7d
JF
680 case 'c':
681 compile = true;
96746747 682 goto target;
75b0a457 683
06edab7d
JF
684 case 'g':
685 if (false);
10d0e915 686 else if (strcmp(optarg, "rename") == 0)
de9fc71b 687 options.verbose_ = true;
cac61857 688#if YYDEBUG
10d0e915 689 else if (strcmp(optarg, "bison") == 0)
06edab7d 690 bison_ = true;
cac61857 691#endif
06edab7d
JF
692 else {
693 fprintf(stderr, "invalid name for -g\n");
694 return 1;
695 }
696 break;
cac61857 697
06edab7d
JF
698 case 'n':
699 if (false);
10d0e915 700 else if (strcmp(optarg, "minify") == 0)
06edab7d
JF
701 pretty_ = true;
702 else {
703 fprintf(stderr, "invalid name for -n\n");
704 return 1;
705 }
706 break;
11c1cc16 707
2aa77fd8 708#ifdef CY_ATTACH
06edab7d 709 case 'p': {
10d0e915 710 size_t size(strlen(optarg));
06edab7d 711 char *end;
69caa5be 712
10d0e915
JF
713 pid = strtoul(optarg, &end, 0);
714 if (optarg + size != end) {
69caa5be 715 // XXX: arg needs to be escaped in some horrendous way of doom
10d0e915
JF
716 // XXX: this is a memory leak now because I just don't care enough
717 char *command;
718 asprintf(&command, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg);
69caa5be
JF
719
720 if (FILE *pids = popen(command, "r")) {
721 char value[32];
722 size = 0;
723
724 for (;;) {
725 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
726 if (read == 0)
727 break;
728 else {
729 size += read;
04aa6240 730 if (size == sizeof(value))
b166b11b 731 goto fail;
69caa5be
JF
732 }
733 }
734
735 size:
736 if (size == 0)
b166b11b 737 goto fail;
69caa5be
JF
738 if (value[size - 1] == '\n') {
739 --size;
740 goto size;
741 }
742
743 value[size] = '\0';
744 size = strlen(value);
745 pid = strtoul(value, &end, 0);
b166b11b 746 if (value + size != end) fail:
69caa5be 747 pid = _not(pid_t);
69caa5be
JF
748 _syscall(pclose(pids));
749 }
750
751 if (pid == _not(pid_t)) {
10d0e915 752 fprintf(stderr, "unable to find process `%s' using ps\n", optarg);
69caa5be
JF
753 return 1;
754 }
06edab7d 755 }
96746747 756 } goto target;
2aa77fd8 757#endif
b10bd496 758
666eedb9 759 case 'r': {
10d0e915 760 //size_t size(strlen(optarg));
666eedb9 761
10d0e915 762 char *colon(strrchr(optarg, ':'));
666eedb9
JF
763 if (colon == NULL) {
764 fprintf(stderr, "missing colon in hostspec\n");
765 return 1;
766 }
767
768 /*char *end;
769 port = strtoul(colon + 1, &end, 10);
10d0e915 770 if (end != optarg + size) {
666eedb9
JF
771 fprintf(stderr, "invalid port in hostspec\n");
772 return 1;
773 }*/
774
10d0e915 775 host = optarg;
666eedb9
JF
776 *colon = '\0';
777 port = colon + 1;
96746747 778 } goto target;
666eedb9 779
06edab7d
JF
780 case 's':
781 strict_ = true;
782 break;
10d0e915
JF
783
784 default:
785 _assert(false);
06edab7d 786 }
10d0e915
JF
787 }
788
789 getopt:
790 argc -= optind;
791 argv += optind;
967067aa 792
b09da87b
JF
793 const char *script;
794
2aa77fd8 795#ifdef CY_ATTACH
10d0e915 796 if (pid != _not(pid_t) && argc > 1) {
fcc64bb5
JF
797 fprintf(stderr, "-p cannot set argv\n");
798 return 1;
799 }
2aa77fd8 800#endif
75b0a457 801
10d0e915 802 if (argc == 0)
b09da87b
JF
803 script = NULL;
804 else {
9185d5ef 805#ifdef CY_EXECUTE
967067aa 806 // XXX: const_cast?! wtf gcc :(
10d0e915 807 CYSetArgs(argc - 1, const_cast<const char **>(argv + 1));
9185d5ef 808#endif
10d0e915 809 script = argv[0];
967067aa
JF
810 if (strcmp(script, "-") == 0)
811 script = NULL;
b09da87b
JF
812 }
813
2aa77fd8 814#ifdef CY_ATTACH
967067aa 815 if (pid == _not(pid_t))
7e5391fd 816 client_ = -1;
967067aa 817 else {
46d13f4c
JF
818 struct Socket {
819 int fd_;
b166b11b 820
46d13f4c
JF
821 Socket(int fd) :
822 fd_(fd)
823 {
824 }
96cc7967 825
46d13f4c
JF
826 ~Socket() {
827 close(fd_);
828 }
96cc7967 829
46d13f4c
JF
830 operator int() {
831 return fd_;
832 }
833 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
96cc7967 834
46d13f4c
JF
835 struct sockaddr_un address;
836 memset(&address, 0, sizeof(address));
837 address.sun_family = AF_UNIX;
b166b11b 838
f8d45a20
JF
839 const char *tmp;
840#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
841 tmp = "/Library/Caches";
842#else
843 tmp = "/tmp";
844#endif
845
846 sprintf(address.sun_path, "%s/.s.cy.%u", tmp, getpid());
46d13f4c 847 unlink(address.sun_path);
b166b11b 848
46d13f4c
JF
849 struct File {
850 const char *path_;
851
852 File(const char *path) :
853 path_(path)
854 {
855 }
856
857 ~File() {
858 unlink(path_);
859 }
860 } file(address.sun_path);
861
862 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
863 _syscall(chmod(address.sun_path, 0777));
864
865 _syscall(listen(server, 1));
f8d45a20 866 InjectLibrary(pid, 1, (const char *[]) {address.sun_path, NULL});
46d13f4c 867 client_ = _syscall(accept(server, NULL, NULL));
967067aa 868 }
2aa77fd8 869#else
7e5391fd 870 client_ = -1;
2aa77fd8 871#endif
579ed526 872
666eedb9
JF
873 if (client_ == -1 && host != NULL && port != NULL) {
874 struct addrinfo hints;
875 memset(&hints, 0, sizeof(hints));
876 hints.ai_family = AF_UNSPEC;
877 hints.ai_socktype = SOCK_STREAM;
878 hints.ai_protocol = 0;
879 hints.ai_flags = 0;
880
881 struct addrinfo *infos;
882 _syscall(getaddrinfo(host, port, &hints, &infos));
883
884 _assert(infos != NULL); try {
885 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
886 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
887 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
888 client_ = client;
889 break;
890 } catch (...) {
891 _syscall(close(client));
892 throw;
893 }
894 }
895 } catch (...) {
896 freeaddrinfo(infos);
897 throw;
898 }
899 }
900
48e3be8a 901 if (script == NULL && tty)
2eb8215d 902 Console(options);
b09da87b 903 else {
2eb8215d 904 CYLocalPool pool;
b09da87b 905
0df6a201 906 std::istream *stream;
48e3be8a 907 if (script == NULL) {
0df6a201
JF
908 stream = &std::cin;
909 script = "<stdin>";
48e3be8a 910 } else {
0df6a201
JF
911 stream = new std::fstream(script, std::ios::in | std::ios::binary);
912 _assert(!stream->fail());
48e3be8a 913 }
62ca2b82 914
0df6a201 915 CYDriver driver(*stream, script);
d3b63265
JF
916 cy::parser parser(driver);
917 Setup(driver, parser);
918
b09da87b
JF
919 if (parser.parse() != 0 || !driver.errors_.empty()) {
920 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
921 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
0df6a201
JF
922 } else if (driver.program_ != NULL) {
923 std::ostringstream str;
924 CYOutput out(str, options);
36bf49c4 925 Setup(out, driver, options, true);
0df6a201
JF
926 out << *driver.program_;
927 std::string code(str.str());
928 if (compile)
929 std::cout << code;
930 else
82a02ede 931 Run(client_, false, code, &std::cout);
0df6a201 932 }
057f943f 933 }
62ca2b82 934
057f943f 935 return 0;
62ca2b82 936}
b6961e53 937
10d0e915
JF
938int main(int argc, char * const argv[], char const * const envp[]) {
939 try {
b6961e53
JF
940 return Main(argc, argv, envp);
941 } catch (const CYException &error) {
942 CYPool pool;
943 fprintf(stderr, "%s\n", error.PoolCString(pool));
944 return 1;
945 }
946}