1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2015 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
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.
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.
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/>.
22 #include "cycript.hpp"
25 #include "JavaScript.hpp"
33 #ifdef HAVE_READLINE_H
36 #include <readline/readline.h>
42 #include <readline/history.h>
51 #include <sys/socket.h>
52 #include <sys/types.h>
57 #include <sys/ioctl.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
68 #include <mach/mach_time.h>
73 #include "Highlight.hpp"
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
;
81 typedef std::complex<int> CYCursor
;
83 static CYCursor current_
;
87 unsigned CYDisplayWidth() {
89 if (ioctl(1, TIOCGWINSZ
, &info
) != -1)
91 return tgetnum(const_cast<char *>("co"));
94 void CYDisplayOutput_(bool display
, const char *&data
) {
97 if (next
== '\0' || next
== CYIgnoreEnd
)
104 CYCursor
CYDisplayOutput(bool display
, int width
, const char *data
, ssize_t offset
= 0) {
105 CYCursor
point(current_
);
110 switch (char next
= *data
++) {
116 CYDisplayOutput_(display
, data
);
124 current_
+= CYCursor(0, 1);
125 if (current_
.imag() != width
)
127 current_
= CYCursor(current_
.real() + 1, 0);
133 current_
= CYCursor(current_
.real() + 1, 4);
148 void CYDisplayMove_(char *negative
, char *positive
, int offset
) {
150 putp(tparm(negative
, -offset
));
152 putp(tparm(positive
, offset
));
155 void CYDisplayMove(CYCursor target
) {
156 CYCursor
offset(target
- current_
);
158 CYDisplayMove_(parm_up_cursor
, parm_down_cursor
, offset
.real());
160 if (char *parm
= tparm(column_address
, target
.imag()))
163 CYDisplayMove_(parm_left_cursor
, parm_right_cursor
, offset
.imag());
168 void CYDisplayUpdate() {
169 current_
= CYCursor(_rl_last_v_pos
, _rl_last_c_pos
);
171 const char *prompt(rl_display_prompt
);
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());
178 int width(CYDisplayWidth());
179 if (width_
!= width
) {
180 current_
= CYCursor();
181 CYDisplayOutput(false, width
, prompt
);
182 current_
= CYDisplayOutput(false, width
, buffer
, point_
);
185 CYDisplayMove(CYCursor());
186 CYDisplayOutput(true, width
, prompt
);
187 CYCursor
target(CYDisplayOutput(true, width
, stream
.str().c_str(), rl_point
));
189 _rl_vis_botlin
= current_
.real();
191 if (current_
.imag() == 0)
192 CYDisplayOutput(true, width
, " ");
195 CYDisplayMove(target
);
198 _rl_last_v_pos
= current_
.real();
199 _rl_last_c_pos
= current_
.imag();
205 static volatile enum {
213 static jmp_buf ctrlc_
;
215 static void sigint(int) {
236 void Setup(CYDriver
&driver
) {
240 driver
.strict_
= true;
243 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
, bool lower
) {
244 out
.pretty_
= pretty_
;
246 driver
.Replace(options
);
249 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
256 json
= CYExecute(CYGetJSContext(), pool
, code
);
268 _assert(CYSendAll(client
, &size
, sizeof(size
)));
269 _assert(CYSendAll(client
, code
.data
, code
.size
));
271 _assert(CYRecvAll(client
, &size
, sizeof(size
)));
272 if (size
== _not(uint32_t))
275 char *temp(new(pool
) char[size
+ 1]);
276 _assert(CYRecvAll(client
, temp
, size
));
283 return CYUTF8String(json
, size
);
286 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
287 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
290 static std::ostream
*out_
;
292 static void Output(CYUTF8String json
, std::ostream
*out
, bool expand
= false) {
293 const char *data(json
.data
);
294 size_t size(json
.size
);
296 if (data
== NULL
|| out
== NULL
)
300 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
301 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
303 CYLexerHighlight(data
, size
, *out
);
304 else for (size_t i(0); i
!= size
; ++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;
325 int (*append_history$
)(int, const char *);
327 static std::string command_
;
331 static CYUTF8String
Run(CYPool
&pool
, const std::string
&code
) {
332 return Run(pool
, client_
, code
);
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
));
343 // need char *, not const char *
344 static char name_
[] = "cycript";
345 static char break_
[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]";
349 std::string histfile_
;
353 History(std::string histfile
) :
357 read_history(histfile_
.c_str());
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';
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';
369 if (append_history$
!= NULL
) {
370 int fd(_syscall(open(histfile_
.c_str(), O_CREAT
| O_WRONLY
, 0600)));
372 _assert((*append_history$
)(histlines_
, histfile_
.c_str()) == 0);
374 _assert(write_history(histfile_
.c_str()) == 0);
378 void operator +=(std::string command
) {
379 add_history(command
.c_str());
384 template <typename Type_
>
385 static Type_
*CYmemrchr(Type_
*data
, Type_ value
, size_t size
) {
387 if (data
[--size
] == value
)
392 static int CYConsoleKeyReturn(int count
, int key
) {
393 if (rl_point
!= rl_end
) {
394 if (memchr(rl_line_buffer
, '\n', rl_end
) == NULL
)
395 return rl_newline(count
, key
);
397 char *before(CYmemrchr(rl_line_buffer
, '\n', rl_point
));
399 before
= rl_line_buffer
;
401 int space(before
+ 1 - rl_line_buffer
);
402 while (space
!= rl_point
&& rl_line_buffer
[space
] == ' ')
405 int adjust(rl_line_buffer
+ space
- 1 - before
);
406 if (space
== rl_point
&& adjust
!= 0)
407 rl_rubout(adjust
, '\b');
409 rl_insert(count
, '\n');
411 rl_insert(adjust
, ' ');
417 if (rl_line_buffer
[0] == '?')
420 std::string
command(rl_line_buffer
, rl_end
);
422 std::istringstream
stream(command
);
424 size_t last(std::string::npos
);
425 for (size_t i(0); i
!= std::string::npos
; i
= command
.find('\n', i
+ 1))
429 CYDriver
driver(pool
, stream
);
430 if (driver
.Parse() || !driver
.errors_
.empty())
431 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
432 if (error
->location_
.begin
.line
!= last
+ 1)
441 return rl_newline(count
, key
);
443 rl_insert(count
, '\n');
447 static int CYConsoleKeyUp(int count
, int key
) {
448 while (count
-- != 0) {
449 char *after(CYmemrchr(rl_line_buffer
, '\n', rl_point
));
451 if (int value
= rl_get_previous_history(1, key
))
456 char *before(CYmemrchr(rl_line_buffer
, '\n', after
- rl_line_buffer
));
458 before
= rl_line_buffer
- 1;
460 ptrdiff_t offset(rl_line_buffer
+ rl_point
- after
);
461 if (offset
> after
- before
)
462 rl_point
= after
- rl_line_buffer
;
464 rl_point
= before
+ offset
- rl_line_buffer
;
470 static int CYConsoleKeyDown(int count
, int key
) {
471 while (count
-- != 0) {
472 char *after(static_cast<char *>(memchr(rl_line_buffer
+ rl_point
, '\n', rl_end
- rl_point
)));
474 int where(where_history());
475 if (int value
= rl_get_next_history(1, key
))
477 if (where
!= where_history()) {
478 char *first(static_cast<char *>(memchr(rl_line_buffer
, '\n', rl_end
)));
480 rl_point
= first
- 1 - rl_line_buffer
;
485 char *before(CYmemrchr(rl_line_buffer
, '\n', rl_point
));
487 before
= rl_line_buffer
- 1;
489 char *next(static_cast<char *>(memchr(after
+ 1, '\n', rl_line_buffer
+ rl_end
- after
- 1)));
491 next
= rl_line_buffer
+ rl_end
;
493 ptrdiff_t offset(rl_line_buffer
+ rl_point
- before
);
494 if (offset
> next
- after
)
495 rl_point
= next
- rl_line_buffer
;
497 rl_point
= after
+ offset
- rl_line_buffer
;
503 static int CYConsoleLineBegin(int count
, int key
) {
504 while (rl_point
!= 0 && rl_line_buffer
[rl_point
- 1] != '\n')
509 static int CYConsoleLineEnd(int count
, int key
) {
510 while (rl_point
!= rl_end
&& rl_line_buffer
[rl_point
] != '\n')
512 if (rl_point
!= rl_end
&& rl_editing_mode
== 0)
517 static int CYConsoleKeyBack(int count
, int key
) {
518 while (count
-- != 0) {
519 char *before(CYmemrchr(rl_line_buffer
, '\n', rl_point
));
521 return rl_rubout(count
, key
);
523 int start(before
+ 1 - rl_line_buffer
);
524 if (start
== rl_point
) rubout
: {
529 for (int i(start
); i
!= rl_point
; ++i
)
530 if (rl_line_buffer
[i
] != ' ')
532 rl_rubout((rl_point
- start
) % 4 ?: 4, key
);
538 static int CYConsoleKeyTab(int count
, int key
) {
539 char *before(CYmemrchr(rl_line_buffer
, '\n', rl_point
));
540 if (before
== NULL
) complete
:
541 return rl_complete_internal(rl_completion_mode(&CYConsoleKeyTab
));
542 int start(before
+ 1 - rl_line_buffer
);
543 for (int i(start
); i
!= rl_point
; ++i
)
544 if (rl_line_buffer
[i
] != ' ')
546 return rl_insert(4 - (rl_point
- start
) % 4, ' ');
549 static void CYConsoleRemapBind(Keymap map
, rl_command_func_t
*from
, rl_command_func_t
*to
) {
550 char **keyseqs(rl_invoking_keyseqs_in_map(from
, map
));
553 for (char **keyseq(keyseqs
); *keyseq
!= NULL
; ++keyseq
) {
554 rl_bind_keyseq_in_map(*keyseq
, to
, map
);
560 static void CYConsoleRemapKeys(Keymap map
) {
561 CYConsoleRemapBind(map
, &rl_beg_of_line
, &CYConsoleLineBegin
);
562 CYConsoleRemapBind(map
, &rl_end_of_line
, &CYConsoleLineEnd
);
564 CYConsoleRemapBind(map
, &rl_get_previous_history
, &CYConsoleKeyUp
);
565 CYConsoleRemapBind(map
, &rl_get_next_history
, &CYConsoleKeyDown
);
567 CYConsoleRemapBind(map
, &rl_rubout
, &CYConsoleKeyBack
);
568 CYConsoleRemapBind(map
, &rl_complete
, &CYConsoleKeyTab
);
571 static void CYConsolePrepTerm(int meta
) {
572 rl_prep_terminal(meta
);
574 CYConsoleRemapKeys(emacs_standard_keymap
);
575 CYConsoleRemapKeys(emacs_meta_keymap
);
576 CYConsoleRemapKeys(emacs_ctlx_keymap
);
577 CYConsoleRemapKeys(vi_insertion_keymap
);
578 CYConsoleRemapKeys(vi_movement_keymap
);
581 static void Console(CYOptions
&options
) {
583 if (const char *home
= getenv("HOME"))
587 if (const char *username
= getenv("LOGNAME"))
588 passwd
= getpwnam(username
);
590 passwd
= getpwuid(getuid());
591 basedir
= passwd
->pw_dir
;
594 basedir
+= "/.cycript";
595 mkdir(basedir
.c_str(), 0700);
598 rl_readline_name
= name_
;
600 History
history(basedir
+ "/history");
609 rl_completer_word_break_characters
= break_
;
610 rl_attempted_completion_function
= &Complete
;
612 rl_redisplay_function
= CYDisplayUpdate
;
613 rl_prep_term_function
= CYConsolePrepTerm
;
615 struct sigaction action
;
616 sigemptyset(&action
.sa_mask
);
617 action
.sa_handler
= &sigint
;
619 sigaction(SIGINT
, &action
, NULL
);
622 if (setjmp(ctrlc_
) != 0) {
629 rl_bind_key('\r', &rl_newline
);
630 rl_bind_key('\n', &rl_newline
);
632 rl_bind_key('\r', &CYConsoleKeyReturn
);
633 rl_bind_key('\n', &CYConsoleKeyReturn
);
637 char *line(readline("cy# "));
645 std::string
command(line
);
650 if (command
[0] == '?') {
651 std::string
data(command
.substr(1));
652 if (data
== "bypass") {
654 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
655 } else if (data
== "debug") {
657 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
658 } else if (data
== "destroy") {
660 } else if (data
== "gc") {
661 *out_
<< "collecting... " << std::flush
;
662 CYGarbageCollect(CYGetJSContext());
663 *out_
<< "done." << std::endl
;
664 } else if (data
== "exit") {
666 } else if (data
== "expand") {
668 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
669 } else if (data
== "lower") {
671 *out_
<< "lower == " << (lower
? "true" : "false") << std::endl
;
682 std::istringstream
stream(command
);
685 CYDriver
driver(pool
, stream
);
688 if (driver
.Parse() || !driver
.errors_
.empty()) {
689 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
690 CYPosition
begin(error
->location_
.begin
);
691 CYPosition
end(error
->location_
.end
);
693 /*if (begin.line != lines2.size()) {
695 std::cerr << lines2[begin.line - 1] << std::endl;
699 for (size_t i(0); i
!= begin
.column
; ++i
)
701 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
703 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
705 std::cerr
<< std::endl
;
708 std::cerr
<< error
->message_
<< std::endl
;
717 if (driver
.script_
== NULL
)
721 CYOutput
out(str
, options
);
722 Setup(out
, driver
, options
, lower
);
723 out
<< *driver
.script_
;
731 CYLexerHighlight(code
.c_str(), code
.size(), std::cout
);
732 std::cout
<< std::endl
;
736 Output(Run(pool
, client_
, code
), &std::cout
, expand
);
740 void InjectLibrary(pid_t
, int, const char *const []);
742 static uint64_t CYGetTime() {
744 return mach_absolute_time();
746 struct timespec spec
;
747 clock_gettime(CLOCK_MONOTONIC
, &spec
);
748 return spec
.tv_sec
* UINT64_C(1000000000) + spec
.tv_nsec
;
752 int Main(int argc
, char * const argv
[], char const * const envp
[]) {
753 bool tty(isatty(STDIN_FILENO
));
758 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
761 pid_t
pid(_not(pid_t
));
764 const char *host(NULL
);
765 const char *port(NULL
);
770 int option(getopt_long(argc
, argv
,
779 , (const struct option
[]) {
780 {NULL
, no_argument
, NULL
, 'c'},
781 {NULL
, required_argument
, NULL
, 'g'},
782 {NULL
, required_argument
, NULL
, 'n'},
784 {NULL
, required_argument
, NULL
, 'p'},
786 {NULL
, required_argument
, NULL
, 'r'},
787 {NULL
, no_argument
, NULL
, 's'},
788 {0, 0, 0, 0}}, NULL
));
797 "usage: cycript [-c]"
802 " [<script> [<arg>...]]\n"
810 fprintf(stderr
, "only one of -[c"
814 "r] may be used at a time\n");
825 else if (strcmp(optarg
, "rename") == 0)
826 options
.verbose_
= true;
827 else if (strcmp(optarg
, "bison") == 0)
829 else if (strcmp(optarg
, "timing") == 0)
832 fprintf(stderr
, "invalid name for -g\n");
839 else if (strcmp(optarg
, "minify") == 0)
842 fprintf(stderr
, "invalid name for -n\n");
849 size_t size(strlen(optarg
));
852 pid
= strtoul(optarg
, &end
, 0);
853 if (optarg
+ size
!= end
) {
854 // XXX: arg needs to be escaped in some horrendous way of doom
855 // XXX: this is a memory leak now because I just don't care enough
857 int writ(asprintf(&command
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg
));
860 if (FILE *pids
= popen(command
, "r")) {
865 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
870 if (size
== sizeof(value
))
878 if (value
[size
- 1] == '\n') {
884 size
= strlen(value
);
885 pid
= strtoul(value
, &end
, 0);
886 if (value
+ size
!= end
) fail
:
888 _syscall(pclose(pids
));
891 if (pid
== _not(pid_t
)) {
892 fprintf(stderr
, "unable to find process `%s' using ps\n", optarg
);
900 //size_t size(strlen(optarg));
902 char *colon(strrchr(optarg
, ':'));
904 fprintf(stderr
, "missing colon in hostspec\n");
909 port = strtoul(colon + 1, &end, 10);
910 if (end != optarg + size) {
911 fprintf(stderr, "invalid port in hostspec\n");
936 if (pid
!= _not(pid_t
) && argc
> 1) {
937 fprintf(stderr
, "-p cannot set argv\n");
946 // XXX: const_cast?! wtf gcc :(
947 CYSetArgs(argc
- 1, const_cast<const char **>(argv
+ 1));
950 if (strcmp(script
, "-") == 0)
955 if (pid
== _not(pid_t
))
973 } server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0)));
975 struct sockaddr_un address
;
976 memset(&address
, 0, sizeof(address
));
977 address
.sun_family
= AF_UNIX
;
980 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
981 tmp
= "/Library/Caches";
986 sprintf(address
.sun_path
, "%s/.s.cy.%u", tmp
, getpid());
987 unlink(address
.sun_path
);
992 File(const char *path
) :
1000 } file(address
.sun_path
);
1002 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
1003 _syscall(chmod(address
.sun_path
, 0777));
1005 _syscall(listen(server
, 1));
1006 const char *const argv
[] = {address
.sun_path
, NULL
};
1007 InjectLibrary(pid
, 1, argv
);
1008 client_
= _syscall(accept(server
, NULL
, NULL
));
1014 if (client_
== -1 && host
!= NULL
&& port
!= NULL
) {
1015 struct addrinfo hints
;
1016 memset(&hints
, 0, sizeof(hints
));
1017 hints
.ai_family
= AF_UNSPEC
;
1018 hints
.ai_socktype
= SOCK_STREAM
;
1019 hints
.ai_protocol
= 0;
1022 struct addrinfo
*infos
;
1023 _syscall(getaddrinfo(host
, port
, &hints
, &infos
));
1025 _assert(infos
!= NULL
); try {
1026 for (struct addrinfo
*info(infos
); info
!= NULL
; info
= info
->ai_next
) {
1027 int client(_syscall(socket(info
->ai_family
, info
->ai_socktype
, info
->ai_protocol
))); try {
1028 _syscall(connect(client
, info
->ai_addr
, info
->ai_addrlen
));
1032 _syscall(close(client
));
1037 freeaddrinfo(infos
);
1042 if (script
== NULL
&& tty
)
1045 std::istream
*stream
;
1046 if (script
== NULL
) {
1050 stream
= new std::fstream(script
, std::ios::in
| std::ios::binary
);
1051 _assert(!stream
->fail());
1055 std::stringbuf buffer
;
1056 stream
->get(buffer
, '\0');
1057 _assert(!stream
->fail());
1061 uint64_t start(CYGetTime());
1064 stream
= new std::istringstream(buffer
.str());
1067 CYDriver
driver(pool
, *stream
, script
);
1070 uint64_t begin(CYGetTime());
1072 uint64_t end(CYGetTime());
1076 average
+= (end
- begin
- average
) / ++samples
;
1078 uint64_t now(CYGetTime());
1081 else if ((now
- start
) / 1000000000 >= 1)
1082 std::cout
<< std::fixed
<< average
<< '\t' << (end
- begin
) << '\t' << samples
<< std::endl
;
1088 stream
= new std::istringstream(buffer
.str());
1093 CYDriver
driver(pool
, *stream
, script
);
1096 bool failed(driver
.Parse());
1098 if (failed
|| !driver
.errors_
.empty()) {
1099 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
1100 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
1101 } else if (driver
.script_
!= NULL
) {
1103 CYOutput
out(str
, options
);
1104 Setup(out
, driver
, options
, true);
1105 out
<< *driver
.script_
;
1106 std::string
code(str
.str());
1110 CYUTF8String
json(Run(pool
, client_
, code
));
1111 if (CYStartsWith(json
, "throw ")) {
1112 CYLexerHighlight(json
.data
, json
.size
, std::cerr
);
1113 std::cerr
<< std::endl
;
1123 int main(int argc
, char * const argv
[], char const * const envp
[]) {
1125 return Main(argc
, argv
, envp
);
1126 } catch (const CYException
&error
) {
1128 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));