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