]> git.saurik.com Git - cycript.git/blob - Console.cpp
Commit line on return inside single-line commands.
[cycript.git] / Console.cpp
1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2015 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
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
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
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/>.
19 **/
20 /* }}} */
21
22 #include "cycript.hpp"
23
24 #ifdef CY_EXECUTE
25 #include "JavaScript.hpp"
26 #endif
27
28 #include <cstdio>
29 #include <complex>
30 #include <fstream>
31 #include <sstream>
32
33 #ifdef HAVE_READLINE_H
34 #include <readline.h>
35 #else
36 #include <readline/readline.h>
37 #endif
38
39 #ifdef HAVE_HISTORY_H
40 #include <history.h>
41 #else
42 #include <readline/history.h>
43 #endif
44
45 #include <errno.h>
46 #include <getopt.h>
47 #include <setjmp.h>
48 #include <signal.h>
49 #include <unistd.h>
50
51 #include <sys/socket.h>
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <fcntl.h>
55 #include <netdb.h>
56
57 #include <sys/ioctl.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <sys/un.h>
62
63 #include <dlfcn.h>
64 #include <pwd.h>
65 #include <term.h>
66
67 #ifdef __APPLE__
68 #include <mach/mach_time.h>
69 #endif
70
71 #include "Driver.hpp"
72 #include "Error.hpp"
73 #include "Highlight.hpp"
74 #include "Syntax.hpp"
75
76 extern "C" int rl_display_fixed;
77 extern "C" int _rl_vis_botlin;
78 extern "C" int _rl_last_c_pos;
79 extern "C" int _rl_last_v_pos;
80
81 typedef std::complex<int> CYCursor;
82
83 static CYCursor current_;
84 static int width_;
85 static size_t point_;
86
87 unsigned 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
94 void 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
104 CYCursor 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
148 void 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
155 void 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
168 void 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
205 static volatile enum {
206 Working,
207 Parsing,
208 Running,
209 Sending,
210 Waiting,
211 } mode_;
212
213 static jmp_buf ctrlc_;
214
215 static void sigint(int) {
216 switch (mode_) {
217 case Working:
218 return;
219 case Parsing:
220 longjmp(ctrlc_, 1);
221 case Running:
222 CYCancel();
223 return;
224 case Sending:
225 return;
226 case Waiting:
227 return;
228 }
229 }
230
231 static bool bison_;
232 static bool timing_;
233 static bool strict_;
234 static bool pretty_;
235
236 void Setup(CYDriver &driver) {
237 if (bison_)
238 driver.debug_ = 1;
239 if (strict_)
240 driver.strict_ = true;
241 }
242
243 void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) {
244 out.pretty_ = pretty_;
245 if (lower)
246 driver.Replace(options);
247 }
248
249 static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
250 const char *json;
251 uint32_t size;
252
253 if (client == -1) {
254 mode_ = Running;
255 #ifdef CY_EXECUTE
256 json = CYExecute(CYGetJSContext(), pool, code);
257 #else
258 json = NULL;
259 #endif
260 mode_ = Working;
261 if (json == NULL)
262 size = 0;
263 else
264 size = strlen(json);
265 } else {
266 mode_ = Sending;
267 size = code.size;
268 _assert(CYSendAll(client, &size, sizeof(size)));
269 _assert(CYSendAll(client, code.data, code.size));
270 mode_ = Waiting;
271 _assert(CYRecvAll(client, &size, sizeof(size)));
272 if (size == _not(uint32_t))
273 json = NULL;
274 else {
275 char *temp(new(pool) char[size + 1]);
276 _assert(CYRecvAll(client, temp, size));
277 temp[size] = '\0';
278 json = temp;
279 }
280 mode_ = Working;
281 }
282
283 return CYUTF8String(json, size);
284 }
285
286 static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
287 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
288 }
289
290 static std::ostream *out_;
291
292 static void Output(CYUTF8String json, std::ostream *out, bool expand = false) {
293 const char *data(json.data);
294 size_t size(json.size);
295
296 if (data == NULL || out == NULL)
297 return;
298
299 if (!expand ||
300 data[0] != '@' && data[0] != '"' && data[0] != '\'' ||
301 data[0] == '@' && data[1] != '"' && data[1] != '\''
302 )
303 CYLexerHighlight(data, size, *out);
304 else for (size_t i(0); i != size; ++i)
305 if (data[i] != '\\')
306 *out << data[i];
307 else switch(data[++i]) {
308 case '\0': goto done;
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;
319 }
320
321 done:
322 *out << std::endl;
323 }
324
325 int (*append_history$)(int, const char *);
326
327 static std::string command_;
328
329 static int client_;
330
331 static CYUTF8String Run(CYPool &pool, const std::string &code) {
332 return Run(pool, client_, code);
333 }
334
335 static char **Complete(const char *word, int start, int end) {
336 rl_attempted_completion_over = ~0;
337 std::string line(rl_line_buffer, start);
338 char **values(CYComplete(word, command_ + line, &Run));
339 mode_ = Parsing;
340 return values;
341 }
342
343 // need char *, not const char *
344 static char name_[] = "cycript";
345 static char break_[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]";
346
347 class History {
348 private:
349 std::string histfile_;
350 size_t histlines_;
351
352 public:
353 History(std::string histfile) :
354 histfile_(histfile),
355 histlines_(0)
356 {
357 read_history(histfile_.c_str());
358
359 for (HIST_ENTRY *history((history_set_pos(0), current_history())); history; history = next_history())
360 for (char *character(history->line); *character; ++character)
361 if (*character == '\x01') *character = '\n';
362 }
363
364 ~History() {
365 for (HIST_ENTRY *history((history_set_pos(0), current_history())); history; history = next_history())
366 for (char *character(history->line); *character; ++character)
367 if (*character == '\n') *character = '\x01';
368
369 if (append_history$ != NULL) {
370 int fd(_syscall(open(histfile_.c_str(), O_CREAT | O_WRONLY, 0600)));
371 _syscall(close(fd));
372 _assert((*append_history$)(histlines_, histfile_.c_str()) == 0);
373 } else {
374 _assert(write_history(histfile_.c_str()) == 0);
375 }
376 }
377
378 void operator +=(std::string command) {
379 add_history(command.c_str());
380 ++histlines_;
381 }
382 };
383
384 static int CYConsoleKeyBypass(int count, int key) {
385 rl_point = rl_end;
386 rl_insert(count, '\n');
387 return rl_newline(count, key);
388 }
389
390 static int CYConsoleKeyReturn(int count, int key) {
391 if (rl_point != rl_end) {
392 if (memchr(rl_line_buffer, '\n', rl_end) == NULL)
393 return CYConsoleKeyBypass(count, key);
394 rl_insert(count, '\n');
395 return 0;
396 }
397
398 rl_insert(count, '\n');
399
400 bool done(false);
401 if (rl_line_buffer[0] == '?')
402 done = true;
403 else {
404 std::string command(rl_line_buffer, rl_end);
405 std::istringstream stream(command);
406
407 size_t last(std::string::npos);
408 for (size_t i(0); i != std::string::npos; i = command.find('\n', i + 1))
409 ++last;
410
411 CYPool pool;
412 CYDriver driver(pool, stream);
413 if (driver.Parse() || !driver.errors_.empty())
414 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
415 if (error->location_.begin.line != last + 1)
416 done = true;
417 break;
418 }
419 else
420 done = true;
421 }
422
423 if (done)
424 return rl_newline(count, key);
425 return 0;
426 }
427
428 template <typename Type_>
429 static Type_ *CYmemrchr(Type_ *data, Type_ value, size_t size) {
430 while (size != 0)
431 if (data[--size] == value)
432 return data + size;
433 return NULL;
434 }
435
436 static int CYConsoleKeyUp(int count, int key) {
437 char *after(CYmemrchr(rl_line_buffer, '\n', rl_point));
438 if (after == NULL) {
439 if (int value = rl_get_previous_history(count, key))
440 return value;
441 return 0;
442 }
443
444 char *before(CYmemrchr(rl_line_buffer, '\n', after - rl_line_buffer));
445 if (before == NULL)
446 before = rl_line_buffer - 1;
447
448 ptrdiff_t offset(rl_line_buffer + rl_point - after);
449 if (offset > after - before)
450 rl_point = after - 1 - rl_line_buffer;
451 else
452 rl_point = before + offset - rl_line_buffer;
453
454 return 0;
455 }
456
457 static int CYConsoleKeyDown(int count, int key) {
458 char *after(static_cast<char *>(memchr(rl_line_buffer + rl_point, '\n', rl_end - rl_point)));
459 if (after == NULL) {
460 if (int value = rl_get_next_history(count, key))
461 return value;
462 rl_point = 0;
463 return 0;
464 }
465
466 char *before(CYmemrchr(rl_line_buffer, '\n', rl_point));
467 if (before == NULL)
468 before = rl_line_buffer - 1;
469
470 ptrdiff_t offset(rl_line_buffer + rl_point - before);
471 if (offset > rl_line_buffer + rl_end - after)
472 rl_point = rl_end;
473 else
474 rl_point = after + offset - rl_line_buffer;
475
476 return 0;
477 }
478
479 static void Console(CYOptions &options) {
480 std::string basedir;
481 if (const char *home = getenv("HOME"))
482 basedir = home;
483 else {
484 passwd *passwd;
485 if (const char *username = getenv("LOGNAME"))
486 passwd = getpwnam(username);
487 else
488 passwd = getpwuid(getuid());
489 basedir = passwd->pw_dir;
490 }
491
492 basedir += "/.cycript";
493 mkdir(basedir.c_str(), 0700);
494
495 rl_initialize();
496 rl_readline_name = name_;
497
498 History history(basedir + "/history");
499
500 bool bypass(false);
501 bool debug(false);
502 bool expand(false);
503 bool lower(true);
504
505 out_ = &std::cout;
506
507 rl_completer_word_break_characters = break_;
508 rl_attempted_completion_function = &Complete;
509 rl_bind_key('\t', rl_complete);
510
511 rl_redisplay_function = CYDisplayUpdate;
512
513 #if defined (__MSDOS__)
514 rl_bind_keyseq("\033[0A", &CYConsoleKeyUp);
515 rl_bind_keyseq("\033[0D", &CYConsoleKeyDown);
516 #endif
517 rl_bind_keyseq("\033[A", &CYConsoleKeyUp);
518 rl_bind_keyseq("\033[B", &CYConsoleKeyDown);
519 rl_bind_keyseq("\033OA", &CYConsoleKeyUp);
520 rl_bind_keyseq("\033OB", &CYConsoleKeyDown);
521 #if defined (__MINGW32__)
522 rl_bind_keyseq("\340H", &CYConsoleKeyUp);
523 rl_bind_keyseq("\340P", &CYConsoleKeyDown);
524 rl_bind_keyseq("\\000H", &CYConsoleKeyUp);
525 rl_bind_keyseq("\\000P", &CYConsoleKeyDown);
526 #endif
527
528 struct sigaction action;
529 sigemptyset(&action.sa_mask);
530 action.sa_handler = &sigint;
531 action.sa_flags = 0;
532 sigaction(SIGINT, &action, NULL);
533
534 for (;;) {
535 if (setjmp(ctrlc_) != 0) {
536 mode_ = Working;
537 *out_ << std::endl;
538 continue;
539 }
540
541 if (bypass) {
542 rl_bind_key('\r', &CYConsoleKeyBypass);
543 rl_bind_key('\n', &CYConsoleKeyBypass);
544 } else {
545 rl_bind_key('\r', &CYConsoleKeyReturn);
546 rl_bind_key('\n', &CYConsoleKeyReturn);
547 }
548
549 mode_ = Parsing;
550 char *line(readline("cy# "));
551 mode_ = Working;
552
553 if (line == NULL) {
554 *out_ << std::endl;
555 break;
556 }
557
558 std::string command(line);
559 free(line);
560 _assert(!command.empty());
561 _assert(command[command.size() - 1] == '\n');
562 command.resize(command.size() - 1);
563 if (command.empty())
564 continue;
565
566 if (command[0] == '?') {
567 std::string data(command.substr(1));
568 if (data == "bypass") {
569 bypass = !bypass;
570 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
571 } else if (data == "debug") {
572 debug = !debug;
573 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
574 } else if (data == "destroy") {
575 CYDestroyContext();
576 } else if (data == "gc") {
577 *out_ << "collecting... " << std::flush;
578 CYGarbageCollect(CYGetJSContext());
579 *out_ << "done." << std::endl;
580 } else if (data == "exit") {
581 return;
582 } else if (data == "expand") {
583 expand = !expand;
584 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
585 } else if (data == "lower") {
586 lower = !lower;
587 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
588 }
589
590 history += command;
591 continue;
592 }
593
594 std::string code;
595 if (bypass)
596 code = command;
597 else {
598 std::istringstream stream(command);
599
600 CYPool pool;
601 CYDriver driver(pool, stream);
602 Setup(driver);
603
604 if (driver.Parse() || !driver.errors_.empty()) {
605 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
606 CYPosition begin(error->location_.begin);
607 CYPosition end(error->location_.end);
608
609 /*if (begin.line != lines2.size()) {
610 std::cerr << " | ";
611 std::cerr << lines2[begin.line - 1] << std::endl;
612 }*/
613
614 std::cerr << "....";
615 for (size_t i(0); i != begin.column; ++i)
616 std::cerr << '.';
617 if (begin.line != end.line || begin.column == end.column)
618 std::cerr << '^';
619 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
620 std::cerr << '^';
621 std::cerr << std::endl;
622
623 std::cerr << " | ";
624 std::cerr << error->message_ << std::endl;
625
626 history += command;
627 break;
628 }
629
630 continue;
631 }
632
633 if (driver.script_ == NULL)
634 continue;
635
636 std::stringbuf str;
637 CYOutput out(str, options);
638 Setup(out, driver, options, lower);
639 out << *driver.script_;
640 code = str.str();
641 }
642
643 history += command;
644
645 if (debug) {
646 std::cout << "cy= ";
647 CYLexerHighlight(code.c_str(), code.size(), std::cout);
648 std::cout << std::endl;
649 }
650
651 CYPool pool;
652 Output(Run(pool, client_, code), &std::cout, expand);
653 }
654 }
655
656 void InjectLibrary(pid_t, int, const char *const []);
657
658 static uint64_t CYGetTime() {
659 #ifdef __APPLE__
660 return mach_absolute_time();
661 #else
662 struct timespec spec;
663 clock_gettime(CLOCK_MONOTONIC, &spec);
664 return spec.tv_sec * UINT64_C(1000000000) + spec.tv_nsec;
665 #endif
666 }
667
668 int Main(int argc, char * const argv[], char const * const envp[]) {
669 bool tty(isatty(STDIN_FILENO));
670 bool compile(false);
671 bool target(false);
672 CYOptions options;
673
674 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
675
676 #ifdef CY_ATTACH
677 pid_t pid(_not(pid_t));
678 #endif
679
680 const char *host(NULL);
681 const char *port(NULL);
682
683 optind = 1;
684
685 for (;;) {
686 int option(getopt_long(argc, argv,
687 "c"
688 "g:"
689 "n:"
690 #ifdef CY_ATTACH
691 "p:"
692 #endif
693 "r:"
694 "s"
695 , (const struct option[]) {
696 {NULL, no_argument, NULL, 'c'},
697 {NULL, required_argument, NULL, 'g'},
698 {NULL, required_argument, NULL, 'n'},
699 #ifdef CY_ATTACH
700 {NULL, required_argument, NULL, 'p'},
701 #endif
702 {NULL, required_argument, NULL, 'r'},
703 {NULL, no_argument, NULL, 's'},
704 {0, 0, 0, 0}}, NULL));
705
706 switch (option) {
707 case -1:
708 goto getopt;
709
710 case ':':
711 case '?':
712 fprintf(stderr,
713 "usage: cycript [-c]"
714 #ifdef CY_ATTACH
715 " [-p <pid|name>]"
716 #endif
717 " [-r <host:port>]"
718 " [<script> [<arg>...]]\n"
719 );
720 return 1;
721
722 target:
723 if (!target)
724 target = true;
725 else {
726 fprintf(stderr, "only one of -[c"
727 #ifdef CY_ATTACH
728 "p"
729 #endif
730 "r] may be used at a time\n");
731 return 1;
732 }
733 break;
734
735 case 'c':
736 compile = true;
737 goto target;
738
739 case 'g':
740 if (false);
741 else if (strcmp(optarg, "rename") == 0)
742 options.verbose_ = true;
743 else if (strcmp(optarg, "bison") == 0)
744 bison_ = true;
745 else if (strcmp(optarg, "timing") == 0)
746 timing_ = true;
747 else {
748 fprintf(stderr, "invalid name for -g\n");
749 return 1;
750 }
751 break;
752
753 case 'n':
754 if (false);
755 else if (strcmp(optarg, "minify") == 0)
756 pretty_ = true;
757 else {
758 fprintf(stderr, "invalid name for -n\n");
759 return 1;
760 }
761 break;
762
763 #ifdef CY_ATTACH
764 case 'p': {
765 size_t size(strlen(optarg));
766 char *end;
767
768 pid = strtoul(optarg, &end, 0);
769 if (optarg + size != end) {
770 // XXX: arg needs to be escaped in some horrendous way of doom
771 // XXX: this is a memory leak now because I just don't care enough
772 char *command;
773 int writ(asprintf(&command, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg));
774 _assert(writ != -1);
775
776 if (FILE *pids = popen(command, "r")) {
777 char value[32];
778 size = 0;
779
780 for (;;) {
781 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
782 if (read == 0)
783 break;
784 else {
785 size += read;
786 if (size == sizeof(value))
787 goto fail;
788 }
789 }
790
791 size:
792 if (size == 0)
793 goto fail;
794 if (value[size - 1] == '\n') {
795 --size;
796 goto size;
797 }
798
799 value[size] = '\0';
800 size = strlen(value);
801 pid = strtoul(value, &end, 0);
802 if (value + size != end) fail:
803 pid = _not(pid_t);
804 _syscall(pclose(pids));
805 }
806
807 if (pid == _not(pid_t)) {
808 fprintf(stderr, "unable to find process `%s' using ps\n", optarg);
809 return 1;
810 }
811 }
812 } goto target;
813 #endif
814
815 case 'r': {
816 //size_t size(strlen(optarg));
817
818 char *colon(strrchr(optarg, ':'));
819 if (colon == NULL) {
820 fprintf(stderr, "missing colon in hostspec\n");
821 return 1;
822 }
823
824 /*char *end;
825 port = strtoul(colon + 1, &end, 10);
826 if (end != optarg + size) {
827 fprintf(stderr, "invalid port in hostspec\n");
828 return 1;
829 }*/
830
831 host = optarg;
832 *colon = '\0';
833 port = colon + 1;
834 } goto target;
835
836 case 's':
837 strict_ = true;
838 break;
839
840 default:
841 _assert(false);
842 }
843 }
844
845 getopt:
846 argc -= optind;
847 argv += optind;
848
849 const char *script;
850
851 #ifdef CY_ATTACH
852 if (pid != _not(pid_t) && argc > 1) {
853 fprintf(stderr, "-p cannot set argv\n");
854 return 1;
855 }
856 #endif
857
858 if (argc == 0)
859 script = NULL;
860 else {
861 #ifdef CY_EXECUTE
862 // XXX: const_cast?! wtf gcc :(
863 CYSetArgs(argc - 1, const_cast<const char **>(argv + 1));
864 #endif
865 script = argv[0];
866 if (strcmp(script, "-") == 0)
867 script = NULL;
868 }
869
870 #ifdef CY_ATTACH
871 if (pid == _not(pid_t))
872 client_ = -1;
873 else {
874 struct Socket {
875 int fd_;
876
877 Socket(int fd) :
878 fd_(fd)
879 {
880 }
881
882 ~Socket() {
883 close(fd_);
884 }
885
886 operator int() {
887 return fd_;
888 }
889 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
890
891 struct sockaddr_un address;
892 memset(&address, 0, sizeof(address));
893 address.sun_family = AF_UNIX;
894
895 const char *tmp;
896 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
897 tmp = "/Library/Caches";
898 #else
899 tmp = "/tmp";
900 #endif
901
902 sprintf(address.sun_path, "%s/.s.cy.%u", tmp, getpid());
903 unlink(address.sun_path);
904
905 struct File {
906 const char *path_;
907
908 File(const char *path) :
909 path_(path)
910 {
911 }
912
913 ~File() {
914 unlink(path_);
915 }
916 } file(address.sun_path);
917
918 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
919 _syscall(chmod(address.sun_path, 0777));
920
921 _syscall(listen(server, 1));
922 const char *const argv[] = {address.sun_path, NULL};
923 InjectLibrary(pid, 1, argv);
924 client_ = _syscall(accept(server, NULL, NULL));
925 }
926 #else
927 client_ = -1;
928 #endif
929
930 if (client_ == -1 && host != NULL && port != NULL) {
931 struct addrinfo hints;
932 memset(&hints, 0, sizeof(hints));
933 hints.ai_family = AF_UNSPEC;
934 hints.ai_socktype = SOCK_STREAM;
935 hints.ai_protocol = 0;
936 hints.ai_flags = 0;
937
938 struct addrinfo *infos;
939 _syscall(getaddrinfo(host, port, &hints, &infos));
940
941 _assert(infos != NULL); try {
942 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
943 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
944 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
945 client_ = client;
946 break;
947 } catch (...) {
948 _syscall(close(client));
949 throw;
950 }
951 }
952 } catch (...) {
953 freeaddrinfo(infos);
954 throw;
955 }
956 }
957
958 if (script == NULL && tty)
959 Console(options);
960 else {
961 std::istream *stream;
962 if (script == NULL) {
963 stream = &std::cin;
964 script = "<stdin>";
965 } else {
966 stream = new std::fstream(script, std::ios::in | std::ios::binary);
967 _assert(!stream->fail());
968 }
969
970 if (timing_) {
971 std::stringbuf buffer;
972 stream->get(buffer, '\0');
973 _assert(!stream->fail());
974
975 double average(0);
976 int samples(-50);
977 uint64_t start(CYGetTime());
978
979 for (;;) {
980 stream = new std::istringstream(buffer.str());
981
982 CYPool pool;
983 CYDriver driver(pool, *stream, script);
984 Setup(driver);
985
986 uint64_t begin(CYGetTime());
987 driver.Parse();
988 uint64_t end(CYGetTime());
989
990 delete stream;
991
992 average += (end - begin - average) / ++samples;
993
994 uint64_t now(CYGetTime());
995 if (samples == 0)
996 average = 0;
997 else if ((now - start) / 1000000000 >= 1)
998 std::cout << std::fixed << average << '\t' << (end - begin) << '\t' << samples << std::endl;
999 else continue;
1000
1001 start = now;
1002 }
1003
1004 stream = new std::istringstream(buffer.str());
1005 std::cin.get();
1006 }
1007
1008 CYPool pool;
1009 CYDriver driver(pool, *stream, script);
1010 Setup(driver);
1011
1012 bool failed(driver.Parse());
1013
1014 if (failed || !driver.errors_.empty()) {
1015 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
1016 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
1017 } else if (driver.script_ != NULL) {
1018 std::stringbuf str;
1019 CYOutput out(str, options);
1020 Setup(out, driver, options, true);
1021 out << *driver.script_;
1022 std::string code(str.str());
1023 if (compile)
1024 std::cout << code;
1025 else {
1026 CYUTF8String json(Run(pool, client_, code));
1027 if (CYStartsWith(json, "throw ")) {
1028 CYLexerHighlight(json.data, json.size, std::cerr);
1029 std::cerr << std::endl;
1030 return 1;
1031 }
1032 }
1033 }
1034 }
1035
1036 return 0;
1037 }
1038
1039 int main(int argc, char * const argv[], char const * const envp[]) {
1040 try {
1041 return Main(argc, argv, envp);
1042 } catch (const CYException &error) {
1043 CYPool pool;
1044 fprintf(stderr, "%s\n", error.PoolCString(pool));
1045 return 1;
1046 }
1047 }