]> git.saurik.com Git - cycript.git/blob - Console.cpp
Support 7a09b83's new boolean argument on startVm.
[cycript.git] / Console.cpp
1 /* Cycript - The Truly Universal Scripting Language
2 * Copyright (C) 2009-2016 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 "Code.hpp"
72 #include "Driver.hpp"
73 #include "Error.hpp"
74 #include "Highlight.hpp"
75 #include "Syntax.hpp"
76
77 extern "C" int rl_display_fixed;
78 extern "C" int _rl_vis_botlin;
79 extern "C" int _rl_last_c_pos;
80 extern "C" int _rl_last_v_pos;
81
82 typedef std::complex<int> CYCursor;
83
84 static CYCursor current_;
85 static int width_;
86 static size_t point_;
87
88 unsigned CYDisplayWidth() {
89 struct winsize info;
90 if (ioctl(1, TIOCGWINSZ, &info) != -1)
91 return info.ws_col;
92 return tgetnum(const_cast<char *>("co"));
93 }
94
95 void CYDisplayOutput_(bool display, const char *&data) {
96 for (;; ++data) {
97 char next(*data);
98 if (next == '\0' || next == CYIgnoreEnd)
99 return;
100 if (display)
101 putchar(next);
102 }
103 }
104
105 CYCursor CYDisplayOutput(bool display, int width, const char *data, ssize_t offset = 0) {
106 CYCursor point(current_);
107
108 for (;;) {
109 if (offset-- == 0)
110 point = current_;
111 switch (char next = *data++) {
112 case '\0':
113 return point;
114 break;
115
116 case CYIgnoreStart:
117 CYDisplayOutput_(display, data);
118 case CYIgnoreEnd:
119 ++offset;
120 break;
121
122 default:
123 if (display)
124 putchar(next);
125 current_ += CYCursor(0, 1);
126 if (current_.imag() != width)
127 break;
128 current_ = CYCursor(current_.real() + 1, 0);
129 if (display)
130 putp(clr_eos);
131 break;
132
133 case '\n':
134 current_ = CYCursor(current_.real() + 1, 4);
135 if (display) {
136 putp(clr_eol);
137 putchar('\n');
138 putchar(' ');
139 putchar(' ');
140 putchar(' ');
141 putchar(' ');
142 }
143 break;
144
145 }
146 }
147 }
148
149 void CYDisplayMove_(char *negative, char *positive, int offset) {
150 if (offset < 0)
151 putp(tparm(negative, -offset));
152 else if (offset > 0)
153 putp(tparm(positive, offset));
154 }
155
156 void CYDisplayMove(CYCursor target) {
157 CYCursor offset(target - current_);
158
159 CYDisplayMove_(parm_up_cursor, parm_down_cursor, offset.real());
160
161 if (char *parm = tparm(column_address, target.imag()))
162 putp(parm);
163 else
164 CYDisplayMove_(parm_left_cursor, parm_right_cursor, offset.imag());
165
166 current_ = target;
167 }
168
169 void CYDisplayUpdate() {
170 current_ = CYCursor(_rl_last_v_pos, _rl_last_c_pos);
171
172 const char *prompt(rl_display_prompt);
173
174 std::ostringstream stream;
175 CYLexerHighlight(rl_line_buffer, rl_end, stream, true);
176 std::string string(stream.str());
177 const char *buffer(string.c_str());
178
179 int width(CYDisplayWidth());
180 if (width_ != width) {
181 current_ = CYCursor();
182 CYDisplayOutput(false, width, prompt);
183 current_ = CYDisplayOutput(false, width, buffer, point_);
184 }
185
186 CYDisplayMove(CYCursor());
187 CYDisplayOutput(true, width, prompt);
188 CYCursor target(CYDisplayOutput(true, width, stream.str().c_str(), rl_point));
189
190 _rl_vis_botlin = current_.real();
191
192 if (current_.imag() == 0)
193 CYDisplayOutput(true, width, " ");
194 putp(clr_eos);
195
196 CYDisplayMove(target);
197 fflush(stdout);
198
199 _rl_last_v_pos = current_.real();
200 _rl_last_c_pos = current_.imag();
201
202 width_ = width;
203 point_ = rl_point;
204 }
205
206 static volatile enum {
207 Working,
208 Parsing,
209 Running,
210 Sending,
211 Waiting,
212 } mode_;
213
214 static jmp_buf ctrlc_;
215
216 static void sigint(int) {
217 switch (mode_) {
218 case Working:
219 return;
220 case Parsing:
221 longjmp(ctrlc_, 1);
222 case Running:
223 #ifndef __ANDROID__
224 CYCancel();
225 #endif
226 return;
227 case Sending:
228 return;
229 case Waiting:
230 return;
231 }
232 }
233
234 static bool bison_;
235 static bool timing_;
236 static bool strict_;
237 static bool pretty_;
238
239 void Setup(CYDriver &driver) {
240 if (bison_)
241 driver.debug_ = 1;
242 if (strict_)
243 driver.strict_ = true;
244 }
245
246 void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) {
247 out.pretty_ = pretty_;
248 if (lower)
249 driver.Replace(options);
250 }
251
252 static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
253 const char *json;
254 uint32_t size;
255
256 if (client == -1) {
257 mode_ = Running;
258 #ifdef CY_EXECUTE
259 json = CYExecute(CYGetJSContext(), pool, code);
260 #else
261 json = NULL;
262 #endif
263 mode_ = Working;
264 if (json == NULL)
265 size = 0;
266 else
267 size = strlen(json);
268 } else {
269 mode_ = Sending;
270 size = code.size;
271 _assert(CYSendAll(client, &size, sizeof(size)));
272 _assert(CYSendAll(client, code.data, code.size));
273 mode_ = Waiting;
274 _assert(CYRecvAll(client, &size, sizeof(size)));
275 if (size == _not(uint32_t)) {
276 size = 0;
277 json = NULL;
278 } else {
279 char *temp(new(pool) char[size + 1]);
280 _assert(CYRecvAll(client, temp, size));
281 temp[size] = '\0';
282 json = temp;
283 }
284 mode_ = Working;
285 }
286
287 return CYUTF8String(json, size);
288 }
289
290 static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
291 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
292 }
293
294 static std::ostream *out_;
295
296 static void Output(CYUTF8String json, std::ostream *out, bool reparse = false) {
297 CYPool pool;
298
299 if (reparse) do {
300 CYStream stream(json.data, json.data + json.size);
301 CYDriver driver(pool, stream);
302 if (driver.Parse(CYMarkExpression))
303 break;
304 std::stringbuf str;
305 CYOptions options;
306 CYOutput out(str, options);
307 out.pretty_ = true;
308 out << *driver.context_;
309 std::string data(str.str());
310 json = CYPoolUTF8String(pool, data);
311 if (json.size == 0)
312 json.data = NULL;
313 } while (false);
314
315 const char *data(json.data);
316 size_t size(json.size);
317
318 if (data == NULL || out == NULL)
319 return;
320
321 CYLexerHighlight(data, size, *out);
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() { try {
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 } catch (const CYException &error) {
377 CYPool pool;
378 std::cout << error.PoolCString(pool) << std::endl;
379 } }
380
381 void operator +=(std::string command) {
382 if (HIST_ENTRY *entry = history_get(where_history()))
383 if (command == entry->line)
384 return;
385 add_history(command.c_str());
386 ++histlines_;
387 }
388 };
389
390 template <typename Type_>
391 static Type_ *CYmemrchr(Type_ *data, Type_ value, size_t size) {
392 while (size != 0)
393 if (data[--size] == value)
394 return data + size;
395 return NULL;
396 }
397
398 static void _lblcall(int (*command)(int, int), int count, int key) {
399 int last(_rl_last_c_pos);
400 // rl_rubout crashes in _rl_erase_at_end_of_line if _rl_last_c_pos != 0
401 if (command == &rl_rubout)
402 _rl_last_c_pos = 0;
403 for (int i(0); i != count; ++i)
404 if (command(1, key) != 0)
405 _assert(false);
406 _rl_last_c_pos = last;
407 }
408
409 static int CYConsoleKeyReturn(int count, int key) {
410 if (rl_point != rl_end) {
411 if (memchr(rl_line_buffer, '\n', rl_end) == NULL) {
412 _lblcall(&rl_newline, count, key);
413 return 0;
414 }
415
416 insert:
417 char *before(CYmemrchr(rl_line_buffer, '\n', rl_point));
418 if (before == NULL)
419 before = rl_line_buffer;
420
421 int space(before + 1 - rl_line_buffer);
422 while (space != rl_point && rl_line_buffer[space] == ' ')
423 ++space;
424
425 int adjust(rl_line_buffer + space - 1 - before);
426 if (space == rl_point && adjust != 0)
427 _lblcall(&rl_rubout, adjust, '\b');
428
429 _lblcall(&rl_insert, count, '\n');
430 if (adjust != 0)
431 _lblcall(&rl_insert, adjust, ' ');
432
433 return 0;
434 }
435
436 bool done(false);
437 if (rl_line_buffer[0] == '?')
438 done = true;
439 else {
440 std::string command(rl_line_buffer, rl_end);
441 command += '\n';
442 std::stringbuf stream(command);
443
444 size_t last(std::string::npos);
445 for (size_t i(0); i != std::string::npos; i = command.find('\n', i + 1))
446 ++last;
447
448 CYPool pool;
449 CYDriver driver(pool, stream);
450 if (driver.Parse() || !driver.errors_.empty())
451 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
452 if (error->location_.begin.line != last + 1)
453 done = true;
454 break;
455 }
456 else
457 done = true;
458 }
459
460 if (done) {
461 _lblcall(&rl_newline, count, key);
462 return 0;
463 }
464
465 // XXX: this was the most obvious fix, but is seriously dumb
466 goto insert;
467 }
468
469 static int CYConsoleKeyUp(int count, int key) {
470 for (; count != 0; --count) {
471 char *after(CYmemrchr(rl_line_buffer, '\n', rl_point));
472 if (after == NULL) {
473 if (int value = rl_get_previous_history(1, key))
474 return value;
475 continue;
476 }
477
478 char *before(CYmemrchr(rl_line_buffer, '\n', after - rl_line_buffer));
479 if (before == NULL)
480 before = rl_line_buffer - 1;
481
482 ptrdiff_t offset(rl_line_buffer + rl_point - after);
483 if (offset > after - before)
484 rl_point = after - rl_line_buffer;
485 else
486 rl_point = before + offset - rl_line_buffer;
487 }
488
489 return 0;
490 }
491
492 static int CYConsoleKeyDown(int count, int key) {
493 for (; count != 0; --count) {
494 char *after(static_cast<char *>(memchr(rl_line_buffer + rl_point, '\n', rl_end - rl_point)));
495 if (after == NULL) {
496 int where(where_history());
497 if (int value = rl_get_next_history(1, key))
498 return value;
499 if (where != where_history()) {
500 char *first(static_cast<char *>(memchr(rl_line_buffer, '\n', rl_end)));
501 if (first != NULL)
502 rl_point = first - 1 - rl_line_buffer;
503 }
504 continue;
505 }
506
507 char *before(CYmemrchr(rl_line_buffer, '\n', rl_point));
508 if (before == NULL)
509 before = rl_line_buffer - 1;
510
511 char *next(static_cast<char *>(memchr(after + 1, '\n', rl_line_buffer + rl_end - after - 1)));
512 if (next == NULL)
513 next = rl_line_buffer + rl_end;
514
515 ptrdiff_t offset(rl_line_buffer + rl_point - before);
516 if (offset > next - after)
517 rl_point = next - rl_line_buffer;
518 else
519 rl_point = after + offset - rl_line_buffer;
520 }
521
522 return 0;
523 }
524
525 static int CYConsoleLineBegin(int count, int key) {
526 while (rl_point != 0 && rl_line_buffer[rl_point - 1] != '\n')
527 --rl_point;
528 return 0;
529 }
530
531 static int CYConsoleLineEnd(int count, int key) {
532 while (rl_point != rl_end && rl_line_buffer[rl_point] != '\n')
533 ++rl_point;
534 if (rl_point != rl_end && rl_editing_mode == 0)
535 --rl_point;
536 return 0;
537 }
538
539 static int CYConsoleKeyBack(int count, int key) {
540 for (; count != 0; --count) {
541 if (rl_point == 0)
542 return 1;
543
544 char *before(CYmemrchr(rl_line_buffer, '\n', rl_point));
545 if (before == NULL) {
546 int adjust(std::min(count, rl_point));
547 _lblcall(&rl_rubout, adjust, key);
548 count -= adjust - 1;
549 continue;
550 }
551
552 int start(before + 1 - rl_line_buffer);
553 if (start == rl_point) rubout: {
554 _lblcall(&rl_rubout, 1, key);
555 continue;
556 }
557
558 for (int i(start); i != rl_point; ++i)
559 if (rl_line_buffer[i] != ' ')
560 goto rubout;
561 _lblcall(&rl_rubout, (rl_point - start) % 4 ?: 4, key);
562 }
563
564 return 0;
565 }
566
567 static int CYConsoleKeyTab(int count, int key) {
568 char *before(CYmemrchr(rl_line_buffer, '\n', rl_point));
569 if (before == NULL) complete:
570 return rl_complete_internal(rl_completion_mode(&CYConsoleKeyTab));
571 int start(before + 1 - rl_line_buffer);
572 for (int i(start); i != rl_point; ++i)
573 if (rl_line_buffer[i] != ' ')
574 goto complete;
575 _lblcall(&rl_insert, 4 - (rl_point - start) % 4, ' ');
576 return 0;
577 }
578
579 static void CYConsoleRemapBind(Keymap map, rl_command_func_t *from, rl_command_func_t *to) {
580 char **keyseqs(rl_invoking_keyseqs_in_map(from, map));
581 if (keyseqs == NULL)
582 return;
583 for (char **keyseq(keyseqs); *keyseq != NULL; ++keyseq) {
584 rl_bind_keyseq_in_map(*keyseq, to, map);
585 free(*keyseq);
586 }
587 free(keyseqs);
588 }
589
590 static void CYConsoleRemapKeys(Keymap map) {
591 CYConsoleRemapBind(map, &rl_beg_of_line, &CYConsoleLineBegin);
592 CYConsoleRemapBind(map, &rl_end_of_line, &CYConsoleLineEnd);
593
594 CYConsoleRemapBind(map, &rl_get_previous_history, &CYConsoleKeyUp);
595 CYConsoleRemapBind(map, &rl_get_next_history, &CYConsoleKeyDown);
596
597 CYConsoleRemapBind(map, &rl_rubout, &CYConsoleKeyBack);
598 CYConsoleRemapBind(map, &rl_complete, &CYConsoleKeyTab);
599 }
600
601 static void CYConsolePrepTerm(int meta) {
602 rl_prep_terminal(meta);
603
604 CYConsoleRemapKeys(emacs_standard_keymap);
605 CYConsoleRemapKeys(emacs_meta_keymap);
606 CYConsoleRemapKeys(emacs_ctlx_keymap);
607 CYConsoleRemapKeys(vi_insertion_keymap);
608 CYConsoleRemapKeys(vi_movement_keymap);
609 }
610
611 static void CYOutputRun(const std::string &code, bool reparse = false) {
612 CYPool pool;
613 Output(Run(pool, client_, code), &std::cout, reparse);
614 }
615
616 static void Console(CYOptions &options) {
617 std::string basedir;
618 #ifdef __ANDROID__
619 basedir = "/data/local/tmp";
620 #else
621 if (const char *home = getenv("HOME"))
622 basedir = home;
623 else {
624 passwd *passwd;
625 if (const char *username = getenv("LOGNAME"))
626 passwd = getpwnam(username);
627 else
628 passwd = getpwuid(getuid());
629 basedir = passwd->pw_dir;
630 }
631 #endif
632
633 basedir += "/.cycript";
634 mkdir(basedir.c_str(), 0700);
635
636 rl_initialize();
637 rl_readline_name = name_;
638
639 History history(basedir + "/history");
640
641 bool bypass(false);
642 bool debug(false);
643 bool lower(true);
644 bool reparse(false);
645
646 out_ = &std::cout;
647
648 rl_completer_word_break_characters = break_;
649 rl_attempted_completion_function = &Complete;
650
651 if (cur_term != NULL) {
652 rl_redisplay_function = CYDisplayUpdate;
653 rl_prep_term_function = CYConsolePrepTerm;
654 }
655
656 CYOutputRun("");
657
658 for (;;) {
659 struct sigaction action;
660 sigemptyset(&action.sa_mask);
661 action.sa_handler = &sigint;
662 action.sa_flags = 0;
663 sigaction(SIGINT, &action, NULL);
664
665 if (setjmp(ctrlc_) != 0) {
666 mode_ = Working;
667 *out_ << std::endl;
668 continue;
669 }
670
671 if (bypass) {
672 rl_bind_key('\r', &rl_newline);
673 rl_bind_key('\n', &rl_newline);
674 } else {
675 rl_bind_key('\r', &CYConsoleKeyReturn);
676 rl_bind_key('\n', &CYConsoleKeyReturn);
677 }
678
679 mode_ = Parsing;
680 char *line(readline("cy# "));
681 mode_ = Working;
682
683 if (line == NULL) {
684 *out_ << std::endl;
685 break;
686 }
687
688 std::string command(line);
689 free(line);
690 if (command.empty())
691 continue;
692 history += command;
693
694 if (command[0] == '?') {
695 std::string data(command.substr(1));
696 if (data == "bypass") {
697 bypass = !bypass;
698 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
699 } else if (data == "debug") {
700 debug = !debug;
701 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
702 } else if (data == "destroy") {
703 CYDestroyContext();
704 } else if (data == "gc") {
705 *out_ << "collecting... " << std::flush;
706 CYGarbageCollect(CYGetJSContext());
707 *out_ << "done." << std::endl;
708 } else if (data == "exit") {
709 return;
710 } else if (data == "lower") {
711 lower = !lower;
712 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
713 } else if (data == "reparse") {
714 reparse = !reparse;
715 *out_ << "reparse == " << (reparse ? "true" : "false") << std::endl;
716 }
717
718 continue;
719 }
720
721 std::string code;
722 if (bypass)
723 code = command;
724 else try {
725 std::stringbuf stream(command);
726
727 CYPool pool;
728 CYDriver driver(pool, stream);
729 Setup(driver);
730
731 if (driver.Parse() || !driver.errors_.empty()) {
732 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
733 CYPosition begin(error->location_.begin);
734 CYPosition end(error->location_.end);
735
736 /*if (begin.line != lines2.size()) {
737 std::cerr << " | ";
738 std::cerr << lines2[begin.line - 1] << std::endl;
739 }*/
740
741 std::cerr << "....";
742 for (size_t i(0); i != begin.column; ++i)
743 std::cerr << '.';
744 if (begin.line != end.line || begin.column == end.column)
745 std::cerr << '^';
746 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
747 std::cerr << '^';
748 std::cerr << std::endl;
749
750 std::cerr << " | ";
751 std::cerr << error->message_ << std::endl;
752
753 break;
754 }
755
756 continue;
757 }
758
759 if (driver.script_ == NULL)
760 continue;
761
762 std::stringbuf str;
763 CYOutput out(str, options);
764 Setup(out, driver, options, lower);
765 out << *driver.script_;
766 code = str.str();
767 } catch (const CYException &error) {
768 CYPool pool;
769 std::cout << error.PoolCString(pool) << std::endl;
770 continue;
771 }
772
773 if (debug) {
774 std::cout << "cy= ";
775 CYLexerHighlight(code.c_str(), code.size(), std::cout);
776 std::cout << std::endl;
777 }
778
779 CYOutputRun(code, reparse);
780 }
781 }
782
783 void InjectLibrary(pid_t, int, const char *const []);
784
785 static uint64_t CYGetTime() {
786 #ifdef __APPLE__
787 return mach_absolute_time();
788 #else
789 struct timespec spec;
790 clock_gettime(CLOCK_MONOTONIC, &spec);
791 return spec.tv_sec * UINT64_C(1000000000) + spec.tv_nsec;
792 #endif
793 }
794
795 int Main(int argc, char * const argv[], char const * const envp[]) {
796 bool tty(isatty(STDIN_FILENO));
797 bool compile(false);
798 bool target(false);
799 CYOptions options;
800
801 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
802
803 #ifdef CY_ATTACH
804 pid_t pid(_not(pid_t));
805 #endif
806
807 const char *host(NULL);
808 const char *port(NULL);
809
810 const char *argv0(argv[0]);
811
812 optind = 1;
813
814 for (;;) {
815 int option(getopt_long(argc, argv,
816 "c"
817 "g:"
818 "n:"
819 #ifdef CY_ATTACH
820 "p:"
821 #endif
822 "r:"
823 "s"
824 , (const struct option[]) {
825 {NULL, no_argument, NULL, 'c'},
826 {NULL, required_argument, NULL, 'g'},
827 {NULL, required_argument, NULL, 'n'},
828 #ifdef CY_ATTACH
829 {NULL, required_argument, NULL, 'p'},
830 #endif
831 {NULL, required_argument, NULL, 'r'},
832 {NULL, no_argument, NULL, 's'},
833 {0, 0, 0, 0}}, NULL));
834
835 switch (option) {
836 case -1:
837 goto getopt;
838
839 case ':':
840 case '?':
841 fprintf(stderr,
842 "usage: cycript [-c]"
843 #ifdef CY_ATTACH
844 " [-p <pid|name>]"
845 #endif
846 " [-r <host:port>]"
847 " [<script> [<arg>...]]\n"
848 );
849 return 1;
850
851 target:
852 if (!target)
853 target = true;
854 else {
855 fprintf(stderr, "only one of -[c"
856 #ifdef CY_ATTACH
857 "p"
858 #endif
859 "r] may be used at a time\n");
860 return 1;
861 }
862 break;
863
864 case 'c':
865 compile = true;
866 goto target;
867
868 case 'g':
869 if (false);
870 else if (strcmp(optarg, "rename") == 0)
871 options.verbose_ = true;
872 else if (strcmp(optarg, "bison") == 0)
873 bison_ = true;
874 else if (strcmp(optarg, "timing") == 0)
875 timing_ = true;
876 else {
877 fprintf(stderr, "invalid name for -g\n");
878 return 1;
879 }
880 break;
881
882 case 'n':
883 if (false);
884 else if (strcmp(optarg, "minify") == 0)
885 pretty_ = true;
886 else {
887 fprintf(stderr, "invalid name for -n\n");
888 return 1;
889 }
890 break;
891
892 #ifdef CY_ATTACH
893 case 'p': {
894 size_t size(strlen(optarg));
895 char *end;
896
897 pid = strtoul(optarg, &end, 0);
898 if (optarg + size != end) {
899 // XXX: arg needs to be escaped in some horrendous way of doom
900 // XXX: this is a memory leak now because I just don't care enough
901 char *command;
902 int writ(asprintf(&command, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg));
903 _assert(writ != -1);
904
905 if (FILE *pids = popen(command, "r")) {
906 char value[32];
907 size = 0;
908
909 for (;;) {
910 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
911 if (read == 0)
912 break;
913 else {
914 size += read;
915 if (size == sizeof(value))
916 goto fail;
917 }
918 }
919
920 size:
921 if (size == 0)
922 goto fail;
923 if (value[size - 1] == '\n') {
924 --size;
925 goto size;
926 }
927
928 value[size] = '\0';
929 size = strlen(value);
930 pid = strtoul(value, &end, 0);
931 if (value + size != end) fail:
932 pid = _not(pid_t);
933 _syscall(pclose(pids));
934 }
935
936 if (pid == _not(pid_t)) {
937 fprintf(stderr, "unable to find process `%s' using ps\n", optarg);
938 return 1;
939 }
940 }
941 } goto target;
942 #endif
943
944 case 'r': {
945 //size_t size(strlen(optarg));
946
947 char *colon(strrchr(optarg, ':'));
948 if (colon == NULL) {
949 fprintf(stderr, "missing colon in hostspec\n");
950 return 1;
951 }
952
953 /*char *end;
954 port = strtoul(colon + 1, &end, 10);
955 if (end != optarg + size) {
956 fprintf(stderr, "invalid port in hostspec\n");
957 return 1;
958 }*/
959
960 host = optarg;
961 *colon = '\0';
962 port = colon + 1;
963 } goto target;
964
965 case 's':
966 strict_ = true;
967 break;
968
969 default:
970 _assert(false);
971 }
972 }
973
974 getopt:
975 argc -= optind;
976 argv += optind;
977
978 const char *script;
979
980 #ifdef CY_ATTACH
981 if (pid != _not(pid_t) && argc > 1) {
982 fprintf(stderr, "-p cannot set argv\n");
983 return 1;
984 }
985 #endif
986
987 if (argc == 0)
988 script = NULL;
989 else {
990 script = argv[0];
991 if (strcmp(script, "-") == 0)
992 script = NULL;
993 --argc;
994 ++argv;
995 }
996
997 #ifdef CY_EXECUTE
998 // XXX: const_cast?! wtf gcc :(
999 CYSetArgs(argv0, script, argc, const_cast<const char **>(argv));
1000 #endif
1001
1002 #ifdef CY_ATTACH
1003 if (pid == _not(pid_t))
1004 client_ = -1;
1005 else {
1006 struct Socket {
1007 int fd_;
1008
1009 Socket(int fd) :
1010 fd_(fd)
1011 {
1012 }
1013
1014 ~Socket() {
1015 close(fd_);
1016 }
1017
1018 operator int() {
1019 return fd_;
1020 }
1021 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
1022
1023 struct sockaddr_un address;
1024 memset(&address, 0, sizeof(address));
1025 address.sun_family = AF_UNIX;
1026
1027 const char *tmp;
1028 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
1029 tmp = "/Library/Caches";
1030 #else
1031 tmp = "/tmp";
1032 #endif
1033
1034 sprintf(address.sun_path, "%s/.s.cy.%u", tmp, getpid());
1035 unlink(address.sun_path);
1036
1037 struct File {
1038 const char *path_;
1039
1040 File(const char *path) :
1041 path_(path)
1042 {
1043 }
1044
1045 ~File() {
1046 unlink(path_);
1047 }
1048 } file(address.sun_path);
1049
1050 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), sizeof(address)));
1051 _syscall(chmod(address.sun_path, 0777));
1052
1053 _syscall(listen(server, 1));
1054 const char *const argv[] = {address.sun_path, NULL};
1055 InjectLibrary(pid, 1, argv);
1056 client_ = _syscall(accept(server, NULL, NULL));
1057 }
1058 #else
1059 client_ = -1;
1060 #endif
1061
1062 if (client_ == -1 && host != NULL && port != NULL) {
1063 struct addrinfo hints;
1064 memset(&hints, 0, sizeof(hints));
1065 hints.ai_family = AF_UNSPEC;
1066 hints.ai_socktype = SOCK_STREAM;
1067 hints.ai_protocol = 0;
1068 hints.ai_flags = 0;
1069
1070 struct addrinfo *infos;
1071 _syscall(getaddrinfo(host, port, &hints, &infos));
1072
1073 _assert(infos != NULL); try {
1074 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
1075 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
1076 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
1077 client_ = client;
1078 break;
1079 } catch (...) {
1080 _syscall(close(client));
1081 throw;
1082 }
1083 }
1084 } catch (...) {
1085 freeaddrinfo(infos);
1086 throw;
1087 }
1088 }
1089
1090 if (script == NULL && tty)
1091 Console(options);
1092 else {
1093 std::istream *stream;
1094 if (script == NULL) {
1095 stream = &std::cin;
1096 script = "<stdin>";
1097 } else {
1098 stream = new std::fstream(script, std::ios::in | std::ios::binary);
1099 _assert(!stream->fail());
1100 }
1101
1102 if (timing_) {
1103 std::stringbuf buffer;
1104 stream->get(buffer, '\0');
1105 _assert(!stream->fail());
1106
1107 double average(0);
1108 int samples(-50);
1109 uint64_t start(CYGetTime());
1110
1111 for (;;) {
1112 stream = new std::istringstream(buffer.str());
1113
1114 CYPool pool;
1115 CYDriver driver(pool, *stream->rdbuf(), script);
1116 Setup(driver);
1117
1118 uint64_t begin(CYGetTime());
1119 driver.Parse();
1120 uint64_t end(CYGetTime());
1121
1122 delete stream;
1123
1124 average += (end - begin - average) / ++samples;
1125
1126 uint64_t now(CYGetTime());
1127 if (samples == 0)
1128 average = 0;
1129 else if ((now - start) / 1000000000 >= 1)
1130 std::cout << std::fixed << average << '\t' << (end - begin) << '\t' << samples << std::endl;
1131 else continue;
1132
1133 start = now;
1134 }
1135
1136 stream = new std::istringstream(buffer.str());
1137 std::cin.get();
1138 }
1139
1140 CYPool pool;
1141 CYDriver driver(pool, *stream->rdbuf(), script);
1142 Setup(driver);
1143
1144 bool failed(driver.Parse());
1145
1146 if (failed || !driver.errors_.empty()) {
1147 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
1148 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
1149 return 1;
1150 } else if (driver.script_ != NULL) {
1151 std::stringbuf str;
1152 CYOutput out(str, options);
1153 Setup(out, driver, options, true);
1154 out << *driver.script_;
1155 std::string code(str.str());
1156 if (compile)
1157 std::cout << code;
1158 else {
1159 CYUTF8String json(Run(pool, client_, code));
1160 if (CYStartsWith(json, "throw ")) {
1161 CYLexerHighlight(json.data, json.size, std::cerr);
1162 std::cerr << std::endl;
1163 return 1;
1164 }
1165 }
1166 }
1167 }
1168
1169 return 0;
1170 }
1171
1172 _visible int main(int argc, char * const argv[], char const * const envp[]) {
1173 try {
1174 return Main(argc, argv, envp);
1175 } catch (const CYException &error) {
1176 CYPool pool;
1177 fprintf(stderr, "%s\n", error.PoolCString(pool));
1178 return 1;
1179 }
1180 }