]> git.saurik.com Git - cycript.git/blame - Console.cpp
Allow multi-line editing and drop libedit support.
[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>
51b2dc6b 29#include <complex>
0df6a201 30#include <fstream>
057f943f
JF
31#include <sstream>
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 45#include <errno.h>
10d0e915 46#include <getopt.h>
51b2dc6b 47#include <setjmp.h>
10d0e915 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
51b2dc6b 57#include <sys/ioctl.h>
967067aa
JF
58#include <sys/types.h>
59#include <sys/socket.h>
60#include <netinet/in.h>
61#include <sys/un.h>
62
da858962 63#include <dlfcn.h>
51b2dc6b
JF
64#include <pwd.h>
65#include <term.h>
da858962 66
341d1456
JF
67#ifdef __APPLE__
68#include <mach/mach_time.h>
69#endif
70
b12a9965 71#include "Driver.hpp"
e66ced89 72#include "Error.hpp"
d9c91152 73#include "Highlight.hpp"
20052ff7 74#include "Syntax.hpp"
7e5391fd 75
51b2dc6b
JF
76extern "C" int rl_display_fixed;
77extern "C" int _rl_vis_botlin;
78extern "C" int _rl_last_c_pos;
79extern "C" int _rl_last_v_pos;
80
81typedef std::complex<int> CYCursor;
82
83static CYCursor current_;
84static int width_;
85static size_t point_;
86
87unsigned CYDisplayWidth() {
88 struct winsize info;
89 if (ioctl(1, TIOCGWINSZ, &info) != -1)
90 return info.ws_col;
91 return tgetnum(const_cast<char *>("co"));
92}
93
94void CYDisplayOutput_(bool display, const char *&data) {
95 for (;; ++data) {
96 char next(*data);
97 if (next == '\0' || next == CYIgnoreEnd)
98 return;
99 if (display)
100 putchar(next);
101 }
102}
103
104CYCursor CYDisplayOutput(bool display, int width, const char *data, ssize_t offset = 0) {
105 CYCursor point(current_);
106
107 for (;;) {
108 if (offset-- == 0)
109 point = current_;
110 switch (char next = *data++) {
111 case '\0':
112 return point;
113 break;
114
115 case CYIgnoreStart:
116 CYDisplayOutput_(display, data);
117 case CYIgnoreEnd:
118 ++offset;
119 break;
120
121 default:
122 if (display)
123 putchar(next);
124 current_ += CYCursor(0, 1);
125 if (current_.imag() != width)
126 break;
127 current_ = CYCursor(current_.real() + 1, 0);
128 if (display)
129 putp(clr_eos);
130 break;
131
132 case '\n':
133 current_ = CYCursor(current_.real() + 1, 4);
134 if (display) {
135 putp(clr_eol);
136 putchar('\n');
137 putchar(' ');
138 putchar(' ');
139 putchar(' ');
140 putchar(' ');
141 }
142 break;
143
144 }
145 }
146}
147
148void CYDisplayMove_(char *negative, char *positive, int offset) {
149 if (offset < 0)
150 putp(tparm(negative, -offset));
151 else if (offset > 0)
152 putp(tparm(positive, offset));
153}
154
155void CYDisplayMove(CYCursor target) {
156 CYCursor offset(target - current_);
157
158 CYDisplayMove_(parm_up_cursor, parm_down_cursor, offset.real());
159
160 if (char *parm = tparm(column_address, target.imag()))
161 putp(parm);
162 else
163 CYDisplayMove_(parm_left_cursor, parm_right_cursor, offset.imag());
164
165 current_ = target;
166}
167
168void CYDisplayUpdate() {
169 current_ = CYCursor(_rl_last_v_pos, _rl_last_c_pos);
170
171 const char *prompt(rl_display_prompt);
172
173 std::ostringstream stream;
174 CYLexerHighlight(rl_line_buffer, rl_end, stream, true);
175 std::string string(stream.str());
176 const char *buffer(string.c_str());
177
178 int width(CYDisplayWidth());
179 if (width_ != width) {
180 current_ = CYCursor();
181 CYDisplayOutput(false, width, prompt);
182 current_ = CYDisplayOutput(false, width, buffer, point_);
183 }
184
185 CYDisplayMove(CYCursor());
186 CYDisplayOutput(true, width, prompt);
187 CYCursor target(CYDisplayOutput(true, width, stream.str().c_str(), rl_point));
188
189 _rl_vis_botlin = current_.real();
190
191 if (current_.imag() == 0)
192 CYDisplayOutput(true, width, " ");
193 putp(clr_eos);
194
195 CYDisplayMove(target);
196 fflush(stdout);
197
198 _rl_last_v_pos = current_.real();
199 _rl_last_c_pos = current_.imag();
200
201 width_ = width;
202 point_ = rl_point;
203}
204
4e39dc0b
JF
205static volatile enum {
206 Working,
207 Parsing,
208 Running,
209 Sending,
210 Waiting,
211} mode_;
212
057f943f
JF
213static jmp_buf ctrlc_;
214
579ed526 215static void sigint(int) {
4e39dc0b
JF
216 switch (mode_) {
217 case Working:
218 return;
219 case Parsing:
220 longjmp(ctrlc_, 1);
221 case Running:
b0ba908c
JF
222 CYCancel();
223 return;
4e39dc0b
JF
224 case Sending:
225 return;
226 case Waiting:
227 return;
228 }
057f943f
JF
229}
230
cac61857 231static bool bison_;
341d1456 232static bool timing_;
b10bd496 233static bool strict_;
11c1cc16 234static bool pretty_;
cac61857 235
d9c91152 236void Setup(CYDriver &driver) {
cac61857 237 if (bison_)
d9c91152 238 driver.debug_ = 1;
b10bd496
JF
239 if (strict_)
240 driver.strict_ = true;
cac61857
JF
241}
242
2c1d569a 243void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) {
11c1cc16 244 out.pretty_ = pretty_;
36bf49c4 245 if (lower)
2c1d569a 246 driver.Replace(options);
11c1cc16
JF
247}
248
7e5391fd 249static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
967067aa 250 const char *json;
9d79cefc 251 uint32_t size;
7e5391fd 252
b166b11b 253 if (client == -1) {
4e39dc0b 254 mode_ = Running;
2aa77fd8 255#ifdef CY_EXECUTE
89d16b11 256 json = CYExecute(CYGetJSContext(), pool, code);
2aa77fd8
JF
257#else
258 json = NULL;
259#endif
4e39dc0b 260 mode_ = Working;
dd221c6b
JF
261 if (json == NULL)
262 size = 0;
263 else
6ec85c5b
JF
264 size = strlen(json);
265 } else {
4e39dc0b 266 mode_ = Sending;
0ced2e47 267 size = code.size;
a1f3555e
JF
268 _assert(CYSendAll(client, &size, sizeof(size)));
269 _assert(CYSendAll(client, code.data, code.size));
4e39dc0b 270 mode_ = Waiting;
a1f3555e 271 _assert(CYRecvAll(client, &size, sizeof(size)));
9d79cefc 272 if (size == _not(uint32_t))
967067aa
JF
273 json = NULL;
274 else {
275 char *temp(new(pool) char[size + 1]);
a1f3555e 276 _assert(CYRecvAll(client, temp, size));
967067aa
JF
277 temp[size] = '\0';
278 json = temp;
279 }
4e39dc0b 280 mode_ = Working;
4cf49641 281 }
b09da87b 282
7e5391fd
JF
283 return CYUTF8String(json, size);
284}
285
286static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
287 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
288}
289
2e2ed904 290static std::ostream *out_;
a3f4a8e1 291
e66ced89 292static void Output(CYUTF8String json, std::ostream *out, bool expand = false) {
a3f4a8e1
JF
293 const char *data(json.data);
294 size_t size(json.size);
295
2e2ed904 296 if (data == NULL || out == NULL)
a3f4a8e1
JF
297 return;
298
0881deb5
JF
299 if (!expand ||
300 data[0] != '@' && data[0] != '"' && data[0] != '\'' ||
301 data[0] == '@' && data[1] != '"' && data[1] != '\''
302 )
e66ced89 303 CYLexerHighlight(data, size, *out);
a3f4a8e1
JF
304 else for (size_t i(0); i != size; ++i)
305 if (data[i] != '\\')
2e2ed904 306 *out << data[i];
a3f4a8e1
JF
307 else switch(data[++i]) {
308 case '\0': goto done;
2e2ed904
JF
309 case '\\': *out << '\\'; break;
310 case '\'': *out << '\''; break;
311 case '"': *out << '"'; break;
312 case 'b': *out << '\b'; break;
313 case 'f': *out << '\f'; break;
314 case 'n': *out << '\n'; break;
315 case 'r': *out << '\r'; break;
316 case 't': *out << '\t'; break;
317 case 'v': *out << '\v'; break;
318 default: *out << '\\'; --i; break;
a3f4a8e1 319 }
6ec85c5b 320
a3f4a8e1 321 done:
2e2ed904 322 *out << std::endl;
a3f4a8e1
JF
323}
324
da858962
JF
325int (*append_history$)(int, const char *);
326
7e5391fd
JF
327static std::string command_;
328
d9c91152 329static int client_;
b0385401 330
d9c91152
JF
331static CYUTF8String Run(CYPool &pool, const std::string &code) {
332 return Run(pool, client_, code);
7e5391fd
JF
333}
334
7e5391fd 335static char **Complete(const char *word, int start, int end) {
10d0e915 336 rl_attempted_completion_over = ~0;
7e5391fd 337 std::string line(rl_line_buffer, start);
51b2dc6b
JF
338 char **values(CYComplete(word, command_ + line, &Run));
339 return values;
7e5391fd
JF
340}
341
342// need char *, not const char *
343static char name_[] = "cycript";
87450281 344static char break_[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]";
7e5391fd 345
da136f88
JF
346class History {
347 private:
348 std::string histfile_;
349 size_t histlines_;
350
351 public:
352 History(std::string histfile) :
353 histfile_(histfile),
354 histlines_(0)
355 {
356 read_history(histfile_.c_str());
51b2dc6b
JF
357
358 for (HIST_ENTRY *history((history_set_pos(0), current_history())); history; history = next_history())
359 for (char *character(history->line); *character; ++character)
360 if (*character == '\x01') *character = '\n';
da136f88
JF
361 }
362
363 ~History() {
51b2dc6b
JF
364 for (HIST_ENTRY *history((history_set_pos(0), current_history())); history; history = next_history())
365 for (char *character(history->line); *character; ++character)
366 if (*character == '\n') *character = '\x01';
367
da136f88 368 if (append_history$ != NULL) {
f61fec22
JF
369 int fd(_syscall(open(histfile_.c_str(), O_CREAT | O_WRONLY, 0600)));
370 _syscall(close(fd));
da136f88
JF
371 _assert((*append_history$)(histlines_, histfile_.c_str()) == 0);
372 } else {
373 _assert(write_history(histfile_.c_str()) == 0);
374 }
375 }
376
51b2dc6b 377 void operator +=(std::string command) {
6265f0de 378 add_history(command.c_str());
da136f88
JF
379 ++histlines_;
380 }
381};
382
51b2dc6b
JF
383static int CYConsoleKeyReturn(int count, int key) {
384 rl_insert(count, '\n');
385
386 if (rl_end != 0 && rl_point == rl_end && rl_line_buffer[0] == '?')
387 rl_done = 1;
388 else if (rl_point == rl_end) {
389 std::string command(rl_line_buffer, rl_end);
390 std::istringstream stream(command);
391
392 size_t last(std::string::npos);
393 for (size_t i(0); i != std::string::npos; i = command.find('\n', i + 1))
394 ++last;
395
396 CYPool pool;
397 CYDriver driver(pool, stream);
398 if (driver.Parse() || !driver.errors_.empty())
399 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
400 if (error->location_.begin.line != last + 1)
401 rl_done = 1;
402 break;
403 }
404 else
405 rl_done = 1;
406 }
407
408 if (rl_done)
409 std::cout << std::endl;
410 return 0;
411}
412
2eb8215d 413static void Console(CYOptions &options) {
1210260f
JF
414 std::string basedir;
415 if (const char *home = getenv("HOME"))
416 basedir = home;
417 else {
418 passwd *passwd;
419 if (const char *username = getenv("LOGNAME"))
420 passwd = getpwnam(username);
421 else
422 passwd = getpwuid(getuid());
423 basedir = passwd->pw_dir;
424 }
b1589845 425
da136f88
JF
426 basedir += "/.cycript";
427 mkdir(basedir.c_str(), 0700);
b1589845 428
7e5391fd
JF
429 rl_initialize();
430 rl_readline_name = name_;
431
da136f88 432 History history(basedir + "/history");
b1589845 433
1f8eae40
JF
434 bool bypass(false);
435 bool debug(false);
6ec85c5b 436 bool expand(false);
36bf49c4 437 bool lower(true);
1f8eae40 438
2e2ed904 439 out_ = &std::cout;
057f943f 440
bc1e87aa 441 rl_completer_word_break_characters = break_;
7e5391fd
JF
442 rl_attempted_completion_function = &Complete;
443 rl_bind_key('\t', rl_complete);
057f943f 444
e66ced89 445 rl_redisplay_function = CYDisplayUpdate;
e66ced89 446
057f943f
JF
447 struct sigaction action;
448 sigemptyset(&action.sa_mask);
449 action.sa_handler = &sigint;
450 action.sa_flags = 0;
451 sigaction(SIGINT, &action, NULL);
452
51b2dc6b 453 for (;;) {
057f943f 454 if (setjmp(ctrlc_) != 0) {
4e39dc0b 455 mode_ = Working;
2e2ed904 456 *out_ << std::endl;
51b2dc6b 457 continue;
057f943f
JF
458 }
459
51b2dc6b
JF
460 if (bypass)
461 rl_bind_key('\r', &rl_newline);
462 else
463 rl_bind_key('\r', &CYConsoleKeyReturn);
464
4e39dc0b 465 mode_ = Parsing;
51b2dc6b 466 char *line(readline("cy# "));
4e39dc0b 467 mode_ = Working;
cd98d280 468
79357996
JF
469 if (line == NULL) {
470 *out_ << std::endl;
057f943f 471 break;
931b816a
JF
472 }
473
51b2dc6b
JF
474 std::string command(line);
475 free(line);
476 _assert(!command.empty());
477 _assert(command[command.size() - 1] == '\n');
478 command.resize(command.size() - 1);
479 if (command.empty())
480 continue;
481
482 if (command[0] == '?') {
483 std::string data(command.substr(1));
484 if (data == "bypass") {
485 bypass = !bypass;
486 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
487 } else if (data == "debug") {
488 debug = !debug;
489 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
490 } else if (data == "destroy") {
491 CYDestroyContext();
492 } else if (data == "gc") {
493 *out_ << "collecting... " << std::flush;
494 CYGarbageCollect(CYGetJSContext());
495 *out_ << "done." << std::endl;
496 } else if (data == "exit") {
497 return;
498 } else if (data == "expand") {
499 expand = !expand;
500 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
501 } else if (data == "lower") {
502 lower = !lower;
503 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
504 }
e818f0e0 505
51b2dc6b
JF
506 history += command;
507 continue;
e818f0e0
JF
508 }
509
1f8eae40 510 std::string code;
1f8eae40 511 if (bypass)
51b2dc6b 512 code = command;
1f8eae40 513 else {
51b2dc6b 514 std::istringstream stream(command);
d3b63265 515
d9c91152 516 CYPool pool;
2c1d569a
JF
517 CYDriver driver(pool, stream);
518 Setup(driver);
519
51b2dc6b 520 if (driver.Parse() || !driver.errors_.empty()) {
f0360d51 521 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
58afc6aa 522 CYPosition begin(error->location_.begin);
51b2dc6b 523 CYPosition end(error->location_.end);
48e3be8a 524
51b2dc6b 525 /*if (begin.line != lines2.size()) {
f0360d51 526 std::cerr << " | ";
51b2dc6b
JF
527 std::cerr << lines2[begin.line - 1] << std::endl;
528 }*/
529
530 std::cerr << "....";
531 for (size_t i(0); i != begin.column; ++i)
532 std::cerr << '.';
533 if (begin.line != end.line || begin.column == end.column)
534 std::cerr << '^';
535 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
536 std::cerr << '^';
537 std::cerr << std::endl;
538
539 std::cerr << " | ";
540 std::cerr << error->message_ << std::endl;
541
542 history += command;
543 break;
1f8eae40 544 }
057f943f 545
51b2dc6b 546 continue;
057f943f
JF
547 }
548
a7d8b413 549 if (driver.script_ == NULL)
51b2dc6b 550 continue;
057f943f 551
efd689d8 552 std::stringbuf str;
0df6a201 553 CYOutput out(str, options);
2c1d569a 554 Setup(out, driver, options, lower);
a7d8b413 555 out << *driver.script_;
0df6a201 556 code = str.str();
057f943f
JF
557 }
558
51b2dc6b 559 history += command;
057f943f 560
82a02ede 561 if (debug) {
f43fcb85 562 std::cout << "cy= ";
e66ced89 563 CYLexerHighlight(code.c_str(), code.size(), std::cout);
82a02ede
JF
564 std::cout << std::endl;
565 }
057f943f 566
e66ced89
JF
567 CYPool pool;
568 Output(Run(pool, client_, code), &std::cout, expand);
b09da87b 569 }
b09da87b 570}
057f943f 571
ccb4e34c 572void InjectLibrary(pid_t, int, const char *const []);
06edab7d 573
341d1456
JF
574static uint64_t CYGetTime() {
575#ifdef __APPLE__
576 return mach_absolute_time();
577#else
578 struct timespec spec;
579 clock_gettime(CLOCK_MONOTONIC, &spec);
580 return spec.tv_sec * UINT64_C(1000000000) + spec.tv_nsec;
581#endif
582}
583
10d0e915 584int Main(int argc, char * const argv[], char const * const envp[]) {
48e3be8a 585 bool tty(isatty(STDIN_FILENO));
75b0a457 586 bool compile(false);
96746747 587 bool target(false);
de9fc71b 588 CYOptions options;
967067aa 589
e4676127 590 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
da858962 591
2aa77fd8
JF
592#ifdef CY_ATTACH
593 pid_t pid(_not(pid_t));
594#endif
595
666eedb9
JF
596 const char *host(NULL);
597 const char *port(NULL);
598
10d0e915 599 optind = 1;
06edab7d
JF
600
601 for (;;) {
10d0e915
JF
602 int option(getopt_long(argc, argv,
603 "c"
604 "g:"
605 "n:"
2aa77fd8 606#ifdef CY_ATTACH
10d0e915 607 "p:"
2aa77fd8 608#endif
10d0e915
JF
609 "r:"
610 "s"
f61fec22 611 , (const struct option[]) {
10d0e915
JF
612 {NULL, no_argument, NULL, 'c'},
613 {NULL, required_argument, NULL, 'g'},
614 {NULL, required_argument, NULL, 'n'},
615#ifdef CY_ATTACH
616 {NULL, required_argument, NULL, 'p'},
617#endif
618 {NULL, required_argument, NULL, 'r'},
619 {NULL, no_argument, NULL, 's'},
620 {0, 0, 0, 0}}, NULL));
06edab7d 621
10d0e915
JF
622 switch (option) {
623 case -1:
06edab7d 624 goto getopt;
10d0e915
JF
625
626 case ':':
627 case '?':
06edab7d
JF
628 fprintf(stderr,
629 "usage: cycript [-c]"
2aa77fd8 630#ifdef CY_ATTACH
69caa5be 631 " [-p <pid|name>]"
2aa77fd8 632#endif
666eedb9 633 " [-r <host:port>]"
06edab7d
JF
634 " [<script> [<arg>...]]\n"
635 );
636 return 1;
967067aa 637
96746747
JF
638 target:
639 if (!target)
640 target = true;
641 else {
642 fprintf(stderr, "only one of -[c"
643#ifdef CY_ATTACH
644 "p"
645#endif
646 "r] may be used at a time\n");
647 return 1;
648 }
649 break;
650
06edab7d
JF
651 case 'c':
652 compile = true;
96746747 653 goto target;
75b0a457 654
06edab7d
JF
655 case 'g':
656 if (false);
10d0e915 657 else if (strcmp(optarg, "rename") == 0)
de9fc71b 658 options.verbose_ = true;
10d0e915 659 else if (strcmp(optarg, "bison") == 0)
06edab7d 660 bison_ = true;
341d1456
JF
661 else if (strcmp(optarg, "timing") == 0)
662 timing_ = true;
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);
10d0e915 671 else if (strcmp(optarg, "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': {
10d0e915 681 size_t size(strlen(optarg));
06edab7d 682 char *end;
69caa5be 683
10d0e915
JF
684 pid = strtoul(optarg, &end, 0);
685 if (optarg + size != end) {
69caa5be 686 // XXX: arg needs to be escaped in some horrendous way of doom
10d0e915
JF
687 // XXX: this is a memory leak now because I just don't care enough
688 char *command;
ccb4e34c
JF
689 int writ(asprintf(&command, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg));
690 _assert(writ != -1);
69caa5be
JF
691
692 if (FILE *pids = popen(command, "r")) {
693 char value[32];
694 size = 0;
695
696 for (;;) {
697 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
698 if (read == 0)
699 break;
700 else {
701 size += read;
04aa6240 702 if (size == sizeof(value))
b166b11b 703 goto fail;
69caa5be
JF
704 }
705 }
706
707 size:
708 if (size == 0)
b166b11b 709 goto fail;
69caa5be
JF
710 if (value[size - 1] == '\n') {
711 --size;
712 goto size;
713 }
714
715 value[size] = '\0';
716 size = strlen(value);
717 pid = strtoul(value, &end, 0);
b166b11b 718 if (value + size != end) fail:
69caa5be 719 pid = _not(pid_t);
69caa5be
JF
720 _syscall(pclose(pids));
721 }
722
723 if (pid == _not(pid_t)) {
10d0e915 724 fprintf(stderr, "unable to find process `%s' using ps\n", optarg);
69caa5be
JF
725 return 1;
726 }
06edab7d 727 }
96746747 728 } goto target;
2aa77fd8 729#endif
b10bd496 730
666eedb9 731 case 'r': {
10d0e915 732 //size_t size(strlen(optarg));
666eedb9 733
10d0e915 734 char *colon(strrchr(optarg, ':'));
666eedb9
JF
735 if (colon == NULL) {
736 fprintf(stderr, "missing colon in hostspec\n");
737 return 1;
738 }
739
740 /*char *end;
741 port = strtoul(colon + 1, &end, 10);
10d0e915 742 if (end != optarg + size) {
666eedb9
JF
743 fprintf(stderr, "invalid port in hostspec\n");
744 return 1;
745 }*/
746
10d0e915 747 host = optarg;
666eedb9
JF
748 *colon = '\0';
749 port = colon + 1;
96746747 750 } goto target;
666eedb9 751
06edab7d
JF
752 case 's':
753 strict_ = true;
754 break;
10d0e915
JF
755
756 default:
757 _assert(false);
06edab7d 758 }
10d0e915
JF
759 }
760
761 getopt:
762 argc -= optind;
763 argv += optind;
967067aa 764
b09da87b
JF
765 const char *script;
766
2aa77fd8 767#ifdef CY_ATTACH
10d0e915 768 if (pid != _not(pid_t) && argc > 1) {
fcc64bb5
JF
769 fprintf(stderr, "-p cannot set argv\n");
770 return 1;
771 }
2aa77fd8 772#endif
75b0a457 773
10d0e915 774 if (argc == 0)
b09da87b
JF
775 script = NULL;
776 else {
9185d5ef 777#ifdef CY_EXECUTE
967067aa 778 // XXX: const_cast?! wtf gcc :(
10d0e915 779 CYSetArgs(argc - 1, const_cast<const char **>(argv + 1));
9185d5ef 780#endif
10d0e915 781 script = argv[0];
967067aa
JF
782 if (strcmp(script, "-") == 0)
783 script = NULL;
b09da87b
JF
784 }
785
2aa77fd8 786#ifdef CY_ATTACH
967067aa 787 if (pid == _not(pid_t))
7e5391fd 788 client_ = -1;
967067aa 789 else {
46d13f4c
JF
790 struct Socket {
791 int fd_;
b166b11b 792
46d13f4c
JF
793 Socket(int fd) :
794 fd_(fd)
795 {
796 }
96cc7967 797
46d13f4c
JF
798 ~Socket() {
799 close(fd_);
800 }
96cc7967 801
46d13f4c
JF
802 operator int() {
803 return fd_;
804 }
805 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
96cc7967 806
46d13f4c
JF
807 struct sockaddr_un address;
808 memset(&address, 0, sizeof(address));
809 address.sun_family = AF_UNIX;
b166b11b 810
f8d45a20
JF
811 const char *tmp;
812#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
813 tmp = "/Library/Caches";
814#else
815 tmp = "/tmp";
816#endif
817
818 sprintf(address.sun_path, "%s/.s.cy.%u", tmp, getpid());
46d13f4c 819 unlink(address.sun_path);
b166b11b 820
46d13f4c
JF
821 struct File {
822 const char *path_;
823
824 File(const char *path) :
825 path_(path)
826 {
827 }
828
829 ~File() {
830 unlink(path_);
831 }
832 } file(address.sun_path);
833
834 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
835 _syscall(chmod(address.sun_path, 0777));
836
837 _syscall(listen(server, 1));
ccb4e34c
JF
838 const char *const argv[] = {address.sun_path, NULL};
839 InjectLibrary(pid, 1, argv);
46d13f4c 840 client_ = _syscall(accept(server, NULL, NULL));
967067aa 841 }
2aa77fd8 842#else
7e5391fd 843 client_ = -1;
2aa77fd8 844#endif
579ed526 845
666eedb9
JF
846 if (client_ == -1 && host != NULL && port != NULL) {
847 struct addrinfo hints;
848 memset(&hints, 0, sizeof(hints));
849 hints.ai_family = AF_UNSPEC;
850 hints.ai_socktype = SOCK_STREAM;
851 hints.ai_protocol = 0;
852 hints.ai_flags = 0;
853
854 struct addrinfo *infos;
855 _syscall(getaddrinfo(host, port, &hints, &infos));
856
857 _assert(infos != NULL); try {
858 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
859 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
860 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
861 client_ = client;
862 break;
863 } catch (...) {
864 _syscall(close(client));
865 throw;
866 }
867 }
868 } catch (...) {
869 freeaddrinfo(infos);
870 throw;
871 }
872 }
873
48e3be8a 874 if (script == NULL && tty)
2eb8215d 875 Console(options);
b09da87b 876 else {
0df6a201 877 std::istream *stream;
48e3be8a 878 if (script == NULL) {
0df6a201
JF
879 stream = &std::cin;
880 script = "<stdin>";
48e3be8a 881 } else {
0df6a201
JF
882 stream = new std::fstream(script, std::ios::in | std::ios::binary);
883 _assert(!stream->fail());
48e3be8a 884 }
62ca2b82 885
341d1456
JF
886 if (timing_) {
887 std::stringbuf buffer;
888 stream->get(buffer, '\0');
889 _assert(!stream->fail());
890
891 double average(0);
892 int samples(-50);
893 uint64_t start(CYGetTime());
894
895 for (;;) {
896 stream = new std::istringstream(buffer.str());
897
898 CYPool pool;
899 CYDriver driver(pool, *stream, script);
900 Setup(driver);
901
902 uint64_t begin(CYGetTime());
903 driver.Parse();
904 uint64_t end(CYGetTime());
905
906 delete stream;
907
908 average += (end - begin - average) / ++samples;
909
910 uint64_t now(CYGetTime());
911 if (samples == 0)
912 average = 0;
913 else if ((now - start) / 1000000000 >= 1)
914 std::cout << std::fixed << average << '\t' << (end - begin) << '\t' << samples << std::endl;
915 else continue;
916
917 start = now;
918 }
919
920 stream = new std::istringstream(buffer.str());
921 std::cin.get();
922 }
923
2c1d569a
JF
924 CYPool pool;
925 CYDriver driver(pool, *stream, script);
d9c91152
JF
926 Setup(driver);
927
2c1d569a 928 bool failed(driver.Parse());
d3b63265 929
d9c91152 930 if (failed || !driver.errors_.empty()) {
b09da87b
JF
931 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
932 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
a7d8b413 933 } else if (driver.script_ != NULL) {
efd689d8 934 std::stringbuf str;
0df6a201 935 CYOutput out(str, options);
2c1d569a 936 Setup(out, driver, options, true);
a7d8b413 937 out << *driver.script_;
0df6a201
JF
938 std::string code(str.str());
939 if (compile)
940 std::cout << code;
e66ced89
JF
941 else {
942 CYUTF8String json(Run(pool, client_, code));
943 if (CYStartsWith(json, "throw ")) {
944 CYLexerHighlight(json.data, json.size, std::cerr);
945 std::cerr << std::endl;
946 return 1;
947 }
948 }
0df6a201 949 }
057f943f 950 }
62ca2b82 951
057f943f 952 return 0;
62ca2b82 953}
b6961e53 954
10d0e915
JF
955int main(int argc, char * const argv[], char const * const envp[]) {
956 try {
b6961e53
JF
957 return Main(argc, argv, envp);
958 } catch (const CYException &error) {
959 CYPool pool;
960 fprintf(stderr, "%s\n", error.PoolCString(pool));
961 return 1;
962 }
963}