]> git.saurik.com Git - cycript.git/blame - Console.cpp
Bison does not actually care about the stack size.
[cycript.git] / Console.cpp
CommitLineData
b3378a02 1/* Cycript - Optimizing JavaScript Compiler/Runtime
c1d3e52e 2 * Copyright (C) 2009-2015 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:
b0ba908c
JF
88 CYCancel();
89 return;
4e39dc0b
JF
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
36bf49c4 112void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) {
11c1cc16 113 out.pretty_ = pretty_;
2eb8215d 114 CYContext context(options);
36bf49c4
JF
115 if (lower)
116 driver.program_->Replace(context);
11c1cc16
JF
117}
118
7e5391fd 119static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
967067aa 120 const char *json;
9d79cefc 121 uint32_t size;
7e5391fd 122
b166b11b 123 if (client == -1) {
4e39dc0b 124 mode_ = Running;
2aa77fd8 125#ifdef CY_EXECUTE
89d16b11 126 json = CYExecute(CYGetJSContext(), pool, code);
2aa77fd8
JF
127#else
128 json = NULL;
129#endif
4e39dc0b 130 mode_ = Working;
dd221c6b
JF
131 if (json == NULL)
132 size = 0;
133 else
6ec85c5b
JF
134 size = strlen(json);
135 } else {
4e39dc0b 136 mode_ = Sending;
0ced2e47 137 size = code.size;
a1f3555e
JF
138 _assert(CYSendAll(client, &size, sizeof(size)));
139 _assert(CYSendAll(client, code.data, code.size));
4e39dc0b 140 mode_ = Waiting;
a1f3555e 141 _assert(CYRecvAll(client, &size, sizeof(size)));
9d79cefc 142 if (size == _not(uint32_t))
967067aa
JF
143 json = NULL;
144 else {
145 char *temp(new(pool) char[size + 1]);
a1f3555e 146 _assert(CYRecvAll(client, temp, size));
967067aa
JF
147 temp[size] = '\0';
148 json = temp;
149 }
4e39dc0b 150 mode_ = Working;
4cf49641 151 }
b09da87b 152
7e5391fd
JF
153 return CYUTF8String(json, size);
154}
155
156static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
157 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
158}
159
2e2ed904 160static std::ostream *out_;
a3f4a8e1 161
82a02ede
JF
162static void Write(bool syntax, const char *data, size_t size, std::ostream &out) {
163 if (syntax)
164 CYLexerHighlight(data, size, out);
165 else
166 out.write(data, size);
167}
168
169static void Output(bool syntax, CYUTF8String json, std::ostream *out, bool expand = false) {
a3f4a8e1
JF
170 const char *data(json.data);
171 size_t size(json.size);
172
2e2ed904 173 if (data == NULL || out == NULL)
a3f4a8e1
JF
174 return;
175
0881deb5
JF
176 if (!expand ||
177 data[0] != '@' && data[0] != '"' && data[0] != '\'' ||
178 data[0] == '@' && data[1] != '"' && data[1] != '\''
179 )
82a02ede 180 Write(syntax, data, size, *out);
a3f4a8e1
JF
181 else for (size_t i(0); i != size; ++i)
182 if (data[i] != '\\')
2e2ed904 183 *out << data[i];
a3f4a8e1
JF
184 else switch(data[++i]) {
185 case '\0': goto done;
2e2ed904
JF
186 case '\\': *out << '\\'; break;
187 case '\'': *out << '\''; break;
188 case '"': *out << '"'; break;
189 case 'b': *out << '\b'; break;
190 case 'f': *out << '\f'; break;
191 case 'n': *out << '\n'; break;
192 case 'r': *out << '\r'; break;
193 case 't': *out << '\t'; break;
194 case 'v': *out << '\v'; break;
195 default: *out << '\\'; --i; break;
a3f4a8e1 196 }
6ec85c5b 197
a3f4a8e1 198 done:
2e2ed904 199 *out << std::endl;
a3f4a8e1
JF
200}
201
82a02ede 202static void Run(int client, bool syntax, const char *data, size_t size, std::ostream *out = NULL, bool expand = false) {
a3f4a8e1 203 CYPool pool;
82a02ede 204 Output(syntax, Run(pool, client, CYUTF8String(data, size)), out, expand);
b09da87b
JF
205}
206
82a02ede
JF
207static void Run(int client, bool syntax, std::string &code, std::ostream *out = NULL, bool expand = false) {
208 Run(client, syntax, code.c_str(), code.size(), out, expand);
fcc64bb5
JF
209}
210
da858962
JF
211int (*append_history$)(int, const char *);
212
7e5391fd
JF
213static std::string command_;
214
2eb8215d 215static CYExpression *ParseExpression(CYUTF8String code) {
d3b63265
JF
216 std::stringstream stream;
217 stream << '(' << code << ')';
218 CYDriver driver(stream);
7e5391fd
JF
219
220 cy::parser parser(driver);
221 Setup(driver, parser);
222
223 if (parser.parse() != 0 || !driver.errors_.empty())
df24434f 224 return NULL;
7e5391fd 225
e06e5ee1
JF
226 CYOptions options;
227 CYContext context(options);
228
b0385401 229 CYStatement *statement(driver.program_->code_);
fd5cdf97
JF
230 _assert(statement != NULL);
231 _assert(statement->next_ == NULL);
e06e5ee1 232
b0385401 233 CYExpress *express(dynamic_cast<CYExpress *>(driver.program_->code_));
fd5cdf97
JF
234 _assert(express != NULL);
235
b0385401
JF
236 CYParenthetical *parenthetical(dynamic_cast<CYParenthetical *>(express->expression_));
237 _assert(parenthetical != NULL);
238
239 return parenthetical->expression_;
7e5391fd
JF
240}
241
242static int client_;
243
244static char **Complete(const char *word, int start, int end) {
10d0e915 245 rl_attempted_completion_over = ~0;
7e5391fd 246
2eb8215d 247 CYLocalPool pool;
7e5391fd
JF
248
249 std::string line(rl_line_buffer, start);
d3b63265
JF
250 std::istringstream stream(command_ + line);
251 CYDriver driver(stream);
7e5391fd
JF
252
253 driver.auto_ = true;
254
d3b63265
JF
255 cy::parser parser(driver);
256 Setup(driver, parser);
257
7e5391fd
JF
258 if (parser.parse() != 0 || !driver.errors_.empty())
259 return NULL;
260
261 if (driver.mode_ == CYDriver::AutoNone)
262 return NULL;
263
264 CYExpression *expression;
265
266 CYOptions options;
2eb8215d 267 CYContext context(options);
7e5391fd
JF
268
269 std::ostringstream prefix;
270
271 switch (driver.mode_) {
272 case CYDriver::AutoPrimary:
273 expression = $ CYThis();
274 break;
275
276 case CYDriver::AutoDirect:
277 expression = driver.context_;
278 break;
279
280 case CYDriver::AutoIndirect:
281 expression = $ CYIndirect(driver.context_);
282 break;
283
284 case CYDriver::AutoMessage: {
285 CYDriver::Context &thing(driver.contexts_.back());
aa926c8b 286 expression = $M($C1($V("object_getClass"), thing.context_), $S("messages"));
7e5391fd
JF
287 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
288 prefix << (*part)->word_ << ':';
289 } break;
290
291 default:
292 _assert(false);
293 }
294
2a18313c 295 std::string begin(prefix.str());
7e5391fd 296
2eb8215d 297 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
2a18313c 298 " function(object, prefix, word) {\n"
7e5391fd 299 " var names = [];\n"
5a3f7a01
JF
300 " var before = prefix.length;\n"
301 " prefix += word;\n"
302 " var entire = prefix.length;\n"
3e6377db 303 " for (var name in object)\n"
5a3f7a01
JF
304 " if (name.substring(0, entire) == prefix)\n"
305 " names.push(name.substr(before));\n"
7e5391fd
JF
306 " return names;\n"
307 " }\n"
2a18313c 308 ), expression, $S(begin.c_str()), $S(word))));
7e5391fd
JF
309
310 driver.program_->Replace(context);
311
efd689d8 312 std::stringbuf str;
7e5391fd
JF
313 CYOutput out(str, options);
314 out << *driver.program_;
315
316 std::string code(str.str());
317 CYUTF8String json(Run(pool, client_, code));
1b2613d3 318 // XXX: if this fails we should not try to parse it
7e5391fd 319
2eb8215d 320 CYExpression *result(ParseExpression(json));
df24434f
JF
321 if (result == NULL)
322 return NULL;
323
fd5cdf97 324 CYArray *array(dynamic_cast<CYArray *>(result->Primitive(context)));
a3f4a8e1 325 if (array == NULL) {
2e2ed904 326 *out_ << '\n';
82a02ede 327 Output(false, json, out_);
a3f4a8e1
JF
328 rl_forced_update_display();
329 return NULL;
330 }
7e5391fd
JF
331
332 // XXX: use an std::set?
333 typedef std::vector<std::string> Completions;
334 Completions completions;
335
336 std::string common;
337 bool rest(false);
338
c2c9f509 339 CYForEach (element, array->elements_) {
7e5391fd
JF
340 CYString *string(dynamic_cast<CYString *>(element->value_));
341 _assert(string != NULL);
342
763aa499
JF
343 std::string completion;
344 if (string->size_ != 0)
345 completion.assign(string->value_, string->size_);
346 else if (driver.mode_ == CYDriver::AutoMessage)
347 completion = "]";
348 else
349 continue;
350
7e5391fd
JF
351 completions.push_back(completion);
352
353 if (!rest) {
354 common = completion;
355 rest = true;
356 } else {
357 size_t limit(completion.size()), size(common.size());
358 if (size > limit)
359 common = common.substr(0, limit);
360 else
361 limit = size;
362 for (limit = 0; limit != size; ++limit)
363 if (common[limit] != completion[limit])
364 break;
365 if (limit != size)
366 common = common.substr(0, limit);
367 }
368 }
369
370 size_t count(completions.size());
371 if (count == 0)
372 return NULL;
373
c41590b2
JF
374 size_t colon(common.find(':'));
375 if (colon != std::string::npos)
376 common = common.substr(0, colon + 1);
6dccefa9
JF
377 if (completions.size() == 1)
378 common += ' ';
c41590b2 379
7e5391fd
JF
380 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
381
382 results[0] = strdup(common.c_str());
383 size_t index(0);
384 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
385 results[++index] = strdup(i->c_str());
386 results[count + 1] = NULL;
387
388 return results;
389}
390
391// need char *, not const char *
392static char name_[] = "cycript";
87450281 393static char break_[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]";
7e5391fd 394
da136f88
JF
395class History {
396 private:
397 std::string histfile_;
398 size_t histlines_;
399
400 public:
401 History(std::string histfile) :
402 histfile_(histfile),
403 histlines_(0)
404 {
405 read_history(histfile_.c_str());
406 }
407
408 ~History() {
409 if (append_history$ != NULL) {
f61fec22
JF
410 int fd(_syscall(open(histfile_.c_str(), O_CREAT | O_WRONLY, 0600)));
411 _syscall(close(fd));
da136f88
JF
412 _assert((*append_history$)(histlines_, histfile_.c_str()) == 0);
413 } else {
414 _assert(write_history(histfile_.c_str()) == 0);
415 }
416 }
417
418 void operator +=(const std::string &command) {
6265f0de 419 add_history(command.c_str());
da136f88
JF
420 ++histlines_;
421 }
422};
423
2eb8215d 424static void Console(CYOptions &options) {
1210260f
JF
425 std::string basedir;
426 if (const char *home = getenv("HOME"))
427 basedir = home;
428 else {
429 passwd *passwd;
430 if (const char *username = getenv("LOGNAME"))
431 passwd = getpwnam(username);
432 else
433 passwd = getpwuid(getuid());
434 basedir = passwd->pw_dir;
435 }
b1589845 436
da136f88
JF
437 basedir += "/.cycript";
438 mkdir(basedir.c_str(), 0700);
b1589845 439
7e5391fd
JF
440 rl_initialize();
441 rl_readline_name = name_;
442
da136f88 443 History history(basedir + "/history");
b1589845 444
1f8eae40
JF
445 bool bypass(false);
446 bool debug(false);
6ec85c5b 447 bool expand(false);
36bf49c4 448 bool lower(true);
cd98d280 449 bool syntax(true);
1f8eae40 450
2e2ed904 451 out_ = &std::cout;
057f943f 452
7e5391fd
JF
453 // rl_completer_word_break_characters is broken in libedit
454 rl_basic_word_break_characters = break_;
bc1e87aa
JF
455
456 rl_completer_word_break_characters = break_;
7e5391fd
JF
457 rl_attempted_completion_function = &Complete;
458 rl_bind_key('\t', rl_complete);
057f943f
JF
459
460 struct sigaction action;
461 sigemptyset(&action.sa_mask);
462 action.sa_handler = &sigint;
463 action.sa_flags = 0;
464 sigaction(SIGINT, &action, NULL);
465
466 restart: for (;;) {
7e5391fd 467 command_.clear();
057f943f
JF
468 std::vector<std::string> lines;
469
931b816a
JF
470 bool extra(false);
471 const char *prompt("cy# ");
472
057f943f 473 if (setjmp(ctrlc_) != 0) {
4e39dc0b 474 mode_ = Working;
2e2ed904 475 *out_ << std::endl;
057f943f
JF
476 goto restart;
477 }
478
057f943f 479 read:
cd98d280
JF
480
481#if RL_READLINE_VERSION >= 0x0600
8a81192b 482 if (syntax)
cd98d280 483 rl_redisplay_function = CYDisplayUpdate;
8a81192b 484 else
cd98d280 485 rl_redisplay_function = rl_redisplay;
cd98d280
JF
486#endif
487
4e39dc0b 488 mode_ = Parsing;
057f943f 489 char *line(readline(prompt));
4e39dc0b 490 mode_ = Working;
cd98d280 491
79357996
JF
492 if (line == NULL) {
493 *out_ << std::endl;
057f943f 494 break;
79357996 495 } else if (line[0] == '\0')
67f1fc6b 496 goto read;
931b816a
JF
497
498 if (!extra) {
499 extra = true;
6ec85c5b 500 if (line[0] == '?') {
1f8eae40
JF
501 std::string data(line + 1);
502 if (data == "bypass") {
503 bypass = !bypass;
2e2ed904 504 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
1f8eae40
JF
505 } else if (data == "debug") {
506 debug = !debug;
2e2ed904 507 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
8fab8594
JF
508 } else if (data == "destroy") {
509 CYDestroyContext();
51b6165e 510 } else if (data == "gc") {
e7ff0158 511 *out_ << "collecting... " << std::flush;
51b6165e 512 CYGarbageCollect(CYGetJSContext());
e7ff0158 513 *out_ << "done." << std::endl;
6a5fd0d9
JF
514 } else if (data == "exit") {
515 return;
6ec85c5b
JF
516 } else if (data == "expand") {
517 expand = !expand;
2e2ed904 518 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
36bf49c4
JF
519 } else if (data == "lower") {
520 lower = !lower;
521 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
82a02ede
JF
522 } else if (data == "syntax") {
523 syntax = !syntax;
524 *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl;
1f8eae40 525 }
be8c2078
JF
526 command_ = line;
527 history += command_;
931b816a
JF
528 goto restart;
529 }
530 }
531
7e5391fd 532 command_ += line;
6265f0de 533 command_ += "\n";
e818f0e0
JF
534
535 char *begin(line), *end(line + strlen(line));
536 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
537 *nl = '\0';
538 lines.push_back(begin);
539 begin = nl + 1;
540 }
541
542 lines.push_back(begin);
543
057f943f
JF
544 free(line);
545
1f8eae40
JF
546 std::string code;
547
548 if (bypass)
7e5391fd 549 code = command_;
1f8eae40 550 else {
2eb8215d 551 CYLocalPool pool;
d3b63265
JF
552
553 std::istringstream stream(command_);
554 CYDriver driver(stream);
555
1f8eae40 556 cy::parser parser(driver);
b10bd496 557 Setup(driver, parser);
1f8eae40 558
1f8eae40 559 if (parser.parse() != 0 || !driver.errors_.empty()) {
f0360d51 560 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
58afc6aa 561 CYPosition begin(error->location_.begin);
6265f0de 562 if (begin.line != lines.size() + 1 || error->warning_) {
58afc6aa 563 CYPosition end(error->location_.end);
48e3be8a 564
f0360d51
JF
565 if (begin.line != lines.size()) {
566 std::cerr << " | ";
567 std::cerr << lines[begin.line - 1] << std::endl;
568 }
48e3be8a 569
c52a09b8 570 std::cerr << "....";
97c8a8fc 571 for (size_t i(0); i != begin.column; ++i)
f0360d51 572 std::cerr << '.';
48e3be8a 573 if (begin.line != end.line || begin.column == end.column)
f0360d51
JF
574 std::cerr << '^';
575 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
576 std::cerr << '^';
577 std::cerr << std::endl;
48e3be8a 578
f0360d51
JF
579 std::cerr << " | ";
580 std::cerr << error->message_ << std::endl;
48e3be8a 581
6265f0de 582 history += command_.substr(0, command_.size() - 1);
1f8eae40
JF
583 goto restart;
584 }
585 }
057f943f 586
1f8eae40 587 driver.errors_.clear();
057f943f 588
1f8eae40
JF
589 prompt = "cy> ";
590 goto read;
057f943f
JF
591 }
592
b10bd496 593 if (driver.program_ == NULL)
1f8eae40 594 goto restart;
057f943f 595
efd689d8 596 std::stringbuf str;
0df6a201 597 CYOutput out(str, options);
36bf49c4 598 Setup(out, driver, options, lower);
0df6a201
JF
599 out << *driver.program_;
600 code = str.str();
057f943f
JF
601 }
602
6265f0de 603 history += command_.substr(0, command_.size() - 1);
057f943f 604
82a02ede 605 if (debug) {
f43fcb85 606 std::cout << "cy= ";
82a02ede
JF
607 Write(syntax, code.c_str(), code.size(), std::cout);
608 std::cout << std::endl;
609 }
057f943f 610
82a02ede 611 Run(client_, syntax, code, out_, expand);
b09da87b 612 }
b09da87b 613}
057f943f 614
f8d45a20 615void InjectLibrary(pid_t, int, const char *[]);
06edab7d 616
10d0e915 617int Main(int argc, char * const argv[], char const * const envp[]) {
48e3be8a 618 bool tty(isatty(STDIN_FILENO));
75b0a457 619 bool compile(false);
96746747 620 bool target(false);
de9fc71b 621 CYOptions options;
967067aa 622
e4676127 623 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
da858962 624
2aa77fd8
JF
625#ifdef CY_ATTACH
626 pid_t pid(_not(pid_t));
627#endif
628
666eedb9
JF
629 const char *host(NULL);
630 const char *port(NULL);
631
10d0e915 632 optind = 1;
06edab7d
JF
633
634 for (;;) {
10d0e915
JF
635 int option(getopt_long(argc, argv,
636 "c"
637 "g:"
638 "n:"
2aa77fd8 639#ifdef CY_ATTACH
10d0e915 640 "p:"
2aa77fd8 641#endif
10d0e915
JF
642 "r:"
643 "s"
f61fec22 644 , (const struct option[]) {
10d0e915
JF
645 {NULL, no_argument, NULL, 'c'},
646 {NULL, required_argument, NULL, 'g'},
647 {NULL, required_argument, NULL, 'n'},
648#ifdef CY_ATTACH
649 {NULL, required_argument, NULL, 'p'},
650#endif
651 {NULL, required_argument, NULL, 'r'},
652 {NULL, no_argument, NULL, 's'},
653 {0, 0, 0, 0}}, NULL));
06edab7d 654
10d0e915
JF
655 switch (option) {
656 case -1:
06edab7d 657 goto getopt;
10d0e915
JF
658
659 case ':':
660 case '?':
06edab7d
JF
661 fprintf(stderr,
662 "usage: cycript [-c]"
2aa77fd8 663#ifdef CY_ATTACH
69caa5be 664 " [-p <pid|name>]"
2aa77fd8 665#endif
666eedb9 666 " [-r <host:port>]"
06edab7d
JF
667 " [<script> [<arg>...]]\n"
668 );
669 return 1;
967067aa 670
96746747
JF
671 target:
672 if (!target)
673 target = true;
674 else {
675 fprintf(stderr, "only one of -[c"
676#ifdef CY_ATTACH
677 "p"
678#endif
679 "r] may be used at a time\n");
680 return 1;
681 }
682 break;
683
06edab7d
JF
684 case 'c':
685 compile = true;
96746747 686 goto target;
75b0a457 687
06edab7d
JF
688 case 'g':
689 if (false);
10d0e915 690 else if (strcmp(optarg, "rename") == 0)
de9fc71b 691 options.verbose_ = true;
cac61857 692#if YYDEBUG
10d0e915 693 else if (strcmp(optarg, "bison") == 0)
06edab7d 694 bison_ = true;
cac61857 695#endif
06edab7d
JF
696 else {
697 fprintf(stderr, "invalid name for -g\n");
698 return 1;
699 }
700 break;
cac61857 701
06edab7d
JF
702 case 'n':
703 if (false);
10d0e915 704 else if (strcmp(optarg, "minify") == 0)
06edab7d
JF
705 pretty_ = true;
706 else {
707 fprintf(stderr, "invalid name for -n\n");
708 return 1;
709 }
710 break;
11c1cc16 711
2aa77fd8 712#ifdef CY_ATTACH
06edab7d 713 case 'p': {
10d0e915 714 size_t size(strlen(optarg));
06edab7d 715 char *end;
69caa5be 716
10d0e915
JF
717 pid = strtoul(optarg, &end, 0);
718 if (optarg + size != end) {
69caa5be 719 // XXX: arg needs to be escaped in some horrendous way of doom
10d0e915
JF
720 // XXX: this is a memory leak now because I just don't care enough
721 char *command;
722 asprintf(&command, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg);
69caa5be
JF
723
724 if (FILE *pids = popen(command, "r")) {
725 char value[32];
726 size = 0;
727
728 for (;;) {
729 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
730 if (read == 0)
731 break;
732 else {
733 size += read;
04aa6240 734 if (size == sizeof(value))
b166b11b 735 goto fail;
69caa5be
JF
736 }
737 }
738
739 size:
740 if (size == 0)
b166b11b 741 goto fail;
69caa5be
JF
742 if (value[size - 1] == '\n') {
743 --size;
744 goto size;
745 }
746
747 value[size] = '\0';
748 size = strlen(value);
749 pid = strtoul(value, &end, 0);
b166b11b 750 if (value + size != end) fail:
69caa5be 751 pid = _not(pid_t);
69caa5be
JF
752 _syscall(pclose(pids));
753 }
754
755 if (pid == _not(pid_t)) {
10d0e915 756 fprintf(stderr, "unable to find process `%s' using ps\n", optarg);
69caa5be
JF
757 return 1;
758 }
06edab7d 759 }
96746747 760 } goto target;
2aa77fd8 761#endif
b10bd496 762
666eedb9 763 case 'r': {
10d0e915 764 //size_t size(strlen(optarg));
666eedb9 765
10d0e915 766 char *colon(strrchr(optarg, ':'));
666eedb9
JF
767 if (colon == NULL) {
768 fprintf(stderr, "missing colon in hostspec\n");
769 return 1;
770 }
771
772 /*char *end;
773 port = strtoul(colon + 1, &end, 10);
10d0e915 774 if (end != optarg + size) {
666eedb9
JF
775 fprintf(stderr, "invalid port in hostspec\n");
776 return 1;
777 }*/
778
10d0e915 779 host = optarg;
666eedb9
JF
780 *colon = '\0';
781 port = colon + 1;
96746747 782 } goto target;
666eedb9 783
06edab7d
JF
784 case 's':
785 strict_ = true;
786 break;
10d0e915
JF
787
788 default:
789 _assert(false);
06edab7d 790 }
10d0e915
JF
791 }
792
793 getopt:
794 argc -= optind;
795 argv += optind;
967067aa 796
b09da87b
JF
797 const char *script;
798
2aa77fd8 799#ifdef CY_ATTACH
10d0e915 800 if (pid != _not(pid_t) && argc > 1) {
fcc64bb5
JF
801 fprintf(stderr, "-p cannot set argv\n");
802 return 1;
803 }
2aa77fd8 804#endif
75b0a457 805
10d0e915 806 if (argc == 0)
b09da87b
JF
807 script = NULL;
808 else {
9185d5ef 809#ifdef CY_EXECUTE
967067aa 810 // XXX: const_cast?! wtf gcc :(
10d0e915 811 CYSetArgs(argc - 1, const_cast<const char **>(argv + 1));
9185d5ef 812#endif
10d0e915 813 script = argv[0];
967067aa
JF
814 if (strcmp(script, "-") == 0)
815 script = NULL;
b09da87b
JF
816 }
817
2aa77fd8 818#ifdef CY_ATTACH
967067aa 819 if (pid == _not(pid_t))
7e5391fd 820 client_ = -1;
967067aa 821 else {
46d13f4c
JF
822 struct Socket {
823 int fd_;
b166b11b 824
46d13f4c
JF
825 Socket(int fd) :
826 fd_(fd)
827 {
828 }
96cc7967 829
46d13f4c
JF
830 ~Socket() {
831 close(fd_);
832 }
96cc7967 833
46d13f4c
JF
834 operator int() {
835 return fd_;
836 }
837 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
96cc7967 838
46d13f4c
JF
839 struct sockaddr_un address;
840 memset(&address, 0, sizeof(address));
841 address.sun_family = AF_UNIX;
b166b11b 842
f8d45a20
JF
843 const char *tmp;
844#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
845 tmp = "/Library/Caches";
846#else
847 tmp = "/tmp";
848#endif
849
850 sprintf(address.sun_path, "%s/.s.cy.%u", tmp, getpid());
46d13f4c 851 unlink(address.sun_path);
b166b11b 852
46d13f4c
JF
853 struct File {
854 const char *path_;
855
856 File(const char *path) :
857 path_(path)
858 {
859 }
860
861 ~File() {
862 unlink(path_);
863 }
864 } file(address.sun_path);
865
866 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
867 _syscall(chmod(address.sun_path, 0777));
868
869 _syscall(listen(server, 1));
f8d45a20 870 InjectLibrary(pid, 1, (const char *[]) {address.sun_path, NULL});
46d13f4c 871 client_ = _syscall(accept(server, NULL, NULL));
967067aa 872 }
2aa77fd8 873#else
7e5391fd 874 client_ = -1;
2aa77fd8 875#endif
579ed526 876
666eedb9
JF
877 if (client_ == -1 && host != NULL && port != NULL) {
878 struct addrinfo hints;
879 memset(&hints, 0, sizeof(hints));
880 hints.ai_family = AF_UNSPEC;
881 hints.ai_socktype = SOCK_STREAM;
882 hints.ai_protocol = 0;
883 hints.ai_flags = 0;
884
885 struct addrinfo *infos;
886 _syscall(getaddrinfo(host, port, &hints, &infos));
887
888 _assert(infos != NULL); try {
889 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
890 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
891 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
892 client_ = client;
893 break;
894 } catch (...) {
895 _syscall(close(client));
896 throw;
897 }
898 }
899 } catch (...) {
900 freeaddrinfo(infos);
901 throw;
902 }
903 }
904
48e3be8a 905 if (script == NULL && tty)
2eb8215d 906 Console(options);
b09da87b 907 else {
2eb8215d 908 CYLocalPool pool;
b09da87b 909
0df6a201 910 std::istream *stream;
48e3be8a 911 if (script == NULL) {
0df6a201
JF
912 stream = &std::cin;
913 script = "<stdin>";
48e3be8a 914 } else {
0df6a201
JF
915 stream = new std::fstream(script, std::ios::in | std::ios::binary);
916 _assert(!stream->fail());
48e3be8a 917 }
62ca2b82 918
0df6a201 919 CYDriver driver(*stream, script);
d3b63265
JF
920 cy::parser parser(driver);
921 Setup(driver, parser);
922
b09da87b
JF
923 if (parser.parse() != 0 || !driver.errors_.empty()) {
924 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
925 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
0df6a201 926 } else if (driver.program_ != NULL) {
efd689d8 927 std::stringbuf str;
0df6a201 928 CYOutput out(str, options);
36bf49c4 929 Setup(out, driver, options, true);
0df6a201
JF
930 out << *driver.program_;
931 std::string code(str.str());
932 if (compile)
933 std::cout << code;
934 else
82a02ede 935 Run(client_, false, code, &std::cout);
0df6a201 936 }
057f943f 937 }
62ca2b82 938
057f943f 939 return 0;
62ca2b82 940}
b6961e53 941
10d0e915
JF
942int main(int argc, char * const argv[], char const * const envp[]) {
943 try {
b6961e53
JF
944 return Main(argc, argv, envp);
945 } catch (const CYException &error) {
946 CYPool pool;
947 fprintf(stderr, "%s\n", error.PoolCString(pool));
948 return 1;
949 }
950}