]> git.saurik.com Git - cycript.git/blame - Console.cpp
Reorganize grammar to match the ECMAScript 6 spec.
[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
341d1456
JF
65#ifdef __APPLE__
66#include <mach/mach_time.h>
67#endif
68
74296173 69#include "Display.hpp"
b12a9965 70#include "Driver.hpp"
d9c91152
JF
71#include "Highlight.hpp"
72#include "Replace.hpp"
7e5391fd 73
4e39dc0b
JF
74static volatile enum {
75 Working,
76 Parsing,
77 Running,
78 Sending,
79 Waiting,
80} mode_;
81
057f943f
JF
82static jmp_buf ctrlc_;
83
579ed526 84static void sigint(int) {
4e39dc0b
JF
85 switch (mode_) {
86 case Working:
87 return;
88 case Parsing:
89 longjmp(ctrlc_, 1);
90 case Running:
b0ba908c
JF
91 CYCancel();
92 return;
4e39dc0b
JF
93 case Sending:
94 return;
95 case Waiting:
96 return;
97 }
057f943f
JF
98}
99
cac61857 100static bool bison_;
341d1456 101static bool timing_;
b10bd496 102static bool strict_;
11c1cc16 103static bool pretty_;
cac61857 104
d9c91152 105void Setup(CYDriver &driver) {
cac61857 106 if (bison_)
d9c91152 107 driver.debug_ = 1;
b10bd496
JF
108 if (strict_)
109 driver.strict_ = true;
cac61857
JF
110}
111
2c1d569a 112void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) {
11c1cc16 113 out.pretty_ = pretty_;
36bf49c4 114 if (lower)
2c1d569a 115 driver.Replace(options);
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
d9c91152 214static int client_;
b0385401 215
d9c91152
JF
216static CYUTF8String Run(CYPool &pool, const std::string &code) {
217 return Run(pool, client_, code);
7e5391fd
JF
218}
219
7e5391fd 220static char **Complete(const char *word, int start, int end) {
10d0e915 221 rl_attempted_completion_over = ~0;
7e5391fd 222 std::string line(rl_line_buffer, start);
d9c91152 223 return CYComplete(word, command_ + line, &Run);
7e5391fd
JF
224}
225
226// need char *, not const char *
227static char name_[] = "cycript";
87450281 228static char break_[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]";
7e5391fd 229
da136f88
JF
230class History {
231 private:
232 std::string histfile_;
233 size_t histlines_;
234
235 public:
236 History(std::string histfile) :
237 histfile_(histfile),
238 histlines_(0)
239 {
240 read_history(histfile_.c_str());
241 }
242
243 ~History() {
244 if (append_history$ != NULL) {
f61fec22
JF
245 int fd(_syscall(open(histfile_.c_str(), O_CREAT | O_WRONLY, 0600)));
246 _syscall(close(fd));
da136f88
JF
247 _assert((*append_history$)(histlines_, histfile_.c_str()) == 0);
248 } else {
249 _assert(write_history(histfile_.c_str()) == 0);
250 }
251 }
252
253 void operator +=(const std::string &command) {
6265f0de 254 add_history(command.c_str());
da136f88
JF
255 ++histlines_;
256 }
257};
258
2eb8215d 259static void Console(CYOptions &options) {
1210260f
JF
260 std::string basedir;
261 if (const char *home = getenv("HOME"))
262 basedir = home;
263 else {
264 passwd *passwd;
265 if (const char *username = getenv("LOGNAME"))
266 passwd = getpwnam(username);
267 else
268 passwd = getpwuid(getuid());
269 basedir = passwd->pw_dir;
270 }
b1589845 271
da136f88
JF
272 basedir += "/.cycript";
273 mkdir(basedir.c_str(), 0700);
b1589845 274
7e5391fd
JF
275 rl_initialize();
276 rl_readline_name = name_;
277
da136f88 278 History history(basedir + "/history");
b1589845 279
1f8eae40
JF
280 bool bypass(false);
281 bool debug(false);
6ec85c5b 282 bool expand(false);
36bf49c4 283 bool lower(true);
cd98d280 284 bool syntax(true);
1f8eae40 285
2e2ed904 286 out_ = &std::cout;
057f943f 287
7e5391fd
JF
288 // rl_completer_word_break_characters is broken in libedit
289 rl_basic_word_break_characters = break_;
bc1e87aa
JF
290
291 rl_completer_word_break_characters = break_;
7e5391fd
JF
292 rl_attempted_completion_function = &Complete;
293 rl_bind_key('\t', rl_complete);
057f943f
JF
294
295 struct sigaction action;
296 sigemptyset(&action.sa_mask);
297 action.sa_handler = &sigint;
298 action.sa_flags = 0;
299 sigaction(SIGINT, &action, NULL);
300
301 restart: for (;;) {
7e5391fd 302 command_.clear();
057f943f
JF
303 std::vector<std::string> lines;
304
931b816a
JF
305 bool extra(false);
306 const char *prompt("cy# ");
307
057f943f 308 if (setjmp(ctrlc_) != 0) {
4e39dc0b 309 mode_ = Working;
2e2ed904 310 *out_ << std::endl;
057f943f
JF
311 goto restart;
312 }
313
057f943f 314 read:
cd98d280
JF
315
316#if RL_READLINE_VERSION >= 0x0600
8a81192b 317 if (syntax)
cd98d280 318 rl_redisplay_function = CYDisplayUpdate;
8a81192b 319 else
cd98d280 320 rl_redisplay_function = rl_redisplay;
cd98d280
JF
321#endif
322
4e39dc0b 323 mode_ = Parsing;
057f943f 324 char *line(readline(prompt));
4e39dc0b 325 mode_ = Working;
cd98d280 326
79357996
JF
327 if (line == NULL) {
328 *out_ << std::endl;
057f943f 329 break;
79357996 330 } else if (line[0] == '\0')
67f1fc6b 331 goto read;
931b816a
JF
332
333 if (!extra) {
334 extra = true;
6ec85c5b 335 if (line[0] == '?') {
1f8eae40
JF
336 std::string data(line + 1);
337 if (data == "bypass") {
338 bypass = !bypass;
2e2ed904 339 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
1f8eae40
JF
340 } else if (data == "debug") {
341 debug = !debug;
2e2ed904 342 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
8fab8594
JF
343 } else if (data == "destroy") {
344 CYDestroyContext();
51b6165e 345 } else if (data == "gc") {
e7ff0158 346 *out_ << "collecting... " << std::flush;
51b6165e 347 CYGarbageCollect(CYGetJSContext());
e7ff0158 348 *out_ << "done." << std::endl;
6a5fd0d9
JF
349 } else if (data == "exit") {
350 return;
6ec85c5b
JF
351 } else if (data == "expand") {
352 expand = !expand;
2e2ed904 353 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
36bf49c4
JF
354 } else if (data == "lower") {
355 lower = !lower;
356 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
82a02ede
JF
357 } else if (data == "syntax") {
358 syntax = !syntax;
359 *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl;
1f8eae40 360 }
be8c2078
JF
361 command_ = line;
362 history += command_;
931b816a
JF
363 goto restart;
364 }
365 }
366
7e5391fd 367 command_ += line;
6265f0de 368 command_ += "\n";
e818f0e0
JF
369
370 char *begin(line), *end(line + strlen(line));
371 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
372 *nl = '\0';
373 lines.push_back(begin);
374 begin = nl + 1;
375 }
376
377 lines.push_back(begin);
378
057f943f
JF
379 free(line);
380
1f8eae40
JF
381 std::string code;
382
383 if (bypass)
7e5391fd 384 code = command_;
1f8eae40 385 else {
d3b63265 386 std::istringstream stream(command_);
d3b63265 387
d9c91152 388 CYPool pool;
2c1d569a
JF
389 CYDriver driver(pool, stream);
390 Setup(driver);
391
392 bool failed(driver.Parse());
1f8eae40 393
d9c91152 394 if (failed || !driver.errors_.empty()) {
f0360d51 395 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
58afc6aa 396 CYPosition begin(error->location_.begin);
6265f0de 397 if (begin.line != lines.size() + 1 || error->warning_) {
58afc6aa 398 CYPosition end(error->location_.end);
48e3be8a 399
f0360d51
JF
400 if (begin.line != lines.size()) {
401 std::cerr << " | ";
402 std::cerr << lines[begin.line - 1] << std::endl;
403 }
48e3be8a 404
c52a09b8 405 std::cerr << "....";
97c8a8fc 406 for (size_t i(0); i != begin.column; ++i)
f0360d51 407 std::cerr << '.';
48e3be8a 408 if (begin.line != end.line || begin.column == end.column)
f0360d51
JF
409 std::cerr << '^';
410 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
411 std::cerr << '^';
412 std::cerr << std::endl;
48e3be8a 413
f0360d51
JF
414 std::cerr << " | ";
415 std::cerr << error->message_ << std::endl;
48e3be8a 416
6265f0de 417 history += command_.substr(0, command_.size() - 1);
1f8eae40
JF
418 goto restart;
419 }
420 }
057f943f 421
1f8eae40 422 driver.errors_.clear();
057f943f 423
1f8eae40
JF
424 prompt = "cy> ";
425 goto read;
057f943f
JF
426 }
427
a7d8b413 428 if (driver.script_ == NULL)
1f8eae40 429 goto restart;
057f943f 430
efd689d8 431 std::stringbuf str;
0df6a201 432 CYOutput out(str, options);
2c1d569a 433 Setup(out, driver, options, lower);
a7d8b413 434 out << *driver.script_;
0df6a201 435 code = str.str();
057f943f
JF
436 }
437
6265f0de 438 history += command_.substr(0, command_.size() - 1);
057f943f 439
82a02ede 440 if (debug) {
f43fcb85 441 std::cout << "cy= ";
82a02ede
JF
442 Write(syntax, code.c_str(), code.size(), std::cout);
443 std::cout << std::endl;
444 }
057f943f 445
82a02ede 446 Run(client_, syntax, code, out_, expand);
b09da87b 447 }
b09da87b 448}
057f943f 449
ccb4e34c 450void InjectLibrary(pid_t, int, const char *const []);
06edab7d 451
341d1456
JF
452static uint64_t CYGetTime() {
453#ifdef __APPLE__
454 return mach_absolute_time();
455#else
456 struct timespec spec;
457 clock_gettime(CLOCK_MONOTONIC, &spec);
458 return spec.tv_sec * UINT64_C(1000000000) + spec.tv_nsec;
459#endif
460}
461
10d0e915 462int Main(int argc, char * const argv[], char const * const envp[]) {
48e3be8a 463 bool tty(isatty(STDIN_FILENO));
75b0a457 464 bool compile(false);
96746747 465 bool target(false);
de9fc71b 466 CYOptions options;
967067aa 467
e4676127 468 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
da858962 469
2aa77fd8
JF
470#ifdef CY_ATTACH
471 pid_t pid(_not(pid_t));
472#endif
473
666eedb9
JF
474 const char *host(NULL);
475 const char *port(NULL);
476
10d0e915 477 optind = 1;
06edab7d
JF
478
479 for (;;) {
10d0e915
JF
480 int option(getopt_long(argc, argv,
481 "c"
482 "g:"
483 "n:"
2aa77fd8 484#ifdef CY_ATTACH
10d0e915 485 "p:"
2aa77fd8 486#endif
10d0e915
JF
487 "r:"
488 "s"
f61fec22 489 , (const struct option[]) {
10d0e915
JF
490 {NULL, no_argument, NULL, 'c'},
491 {NULL, required_argument, NULL, 'g'},
492 {NULL, required_argument, NULL, 'n'},
493#ifdef CY_ATTACH
494 {NULL, required_argument, NULL, 'p'},
495#endif
496 {NULL, required_argument, NULL, 'r'},
497 {NULL, no_argument, NULL, 's'},
498 {0, 0, 0, 0}}, NULL));
06edab7d 499
10d0e915
JF
500 switch (option) {
501 case -1:
06edab7d 502 goto getopt;
10d0e915
JF
503
504 case ':':
505 case '?':
06edab7d
JF
506 fprintf(stderr,
507 "usage: cycript [-c]"
2aa77fd8 508#ifdef CY_ATTACH
69caa5be 509 " [-p <pid|name>]"
2aa77fd8 510#endif
666eedb9 511 " [-r <host:port>]"
06edab7d
JF
512 " [<script> [<arg>...]]\n"
513 );
514 return 1;
967067aa 515
96746747
JF
516 target:
517 if (!target)
518 target = true;
519 else {
520 fprintf(stderr, "only one of -[c"
521#ifdef CY_ATTACH
522 "p"
523#endif
524 "r] may be used at a time\n");
525 return 1;
526 }
527 break;
528
06edab7d
JF
529 case 'c':
530 compile = true;
96746747 531 goto target;
75b0a457 532
06edab7d
JF
533 case 'g':
534 if (false);
10d0e915 535 else if (strcmp(optarg, "rename") == 0)
de9fc71b 536 options.verbose_ = true;
10d0e915 537 else if (strcmp(optarg, "bison") == 0)
06edab7d 538 bison_ = true;
341d1456
JF
539 else if (strcmp(optarg, "timing") == 0)
540 timing_ = true;
06edab7d
JF
541 else {
542 fprintf(stderr, "invalid name for -g\n");
543 return 1;
544 }
545 break;
cac61857 546
06edab7d
JF
547 case 'n':
548 if (false);
10d0e915 549 else if (strcmp(optarg, "minify") == 0)
06edab7d
JF
550 pretty_ = true;
551 else {
552 fprintf(stderr, "invalid name for -n\n");
553 return 1;
554 }
555 break;
11c1cc16 556
2aa77fd8 557#ifdef CY_ATTACH
06edab7d 558 case 'p': {
10d0e915 559 size_t size(strlen(optarg));
06edab7d 560 char *end;
69caa5be 561
10d0e915
JF
562 pid = strtoul(optarg, &end, 0);
563 if (optarg + size != end) {
69caa5be 564 // XXX: arg needs to be escaped in some horrendous way of doom
10d0e915
JF
565 // XXX: this is a memory leak now because I just don't care enough
566 char *command;
ccb4e34c
JF
567 int writ(asprintf(&command, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg));
568 _assert(writ != -1);
69caa5be
JF
569
570 if (FILE *pids = popen(command, "r")) {
571 char value[32];
572 size = 0;
573
574 for (;;) {
575 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
576 if (read == 0)
577 break;
578 else {
579 size += read;
04aa6240 580 if (size == sizeof(value))
b166b11b 581 goto fail;
69caa5be
JF
582 }
583 }
584
585 size:
586 if (size == 0)
b166b11b 587 goto fail;
69caa5be
JF
588 if (value[size - 1] == '\n') {
589 --size;
590 goto size;
591 }
592
593 value[size] = '\0';
594 size = strlen(value);
595 pid = strtoul(value, &end, 0);
b166b11b 596 if (value + size != end) fail:
69caa5be 597 pid = _not(pid_t);
69caa5be
JF
598 _syscall(pclose(pids));
599 }
600
601 if (pid == _not(pid_t)) {
10d0e915 602 fprintf(stderr, "unable to find process `%s' using ps\n", optarg);
69caa5be
JF
603 return 1;
604 }
06edab7d 605 }
96746747 606 } goto target;
2aa77fd8 607#endif
b10bd496 608
666eedb9 609 case 'r': {
10d0e915 610 //size_t size(strlen(optarg));
666eedb9 611
10d0e915 612 char *colon(strrchr(optarg, ':'));
666eedb9
JF
613 if (colon == NULL) {
614 fprintf(stderr, "missing colon in hostspec\n");
615 return 1;
616 }
617
618 /*char *end;
619 port = strtoul(colon + 1, &end, 10);
10d0e915 620 if (end != optarg + size) {
666eedb9
JF
621 fprintf(stderr, "invalid port in hostspec\n");
622 return 1;
623 }*/
624
10d0e915 625 host = optarg;
666eedb9
JF
626 *colon = '\0';
627 port = colon + 1;
96746747 628 } goto target;
666eedb9 629
06edab7d
JF
630 case 's':
631 strict_ = true;
632 break;
10d0e915
JF
633
634 default:
635 _assert(false);
06edab7d 636 }
10d0e915
JF
637 }
638
639 getopt:
640 argc -= optind;
641 argv += optind;
967067aa 642
b09da87b
JF
643 const char *script;
644
2aa77fd8 645#ifdef CY_ATTACH
10d0e915 646 if (pid != _not(pid_t) && argc > 1) {
fcc64bb5
JF
647 fprintf(stderr, "-p cannot set argv\n");
648 return 1;
649 }
2aa77fd8 650#endif
75b0a457 651
10d0e915 652 if (argc == 0)
b09da87b
JF
653 script = NULL;
654 else {
9185d5ef 655#ifdef CY_EXECUTE
967067aa 656 // XXX: const_cast?! wtf gcc :(
10d0e915 657 CYSetArgs(argc - 1, const_cast<const char **>(argv + 1));
9185d5ef 658#endif
10d0e915 659 script = argv[0];
967067aa
JF
660 if (strcmp(script, "-") == 0)
661 script = NULL;
b09da87b
JF
662 }
663
2aa77fd8 664#ifdef CY_ATTACH
967067aa 665 if (pid == _not(pid_t))
7e5391fd 666 client_ = -1;
967067aa 667 else {
46d13f4c
JF
668 struct Socket {
669 int fd_;
b166b11b 670
46d13f4c
JF
671 Socket(int fd) :
672 fd_(fd)
673 {
674 }
96cc7967 675
46d13f4c
JF
676 ~Socket() {
677 close(fd_);
678 }
96cc7967 679
46d13f4c
JF
680 operator int() {
681 return fd_;
682 }
683 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
96cc7967 684
46d13f4c
JF
685 struct sockaddr_un address;
686 memset(&address, 0, sizeof(address));
687 address.sun_family = AF_UNIX;
b166b11b 688
f8d45a20
JF
689 const char *tmp;
690#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
691 tmp = "/Library/Caches";
692#else
693 tmp = "/tmp";
694#endif
695
696 sprintf(address.sun_path, "%s/.s.cy.%u", tmp, getpid());
46d13f4c 697 unlink(address.sun_path);
b166b11b 698
46d13f4c
JF
699 struct File {
700 const char *path_;
701
702 File(const char *path) :
703 path_(path)
704 {
705 }
706
707 ~File() {
708 unlink(path_);
709 }
710 } file(address.sun_path);
711
712 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
713 _syscall(chmod(address.sun_path, 0777));
714
715 _syscall(listen(server, 1));
ccb4e34c
JF
716 const char *const argv[] = {address.sun_path, NULL};
717 InjectLibrary(pid, 1, argv);
46d13f4c 718 client_ = _syscall(accept(server, NULL, NULL));
967067aa 719 }
2aa77fd8 720#else
7e5391fd 721 client_ = -1;
2aa77fd8 722#endif
579ed526 723
666eedb9
JF
724 if (client_ == -1 && host != NULL && port != NULL) {
725 struct addrinfo hints;
726 memset(&hints, 0, sizeof(hints));
727 hints.ai_family = AF_UNSPEC;
728 hints.ai_socktype = SOCK_STREAM;
729 hints.ai_protocol = 0;
730 hints.ai_flags = 0;
731
732 struct addrinfo *infos;
733 _syscall(getaddrinfo(host, port, &hints, &infos));
734
735 _assert(infos != NULL); try {
736 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
737 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
738 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
739 client_ = client;
740 break;
741 } catch (...) {
742 _syscall(close(client));
743 throw;
744 }
745 }
746 } catch (...) {
747 freeaddrinfo(infos);
748 throw;
749 }
750 }
751
48e3be8a 752 if (script == NULL && tty)
2eb8215d 753 Console(options);
b09da87b 754 else {
0df6a201 755 std::istream *stream;
48e3be8a 756 if (script == NULL) {
0df6a201
JF
757 stream = &std::cin;
758 script = "<stdin>";
48e3be8a 759 } else {
0df6a201
JF
760 stream = new std::fstream(script, std::ios::in | std::ios::binary);
761 _assert(!stream->fail());
48e3be8a 762 }
62ca2b82 763
341d1456
JF
764 if (timing_) {
765 std::stringbuf buffer;
766 stream->get(buffer, '\0');
767 _assert(!stream->fail());
768
769 double average(0);
770 int samples(-50);
771 uint64_t start(CYGetTime());
772
773 for (;;) {
774 stream = new std::istringstream(buffer.str());
775
776 CYPool pool;
777 CYDriver driver(pool, *stream, script);
778 Setup(driver);
779
780 uint64_t begin(CYGetTime());
781 driver.Parse();
782 uint64_t end(CYGetTime());
783
784 delete stream;
785
786 average += (end - begin - average) / ++samples;
787
788 uint64_t now(CYGetTime());
789 if (samples == 0)
790 average = 0;
791 else if ((now - start) / 1000000000 >= 1)
792 std::cout << std::fixed << average << '\t' << (end - begin) << '\t' << samples << std::endl;
793 else continue;
794
795 start = now;
796 }
797
798 stream = new std::istringstream(buffer.str());
799 std::cin.get();
800 }
801
2c1d569a
JF
802 CYPool pool;
803 CYDriver driver(pool, *stream, script);
d9c91152
JF
804 Setup(driver);
805
2c1d569a 806 bool failed(driver.Parse());
d3b63265 807
d9c91152 808 if (failed || !driver.errors_.empty()) {
b09da87b
JF
809 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
810 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
a7d8b413 811 } else if (driver.script_ != NULL) {
efd689d8 812 std::stringbuf str;
0df6a201 813 CYOutput out(str, options);
2c1d569a 814 Setup(out, driver, options, true);
a7d8b413 815 out << *driver.script_;
0df6a201
JF
816 std::string code(str.str());
817 if (compile)
818 std::cout << code;
819 else
82a02ede 820 Run(client_, false, code, &std::cout);
0df6a201 821 }
057f943f 822 }
62ca2b82 823
057f943f 824 return 0;
62ca2b82 825}
b6961e53 826
10d0e915
JF
827int main(int argc, char * const argv[], char const * const envp[]) {
828 try {
b6961e53
JF
829 return Main(argc, argv, envp);
830 } catch (const CYException &error) {
831 CYPool pool;
832 fprintf(stderr, "%s\n", error.PoolCString(pool));
833 return 1;
834 }
835}