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>
65 #include "Display.hpp"
67 #include "Highlight.hpp"
68 #include "Replace.hpp"
70 static volatile enum {
78 static jmp_buf ctrlc_
;
80 static void sigint(int) {
100 void Setup(CYDriver
&driver
) {
104 driver
.strict_
= true;
107 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
, bool lower
) {
108 out
.pretty_
= pretty_
;
110 driver
.Replace(options
);
113 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
120 json
= CYExecute(CYGetJSContext(), pool
, code
);
132 _assert(CYSendAll(client
, &size
, sizeof(size
)));
133 _assert(CYSendAll(client
, code
.data
, code
.size
));
135 _assert(CYRecvAll(client
, &size
, sizeof(size
)));
136 if (size
== _not(uint32_t))
139 char *temp(new(pool
) char[size
+ 1]);
140 _assert(CYRecvAll(client
, temp
, size
));
147 return CYUTF8String(json
, size
);
150 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
151 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
154 static std::ostream
*out_
;
156 static void Write(bool syntax
, const char *data
, size_t size
, std::ostream
&out
) {
158 CYLexerHighlight(data
, size
, out
);
160 out
.write(data
, size
);
163 static void Output(bool syntax
, CYUTF8String json
, std::ostream
*out
, bool expand
= false) {
164 const char *data(json
.data
);
165 size_t size(json
.size
);
167 if (data
== NULL
|| out
== NULL
)
171 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
172 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
174 Write(syntax
, data
, size
, *out
);
175 else for (size_t i(0); i
!= size
; ++i
)
178 else switch(data
[++i
]) {
179 case '\0': goto done
;
180 case '\\': *out
<< '\\'; break;
181 case '\'': *out
<< '\''; break;
182 case '"': *out
<< '"'; break;
183 case 'b': *out
<< '\b'; break;
184 case 'f': *out
<< '\f'; break;
185 case 'n': *out
<< '\n'; break;
186 case 'r': *out
<< '\r'; break;
187 case 't': *out
<< '\t'; break;
188 case 'v': *out
<< '\v'; break;
189 default: *out
<< '\\'; --i
; break;
196 static void Run(int client
, bool syntax
, const char *data
, size_t size
, std::ostream
*out
= NULL
, bool expand
= false) {
198 Output(syntax
, Run(pool
, client
, CYUTF8String(data
, size
)), out
, expand
);
201 static void Run(int client
, bool syntax
, std::string
&code
, std::ostream
*out
= NULL
, bool expand
= false) {
202 Run(client
, syntax
, code
.c_str(), code
.size(), out
, expand
);
205 int (*append_history$
)(int, const char *);
207 static std::string command_
;
211 static CYUTF8String
Run(CYPool
&pool
, const std::string
&code
) {
212 return Run(pool
, client_
, code
);
215 static char **Complete(const char *word
, int start
, int end
) {
216 rl_attempted_completion_over
= ~0;
217 std::string
line(rl_line_buffer
, start
);
218 return CYComplete(word
, command_
+ line
, &Run
);
221 // need char *, not const char *
222 static char name_
[] = "cycript";
223 static char break_
[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]";
227 std::string histfile_
;
231 History(std::string histfile
) :
235 read_history(histfile_
.c_str());
239 if (append_history$
!= NULL
) {
240 int fd(_syscall(open(histfile_
.c_str(), O_CREAT
| O_WRONLY
, 0600)));
242 _assert((*append_history$
)(histlines_
, histfile_
.c_str()) == 0);
244 _assert(write_history(histfile_
.c_str()) == 0);
248 void operator +=(const std::string
&command
) {
249 add_history(command
.c_str());
254 static void Console(CYOptions
&options
) {
256 if (const char *home
= getenv("HOME"))
260 if (const char *username
= getenv("LOGNAME"))
261 passwd
= getpwnam(username
);
263 passwd
= getpwuid(getuid());
264 basedir
= passwd
->pw_dir
;
267 basedir
+= "/.cycript";
268 mkdir(basedir
.c_str(), 0700);
271 rl_readline_name
= name_
;
273 History
history(basedir
+ "/history");
283 // rl_completer_word_break_characters is broken in libedit
284 rl_basic_word_break_characters
= break_
;
286 rl_completer_word_break_characters
= break_
;
287 rl_attempted_completion_function
= &Complete
;
288 rl_bind_key('\t', rl_complete
);
290 struct sigaction action
;
291 sigemptyset(&action
.sa_mask
);
292 action
.sa_handler
= &sigint
;
294 sigaction(SIGINT
, &action
, NULL
);
298 std::vector
<std::string
> lines
;
301 const char *prompt("cy# ");
303 if (setjmp(ctrlc_
) != 0) {
311 #if RL_READLINE_VERSION >= 0x0600
313 rl_redisplay_function
= CYDisplayUpdate
;
315 rl_redisplay_function
= rl_redisplay
;
319 char *line(readline(prompt
));
325 } else if (line
[0] == '\0')
330 if (line
[0] == '?') {
331 std::string
data(line
+ 1);
332 if (data
== "bypass") {
334 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
335 } else if (data
== "debug") {
337 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
338 } else if (data
== "destroy") {
340 } else if (data
== "gc") {
341 *out_
<< "collecting... " << std::flush
;
342 CYGarbageCollect(CYGetJSContext());
343 *out_
<< "done." << std::endl
;
344 } else if (data
== "exit") {
346 } else if (data
== "expand") {
348 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
349 } else if (data
== "lower") {
351 *out_
<< "lower == " << (lower
? "true" : "false") << std::endl
;
352 } else if (data
== "syntax") {
354 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
365 char *begin(line
), *end(line
+ strlen(line
));
366 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
368 lines
.push_back(begin
);
372 lines
.push_back(begin
);
381 std::istringstream
stream(command_
);
384 CYDriver
driver(pool
, stream
);
387 bool failed(driver
.Parse());
389 if (failed
|| !driver
.errors_
.empty()) {
390 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
391 CYPosition
begin(error
->location_
.begin
);
392 if (begin
.line
!= lines
.size() + 1 || error
->warning_
) {
393 CYPosition
end(error
->location_
.end
);
395 if (begin
.line
!= lines
.size()) {
397 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
401 for (size_t i(0); i
!= begin
.column
; ++i
)
403 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
405 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
407 std::cerr
<< std::endl
;
410 std::cerr
<< error
->message_
<< std::endl
;
412 history
+= command_
.substr(0, command_
.size() - 1);
417 driver
.errors_
.clear();
423 if (driver
.program_
== NULL
)
427 CYOutput
out(str
, options
);
428 Setup(out
, driver
, options
, lower
);
429 out
<< *driver
.program_
;
433 history
+= command_
.substr(0, command_
.size() - 1);
437 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
438 std::cout
<< std::endl
;
441 Run(client_
, syntax
, code
, out_
, expand
);
445 void InjectLibrary(pid_t
, int, const char *const []);
447 int Main(int argc
, char * const argv
[], char const * const envp
[]) {
448 bool tty(isatty(STDIN_FILENO
));
453 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
456 pid_t
pid(_not(pid_t
));
459 const char *host(NULL
);
460 const char *port(NULL
);
465 int option(getopt_long(argc
, argv
,
474 , (const struct option
[]) {
475 {NULL
, no_argument
, NULL
, 'c'},
476 {NULL
, required_argument
, NULL
, 'g'},
477 {NULL
, required_argument
, NULL
, 'n'},
479 {NULL
, required_argument
, NULL
, 'p'},
481 {NULL
, required_argument
, NULL
, 'r'},
482 {NULL
, no_argument
, NULL
, 's'},
483 {0, 0, 0, 0}}, NULL
));
492 "usage: cycript [-c]"
497 " [<script> [<arg>...]]\n"
505 fprintf(stderr
, "only one of -[c"
509 "r] may be used at a time\n");
520 else if (strcmp(optarg
, "rename") == 0)
521 options
.verbose_
= true;
522 else if (strcmp(optarg
, "bison") == 0)
525 fprintf(stderr
, "invalid name for -g\n");
532 else if (strcmp(optarg
, "minify") == 0)
535 fprintf(stderr
, "invalid name for -n\n");
542 size_t size(strlen(optarg
));
545 pid
= strtoul(optarg
, &end
, 0);
546 if (optarg
+ size
!= end
) {
547 // XXX: arg needs to be escaped in some horrendous way of doom
548 // XXX: this is a memory leak now because I just don't care enough
550 int writ(asprintf(&command
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg
));
553 if (FILE *pids
= popen(command
, "r")) {
558 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
563 if (size
== sizeof(value
))
571 if (value
[size
- 1] == '\n') {
577 size
= strlen(value
);
578 pid
= strtoul(value
, &end
, 0);
579 if (value
+ size
!= end
) fail
:
581 _syscall(pclose(pids
));
584 if (pid
== _not(pid_t
)) {
585 fprintf(stderr
, "unable to find process `%s' using ps\n", optarg
);
593 //size_t size(strlen(optarg));
595 char *colon(strrchr(optarg
, ':'));
597 fprintf(stderr
, "missing colon in hostspec\n");
602 port = strtoul(colon + 1, &end, 10);
603 if (end != optarg + size) {
604 fprintf(stderr, "invalid port in hostspec\n");
629 if (pid
!= _not(pid_t
) && argc
> 1) {
630 fprintf(stderr
, "-p cannot set argv\n");
639 // XXX: const_cast?! wtf gcc :(
640 CYSetArgs(argc
- 1, const_cast<const char **>(argv
+ 1));
643 if (strcmp(script
, "-") == 0)
648 if (pid
== _not(pid_t
))
666 } server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0)));
668 struct sockaddr_un address
;
669 memset(&address
, 0, sizeof(address
));
670 address
.sun_family
= AF_UNIX
;
673 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
674 tmp
= "/Library/Caches";
679 sprintf(address
.sun_path
, "%s/.s.cy.%u", tmp
, getpid());
680 unlink(address
.sun_path
);
685 File(const char *path
) :
693 } file(address
.sun_path
);
695 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
696 _syscall(chmod(address
.sun_path
, 0777));
698 _syscall(listen(server
, 1));
699 const char *const argv
[] = {address
.sun_path
, NULL
};
700 InjectLibrary(pid
, 1, argv
);
701 client_
= _syscall(accept(server
, NULL
, NULL
));
707 if (client_
== -1 && host
!= NULL
&& port
!= NULL
) {
708 struct addrinfo hints
;
709 memset(&hints
, 0, sizeof(hints
));
710 hints
.ai_family
= AF_UNSPEC
;
711 hints
.ai_socktype
= SOCK_STREAM
;
712 hints
.ai_protocol
= 0;
715 struct addrinfo
*infos
;
716 _syscall(getaddrinfo(host
, port
, &hints
, &infos
));
718 _assert(infos
!= NULL
); try {
719 for (struct addrinfo
*info(infos
); info
!= NULL
; info
= info
->ai_next
) {
720 int client(_syscall(socket(info
->ai_family
, info
->ai_socktype
, info
->ai_protocol
))); try {
721 _syscall(connect(client
, info
->ai_addr
, info
->ai_addrlen
));
725 _syscall(close(client
));
735 if (script
== NULL
&& tty
)
738 std::istream
*stream
;
739 if (script
== NULL
) {
743 stream
= new std::fstream(script
, std::ios::in
| std::ios::binary
);
744 _assert(!stream
->fail());
748 CYDriver
driver(pool
, *stream
, script
);
751 bool failed(driver
.Parse());
753 if (failed
|| !driver
.errors_
.empty()) {
754 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
755 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
756 } else if (driver
.program_
!= NULL
) {
758 CYOutput
out(str
, options
);
759 Setup(out
, driver
, options
, true);
760 out
<< *driver
.program_
;
761 std::string
code(str
.str());
765 Run(client_
, false, code
, &std::cout
);
772 int main(int argc
, char * const argv
[], char const * const envp
[]) {
774 return Main(argc
, argv
, envp
);
775 } catch (const CYException
&error
) {
777 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));