1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cycript. 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>
49 #include <sys/socket.h>
50 #include <sys/types.h>
55 #include <sys/types.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
61 #include <apr_getopt.h>
62 #include <apr_pools.h>
63 #include <apr_strings.h>
67 #include "Display.hpp"
68 #include "Replace.hpp"
70 #include "Cycript.tab.hh"
73 static volatile enum {
81 static jmp_buf ctrlc_
;
83 static void sigint(int) {
104 void Setup(CYDriver
&driver
, cy::parser
&parser
) {
107 parser
.set_debug_level(1);
110 driver
.strict_
= true;
113 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
, bool lower
) {
114 out
.pretty_
= pretty_
;
115 CYContext
context(options
);
117 driver
.program_
->Replace(context
);
120 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
127 json
= CYExecute(CYGetJSContext(), pool
, code
);
139 _assert(CYSendAll(client
, &size
, sizeof(size
)));
140 _assert(CYSendAll(client
, code
.data
, code
.size
));
142 _assert(CYRecvAll(client
, &size
, sizeof(size
)));
143 if (size
== _not(uint32_t))
146 char *temp(new(pool
) char[size
+ 1]);
147 _assert(CYRecvAll(client
, temp
, size
));
154 return CYUTF8String(json
, size
);
157 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
158 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
161 static std::ostream
*out_
;
163 static void Write(bool syntax
, const char *data
, size_t size
, std::ostream
&out
) {
165 CYLexerHighlight(data
, size
, out
);
167 out
.write(data
, size
);
170 static void Output(bool syntax
, CYUTF8String json
, std::ostream
*out
, bool expand
= false) {
171 const char *data(json
.data
);
172 size_t size(json
.size
);
174 if (data
== NULL
|| out
== NULL
)
178 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
179 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
181 Write(syntax
, data
, size
, *out
);
182 else for (size_t i(0); i
!= size
; ++i
)
185 else switch(data
[++i
]) {
186 case '\0': goto done
;
187 case '\\': *out
<< '\\'; break;
188 case '\'': *out
<< '\''; break;
189 case '"': *out
<< '"'; break;
190 case 'b': *out
<< '\b'; break;
191 case 'f': *out
<< '\f'; break;
192 case 'n': *out
<< '\n'; break;
193 case 'r': *out
<< '\r'; break;
194 case 't': *out
<< '\t'; break;
195 case 'v': *out
<< '\v'; break;
196 default: *out
<< '\\'; --i
; break;
203 static void Run(int client
, bool syntax
, const char *data
, size_t size
, std::ostream
*out
= NULL
, bool expand
= false) {
205 Output(syntax
, Run(pool
, client
, CYUTF8String(data
, size
)), out
, expand
);
208 static void Run(int client
, bool syntax
, std::string
&code
, std::ostream
*out
= NULL
, bool expand
= false) {
209 Run(client
, syntax
, code
.c_str(), code
.size(), out
, expand
);
212 int (*append_history$
)(int, const char *);
214 static std::string command_
;
216 static CYExpression
*ParseExpression(CYUTF8String code
) {
217 std::stringstream stream
;
218 stream
<< '(' << code
<< ')';
219 CYDriver
driver(stream
);
221 cy::parser
parser(driver
);
222 Setup(driver
, parser
);
224 if (parser
.parse() != 0 || !driver
.errors_
.empty())
228 CYContext
context(options
);
230 CYStatement
*statement(driver
.program_
->statements_
);
231 _assert(statement
!= NULL
);
232 _assert(statement
->next_
== NULL
);
234 CYExpress
*express(dynamic_cast<CYExpress
*>(driver
.program_
->statements_
));
235 _assert(express
!= NULL
);
237 return express
->expression_
;
242 static char **Complete(const char *word
, int start
, int end
) {
243 rl_attempted_completion_over
= TRUE
;
247 std::string
line(rl_line_buffer
, start
);
248 std::istringstream
stream(command_
+ line
);
249 CYDriver
driver(stream
);
253 cy::parser
parser(driver
);
254 Setup(driver
, parser
);
256 if (parser
.parse() != 0 || !driver
.errors_
.empty())
259 if (driver
.mode_
== CYDriver::AutoNone
)
262 CYExpression
*expression
;
265 CYContext
context(options
);
267 std::ostringstream prefix
;
269 switch (driver
.mode_
) {
270 case CYDriver::AutoPrimary
:
271 expression
= $
CYThis();
274 case CYDriver::AutoDirect
:
275 expression
= driver
.context_
;
278 case CYDriver::AutoIndirect
:
279 expression
= $
CYIndirect(driver
.context_
);
282 case CYDriver::AutoMessage
: {
283 CYDriver::Context
&thing(driver
.contexts_
.back());
284 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
285 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
286 prefix
<< (*part
)->word_
<< ':';
293 std::string
begin(prefix
.str());
295 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
296 " function(object, prefix, word) {\n"
298 " var before = prefix.length;\n"
300 " var entire = prefix.length;\n"
301 " for (var name in object)\n"
302 " if (name.substring(0, entire) == prefix)\n"
303 " names.push(name.substr(before));\n"
306 ), expression
, $
S(begin
.c_str()), $
S(word
))));
308 driver
.program_
->Replace(context
);
310 std::ostringstream str
;
311 CYOutput
out(str
, options
);
312 out
<< *driver
.program_
;
314 std::string
code(str
.str());
315 CYUTF8String
json(Run(pool
, client_
, code
));
316 // XXX: if this fails we should not try to parse it
318 CYExpression
*result(ParseExpression(json
));
322 CYArray
*array(dynamic_cast<CYArray
*>(result
->Primitive(context
)));
325 Output(false, json
, out_
);
326 rl_forced_update_display();
330 // XXX: use an std::set?
331 typedef std::vector
<std::string
> Completions
;
332 Completions completions
;
337 CYForEach (element
, array
->elements_
) {
338 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
339 _assert(string
!= NULL
);
341 std::string completion
;
342 if (string
->size_
!= 0)
343 completion
.assign(string
->value_
, string
->size_
);
344 else if (driver
.mode_
== CYDriver::AutoMessage
)
349 completions
.push_back(completion
);
355 size_t limit(completion
.size()), size(common
.size());
357 common
= common
.substr(0, limit
);
360 for (limit
= 0; limit
!= size
; ++limit
)
361 if (common
[limit
] != completion
[limit
])
364 common
= common
.substr(0, limit
);
368 size_t count(completions
.size());
372 size_t colon(common
.find(':'));
373 if (colon
!= std::string::npos
)
374 common
= common
.substr(0, colon
+ 1);
375 if (completions
.size() == 1)
378 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
380 results
[0] = strdup(common
.c_str());
382 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
383 results
[++index
] = strdup(i
->c_str());
384 results
[count
+ 1] = NULL
;
389 // need char *, not const char *
390 static char name_
[] = "cycript";
391 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
395 std::string histfile_
;
399 History(std::string histfile
) :
403 read_history(histfile_
.c_str());
407 if (append_history$
!= NULL
) {
408 _syscall(close(_syscall(open(histfile_
.c_str(), O_CREAT
| O_WRONLY
, 0600))));
409 _assert((*append_history$
)(histlines_
, histfile_
.c_str()) == 0);
411 _assert(write_history(histfile_
.c_str()) == 0);
415 void operator +=(const std::string
&command
) {
416 add_history(command_
.c_str());
421 static void Console(CYOptions
&options
) {
425 if (const char *username
= getenv("LOGNAME"))
426 passwd
= getpwnam(username
);
428 passwd
= getpwuid(getuid());
430 std::string
basedir(passwd
->pw_dir
);
431 basedir
+= "/.cycript";
432 mkdir(basedir
.c_str(), 0700);
435 rl_readline_name
= name_
;
437 History
history(basedir
+ "/history");
447 // rl_completer_word_break_characters is broken in libedit
448 rl_basic_word_break_characters
= break_
;
450 rl_completer_word_break_characters
= break_
;
451 rl_attempted_completion_function
= &Complete
;
452 rl_bind_key('\t', rl_complete
);
454 struct sigaction action
;
455 sigemptyset(&action
.sa_mask
);
456 action
.sa_handler
= &sigint
;
458 sigaction(SIGINT
, &action
, NULL
);
462 std::vector
<std::string
> lines
;
465 const char *prompt("cy# ");
467 if (setjmp(ctrlc_
) != 0) {
475 #if RL_READLINE_VERSION >= 0x0600
477 rl_redisplay_function
= CYDisplayUpdate
;
479 rl_redisplay_function
= rl_redisplay
;
483 char *line(readline(prompt
));
489 } else if (line
[0] == '\0')
494 if (line
[0] == '?') {
495 std::string
data(line
+ 1);
496 if (data
== "bypass") {
498 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
499 } else if (data
== "debug") {
501 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
502 } else if (data
== "destroy") {
504 } else if (data
== "gc") {
505 *out_
<< "collecting... " << std::flush
;
506 CYGarbageCollect(CYGetJSContext());
507 *out_
<< "done." << std::endl
;
508 } else if (data
== "exit") {
510 } else if (data
== "expand") {
512 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
513 } else if (data
== "lower") {
515 *out_
<< "lower == " << (lower
? "true" : "false") << std::endl
;
516 } else if (data
== "syntax") {
518 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
528 char *begin(line
), *end(line
+ strlen(line
));
529 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
531 lines
.push_back(begin
);
535 lines
.push_back(begin
);
546 std::istringstream
stream(command_
);
547 CYDriver
driver(stream
);
549 cy::parser
parser(driver
);
550 Setup(driver
, parser
);
552 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
553 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
554 cy::position
begin(error
->location_
.begin
);
555 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
556 cy::position
end(error
->location_
.end
);
558 if (begin
.line
!= lines
.size()) {
560 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
564 for (size_t i(0); i
!= begin
.column
; ++i
)
566 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
568 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
570 std::cerr
<< std::endl
;
573 std::cerr
<< error
->message_
<< std::endl
;
580 driver
.errors_
.clear();
587 if (driver
.program_
== NULL
)
590 std::ostringstream str
;
591 CYOutput
out(str
, options
);
592 Setup(out
, driver
, options
, lower
);
593 out
<< *driver
.program_
;
601 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
602 std::cout
<< std::endl
;
605 Run(client_
, syntax
, code
, out_
, expand
);
609 void InjectLibrary(pid_t pid
);
611 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
612 _aprcall(apr_initialize());
615 apr_pool_create(&pool
, NULL
);
617 bool tty(isatty(STDIN_FILENO
));
622 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
625 pid_t
pid(_not(pid_t
));
628 const char *host(NULL
);
629 const char *port(NULL
);
632 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
638 apr_status_t
status(apr_getopt_long(state
, (apr_getopt_option_t
[]) {
639 {NULL
, 'c', false, NULL
},
640 {NULL
, 'g', true, NULL
},
641 {NULL
, 'n', true, NULL
},
643 {NULL
, 'p', true, NULL
},
645 {NULL
, 'r', true, NULL
},
646 {NULL
, 's', false, NULL
},
647 {0, 0, 0, 0}}, &opt
, &arg
));
655 "usage: cycript [-c]"
660 " [<script> [<arg>...]]\n"
672 fprintf(stderr
, "only one of -[c"
676 "r] may be used at a time\n");
687 else if (strcmp(arg
, "rename") == 0)
688 options
.verbose_
= true;
690 else if (strcmp(arg
, "bison") == 0)
694 fprintf(stderr
, "invalid name for -g\n");
701 else if (strcmp(arg
, "minify") == 0)
704 fprintf(stderr
, "invalid name for -n\n");
711 size_t size(strlen(arg
));
714 pid
= strtoul(arg
, &end
, 0);
715 if (arg
+ size
!= end
) {
716 // XXX: arg needs to be escaped in some horrendous way of doom
717 const char *command(apr_pstrcat(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^", arg
, " /{s/^[^ ]* //;q;};};d'", NULL
));
719 if (FILE *pids
= popen(command
, "r")) {
724 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
729 if (size
== sizeof(value
))
737 if (value
[size
- 1] == '\n') {
743 size
= strlen(value
);
744 pid
= strtoul(value
, &end
, 0);
745 if (value
+ size
!= end
) fail
:
747 _syscall(pclose(pids
));
750 if (pid
== _not(pid_t
)) {
751 fprintf(stderr
, "unable to find process `%s' using ps\n", arg
);
759 //size_t size(strlen(arg));
761 char *colon(strrchr(arg
, ':'));
763 fprintf(stderr
, "missing colon in hostspec\n");
768 port = strtoul(colon + 1, &end, 10);
769 if (end != arg + size) {
770 fprintf(stderr, "invalid port in hostspec\n");
789 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
790 fprintf(stderr
, "-p cannot set argv\n");
799 // XXX: const_cast?! wtf gcc :(
800 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
803 if (strcmp(script
, "-") == 0)
808 if (pid
== _not(pid_t
))
826 } server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0)));
828 struct sockaddr_un address
;
829 memset(&address
, 0, sizeof(address
));
830 address
.sun_family
= AF_UNIX
;
832 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
833 unlink(address
.sun_path
);
838 File(const char *path
) :
846 } file(address
.sun_path
);
848 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
849 _syscall(chmod(address
.sun_path
, 0777));
851 _syscall(listen(server
, 1));
853 client_
= _syscall(accept(server
, NULL
, NULL
));
859 if (client_
== -1 && host
!= NULL
&& port
!= NULL
) {
860 struct addrinfo hints
;
861 memset(&hints
, 0, sizeof(hints
));
862 hints
.ai_family
= AF_UNSPEC
;
863 hints
.ai_socktype
= SOCK_STREAM
;
864 hints
.ai_protocol
= 0;
867 struct addrinfo
*infos
;
868 _syscall(getaddrinfo(host
, port
, &hints
, &infos
));
870 _assert(infos
!= NULL
); try {
871 for (struct addrinfo
*info(infos
); info
!= NULL
; info
= info
->ai_next
) {
872 int client(_syscall(socket(info
->ai_family
, info
->ai_socktype
, info
->ai_protocol
))); try {
873 _syscall(connect(client
, info
->ai_addr
, info
->ai_addrlen
));
877 _syscall(close(client
));
887 if (script
== NULL
&& tty
)
892 std::istream
*stream
;
893 if (script
== NULL
) {
897 stream
= new std::fstream(script
, std::ios::in
| std::ios::binary
);
898 _assert(!stream
->fail());
901 CYDriver
driver(*stream
, script
);
902 cy::parser
parser(driver
);
903 Setup(driver
, parser
);
905 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
906 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
907 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
908 } else if (driver
.program_
!= NULL
) {
909 std::ostringstream str
;
910 CYOutput
out(str
, options
);
911 Setup(out
, driver
, options
, true);
912 out
<< *driver
.program_
;
913 std::string
code(str
.str());
917 Run(client_
, false, code
, &std::cout
);
921 apr_pool_destroy(pool
);
926 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
927 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
929 if (status
!= APR_SUCCESS
) {
930 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
933 return Main(argc
, argv
, envp
);
934 } catch (const CYException
&error
) {
936 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));