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