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"
34 #ifdef HAVE_READLINE_H
37 #include <readline/readline.h>
43 #include <readline/history.h>
51 #include <sys/socket.h>
52 #include <sys/types.h>
57 #include <sys/types.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
66 #include <mach/mach_time.h>
69 #include "Display.hpp"
72 #include "Highlight.hpp"
75 static volatile enum {
83 static jmp_buf ctrlc_
;
85 static void sigint(int) {
106 void Setup(CYDriver
&driver
) {
110 driver
.strict_
= true;
113 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
, bool lower
) {
114 out
.pretty_
= pretty_
;
116 driver
.Replace(options
);
119 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
126 json
= CYExecute(CYGetJSContext(), pool
, code
);
138 _assert(CYSendAll(client
, &size
, sizeof(size
)));
139 _assert(CYSendAll(client
, code
.data
, code
.size
));
141 _assert(CYRecvAll(client
, &size
, sizeof(size
)));
142 if (size
== _not(uint32_t))
145 char *temp(new(pool
) char[size
+ 1]);
146 _assert(CYRecvAll(client
, temp
, size
));
153 return CYUTF8String(json
, size
);
156 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
157 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
160 static std::ostream
*out_
;
162 static void Output(CYUTF8String json
, std::ostream
*out
, bool expand
= false) {
163 const char *data(json
.data
);
164 size_t size(json
.size
);
166 if (data
== NULL
|| out
== NULL
)
170 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
171 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
173 CYLexerHighlight(data
, size
, *out
);
174 else for (size_t i(0); i
!= size
; ++i
)
177 else switch(data
[++i
]) {
178 case '\0': goto done
;
179 case '\\': *out
<< '\\'; break;
180 case '\'': *out
<< '\''; break;
181 case '"': *out
<< '"'; break;
182 case 'b': *out
<< '\b'; break;
183 case 'f': *out
<< '\f'; break;
184 case 'n': *out
<< '\n'; break;
185 case 'r': *out
<< '\r'; break;
186 case 't': *out
<< '\t'; break;
187 case 'v': *out
<< '\v'; break;
188 default: *out
<< '\\'; --i
; break;
195 int (*append_history$
)(int, const char *);
197 static std::string command_
;
201 static CYUTF8String
Run(CYPool
&pool
, const std::string
&code
) {
202 return Run(pool
, client_
, code
);
205 static char **Complete(const char *word
, int start
, int end
) {
206 rl_attempted_completion_over
= ~0;
207 std::string
line(rl_line_buffer
, start
);
208 return CYComplete(word
, command_
+ line
, &Run
);
211 // need char *, not const char *
212 static char name_
[] = "cycript";
213 static char break_
[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]";
217 std::string histfile_
;
221 History(std::string histfile
) :
225 read_history(histfile_
.c_str());
229 if (append_history$
!= NULL
) {
230 int fd(_syscall(open(histfile_
.c_str(), O_CREAT
| O_WRONLY
, 0600)));
232 _assert((*append_history$
)(histlines_
, histfile_
.c_str()) == 0);
234 _assert(write_history(histfile_
.c_str()) == 0);
238 void operator +=(const std::string
&command
) {
239 add_history(command
.c_str());
244 static void Console(CYOptions
&options
) {
246 if (const char *home
= getenv("HOME"))
250 if (const char *username
= getenv("LOGNAME"))
251 passwd
= getpwnam(username
);
253 passwd
= getpwuid(getuid());
254 basedir
= passwd
->pw_dir
;
257 basedir
+= "/.cycript";
258 mkdir(basedir
.c_str(), 0700);
261 rl_readline_name
= name_
;
263 History
history(basedir
+ "/history");
272 // rl_completer_word_break_characters is broken in libedit
273 rl_basic_word_break_characters
= break_
;
275 rl_completer_word_break_characters
= break_
;
276 rl_attempted_completion_function
= &Complete
;
277 rl_bind_key('\t', rl_complete
);
279 #if RL_READLINE_VERSION >= 0x0600
280 rl_redisplay_function
= CYDisplayUpdate
;
283 struct sigaction action
;
284 sigemptyset(&action
.sa_mask
);
285 action
.sa_handler
= &sigint
;
287 sigaction(SIGINT
, &action
, NULL
);
291 std::vector
<std::string
> lines
;
294 const char *prompt("cy# ");
296 if (setjmp(ctrlc_
) != 0) {
304 char *line(readline(prompt
));
310 } else if (line
[0] == '\0')
315 if (line
[0] == '?') {
316 std::string
data(line
+ 1);
317 if (data
== "bypass") {
319 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
320 } else if (data
== "debug") {
322 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
323 } else if (data
== "destroy") {
325 } else if (data
== "gc") {
326 *out_
<< "collecting... " << std::flush
;
327 CYGarbageCollect(CYGetJSContext());
328 *out_
<< "done." << std::endl
;
329 } else if (data
== "exit") {
331 } else if (data
== "expand") {
333 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
334 } else if (data
== "lower") {
336 *out_
<< "lower == " << (lower
? "true" : "false") << std::endl
;
347 char *begin(line
), *end(line
+ strlen(line
));
348 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
350 lines
.push_back(begin
);
354 lines
.push_back(begin
);
363 std::istringstream
stream(command_
);
366 CYDriver
driver(pool
, stream
);
369 bool failed(driver
.Parse());
371 if (failed
|| !driver
.errors_
.empty()) {
372 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
373 CYPosition
begin(error
->location_
.begin
);
374 if (begin
.line
!= lines
.size() + 1 || error
->warning_
) {
375 CYPosition
end(error
->location_
.end
);
377 if (begin
.line
!= lines
.size()) {
379 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
383 for (size_t i(0); i
!= begin
.column
; ++i
)
385 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
387 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
389 std::cerr
<< std::endl
;
392 std::cerr
<< error
->message_
<< std::endl
;
394 history
+= command_
.substr(0, command_
.size() - 1);
399 driver
.errors_
.clear();
405 if (driver
.script_
== NULL
)
409 CYOutput
out(str
, options
);
410 Setup(out
, driver
, options
, lower
);
411 out
<< *driver
.script_
;
415 history
+= command_
.substr(0, command_
.size() - 1);
419 CYLexerHighlight(code
.c_str(), code
.size(), std::cout
);
420 std::cout
<< std::endl
;
424 Output(Run(pool
, client_
, code
), &std::cout
, expand
);
428 void InjectLibrary(pid_t
, int, const char *const []);
430 static uint64_t CYGetTime() {
432 return mach_absolute_time();
434 struct timespec spec
;
435 clock_gettime(CLOCK_MONOTONIC
, &spec
);
436 return spec
.tv_sec
* UINT64_C(1000000000) + spec
.tv_nsec
;
440 int Main(int argc
, char * const argv
[], char const * const envp
[]) {
441 bool tty(isatty(STDIN_FILENO
));
446 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
449 pid_t
pid(_not(pid_t
));
452 const char *host(NULL
);
453 const char *port(NULL
);
458 int option(getopt_long(argc
, argv
,
467 , (const struct option
[]) {
468 {NULL
, no_argument
, NULL
, 'c'},
469 {NULL
, required_argument
, NULL
, 'g'},
470 {NULL
, required_argument
, NULL
, 'n'},
472 {NULL
, required_argument
, NULL
, 'p'},
474 {NULL
, required_argument
, NULL
, 'r'},
475 {NULL
, no_argument
, NULL
, 's'},
476 {0, 0, 0, 0}}, NULL
));
485 "usage: cycript [-c]"
490 " [<script> [<arg>...]]\n"
498 fprintf(stderr
, "only one of -[c"
502 "r] may be used at a time\n");
513 else if (strcmp(optarg
, "rename") == 0)
514 options
.verbose_
= true;
515 else if (strcmp(optarg
, "bison") == 0)
517 else if (strcmp(optarg
, "timing") == 0)
520 fprintf(stderr
, "invalid name for -g\n");
527 else if (strcmp(optarg
, "minify") == 0)
530 fprintf(stderr
, "invalid name for -n\n");
537 size_t size(strlen(optarg
));
540 pid
= strtoul(optarg
, &end
, 0);
541 if (optarg
+ size
!= end
) {
542 // XXX: arg needs to be escaped in some horrendous way of doom
543 // XXX: this is a memory leak now because I just don't care enough
545 int writ(asprintf(&command
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg
));
548 if (FILE *pids
= popen(command
, "r")) {
553 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
558 if (size
== sizeof(value
))
566 if (value
[size
- 1] == '\n') {
572 size
= strlen(value
);
573 pid
= strtoul(value
, &end
, 0);
574 if (value
+ size
!= end
) fail
:
576 _syscall(pclose(pids
));
579 if (pid
== _not(pid_t
)) {
580 fprintf(stderr
, "unable to find process `%s' using ps\n", optarg
);
588 //size_t size(strlen(optarg));
590 char *colon(strrchr(optarg
, ':'));
592 fprintf(stderr
, "missing colon in hostspec\n");
597 port = strtoul(colon + 1, &end, 10);
598 if (end != optarg + size) {
599 fprintf(stderr, "invalid port in hostspec\n");
624 if (pid
!= _not(pid_t
) && argc
> 1) {
625 fprintf(stderr
, "-p cannot set argv\n");
634 // XXX: const_cast?! wtf gcc :(
635 CYSetArgs(argc
- 1, const_cast<const char **>(argv
+ 1));
638 if (strcmp(script
, "-") == 0)
643 if (pid
== _not(pid_t
))
661 } server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0)));
663 struct sockaddr_un address
;
664 memset(&address
, 0, sizeof(address
));
665 address
.sun_family
= AF_UNIX
;
668 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
669 tmp
= "/Library/Caches";
674 sprintf(address
.sun_path
, "%s/.s.cy.%u", tmp
, getpid());
675 unlink(address
.sun_path
);
680 File(const char *path
) :
688 } file(address
.sun_path
);
690 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
691 _syscall(chmod(address
.sun_path
, 0777));
693 _syscall(listen(server
, 1));
694 const char *const argv
[] = {address
.sun_path
, NULL
};
695 InjectLibrary(pid
, 1, argv
);
696 client_
= _syscall(accept(server
, NULL
, NULL
));
702 if (client_
== -1 && host
!= NULL
&& port
!= NULL
) {
703 struct addrinfo hints
;
704 memset(&hints
, 0, sizeof(hints
));
705 hints
.ai_family
= AF_UNSPEC
;
706 hints
.ai_socktype
= SOCK_STREAM
;
707 hints
.ai_protocol
= 0;
710 struct addrinfo
*infos
;
711 _syscall(getaddrinfo(host
, port
, &hints
, &infos
));
713 _assert(infos
!= NULL
); try {
714 for (struct addrinfo
*info(infos
); info
!= NULL
; info
= info
->ai_next
) {
715 int client(_syscall(socket(info
->ai_family
, info
->ai_socktype
, info
->ai_protocol
))); try {
716 _syscall(connect(client
, info
->ai_addr
, info
->ai_addrlen
));
720 _syscall(close(client
));
730 if (script
== NULL
&& tty
)
733 std::istream
*stream
;
734 if (script
== NULL
) {
738 stream
= new std::fstream(script
, std::ios::in
| std::ios::binary
);
739 _assert(!stream
->fail());
743 std::stringbuf buffer
;
744 stream
->get(buffer
, '\0');
745 _assert(!stream
->fail());
749 uint64_t start(CYGetTime());
752 stream
= new std::istringstream(buffer
.str());
755 CYDriver
driver(pool
, *stream
, script
);
758 uint64_t begin(CYGetTime());
760 uint64_t end(CYGetTime());
764 average
+= (end
- begin
- average
) / ++samples
;
766 uint64_t now(CYGetTime());
769 else if ((now
- start
) / 1000000000 >= 1)
770 std::cout
<< std::fixed
<< average
<< '\t' << (end
- begin
) << '\t' << samples
<< std::endl
;
776 stream
= new std::istringstream(buffer
.str());
781 CYDriver
driver(pool
, *stream
, script
);
784 bool failed(driver
.Parse());
786 if (failed
|| !driver
.errors_
.empty()) {
787 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
788 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
789 } else if (driver
.script_
!= NULL
) {
791 CYOutput
out(str
, options
);
792 Setup(out
, driver
, options
, true);
793 out
<< *driver
.script_
;
794 std::string
code(str
.str());
798 CYUTF8String
json(Run(pool
, client_
, code
));
799 if (CYStartsWith(json
, "throw ")) {
800 CYLexerHighlight(json
.data
, json
.size
, std::cerr
);
801 std::cerr
<< std::endl
;
811 int main(int argc
, char * const argv
[], char const * const envp
[]) {
813 return Main(argc
, argv
, envp
);
814 } catch (const CYException
&error
) {
816 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));