1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2012 Jay Freeman (saurik)
5 /* GNU Lesser General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Cycript. 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>
50 #include <sys/types.h>
54 #include "Cycript.tab.hh"
56 #include <sys/types.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
62 #include <apr_getopt.h>
66 #include "Replace.hpp"
68 static volatile enum {
76 static jmp_buf ctrlc_
;
78 static void sigint(int) {
99 void Setup(CYDriver
&driver
, cy::parser
&parser
) {
102 parser
.set_debug_level(1);
105 driver
.strict_
= true;
108 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
) {
109 out
.pretty_
= pretty_
;
110 CYContext
context(options
);
111 driver
.program_
->Replace(context
);
114 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
121 json
= CYExecute(pool
, code
);
133 CYSendAll(client
, &size
, sizeof(size
));
134 CYSendAll(client
, code
.data
, code
.size
);
136 CYRecvAll(client
, &size
, sizeof(size
));
137 if (size
== _not(size_t))
140 char *temp(new(pool
) char[size
+ 1]);
141 CYRecvAll(client
, temp
, size
);
148 return CYUTF8String(json
, size
);
151 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
152 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
155 static std::ostream
*out_
;
157 static void Write(bool syntax
, const char *data
, size_t size
, std::ostream
&out
) {
159 CYLexerHighlight(data
, size
, out
);
161 out
.write(data
, size
);
164 static void Output(bool syntax
, CYUTF8String json
, std::ostream
*out
, bool expand
= false) {
165 const char *data(json
.data
);
166 size_t size(json
.size
);
168 if (data
== NULL
|| out
== NULL
)
172 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
173 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
175 Write(syntax
, data
, size
, *out
);
176 else for (size_t i(0); i
!= size
; ++i
)
179 else switch(data
[++i
]) {
180 case '\0': goto done
;
181 case '\\': *out
<< '\\'; break;
182 case '\'': *out
<< '\''; break;
183 case '"': *out
<< '"'; break;
184 case 'b': *out
<< '\b'; break;
185 case 'f': *out
<< '\f'; break;
186 case 'n': *out
<< '\n'; break;
187 case 'r': *out
<< '\r'; break;
188 case 't': *out
<< '\t'; break;
189 case 'v': *out
<< '\v'; break;
190 default: *out
<< '\\'; --i
; break;
197 static void Run(int client
, bool syntax
, const char *data
, size_t size
, std::ostream
*out
= NULL
, bool expand
= false) {
199 Output(syntax
, Run(pool
, client
, CYUTF8String(data
, size
)), out
, expand
);
202 static void Run(int client
, bool syntax
, std::string
&code
, std::ostream
*out
= NULL
, bool expand
= false) {
203 Run(client
, syntax
, code
.c_str(), code
.size(), out
, expand
);
206 int (*append_history$
)(int, const char *);
208 static std::string command_
;
210 static CYExpression
*ParseExpression(CYUTF8String code
) {
211 std::stringstream stream
;
212 stream
<< '(' << code
<< ')';
213 CYDriver
driver(stream
);
215 cy::parser
parser(driver
);
216 Setup(driver
, parser
);
218 if (parser
.parse() != 0 || !driver
.errors_
.empty())
222 CYContext
context(options
);
224 // XXX: this could be replaced with a CYStatement::Primitive()
225 if (CYExpress
*express
= dynamic_cast<CYExpress
*>(driver
.program_
->statements_
))
226 return express
->expression_
->Primitive(context
);
233 static char **Complete(const char *word
, int start
, int end
) {
234 rl_attempted_completion_over
= TRUE
;
238 std::string
line(rl_line_buffer
, start
);
239 std::istringstream
stream(command_
+ line
);
240 CYDriver
driver(stream
);
244 cy::parser
parser(driver
);
245 Setup(driver
, parser
);
247 if (parser
.parse() != 0 || !driver
.errors_
.empty())
250 if (driver
.mode_
== CYDriver::AutoNone
)
253 CYExpression
*expression
;
256 CYContext
context(options
);
258 std::ostringstream prefix
;
260 switch (driver
.mode_
) {
261 case CYDriver::AutoPrimary
:
262 expression
= $
CYThis();
265 case CYDriver::AutoDirect
:
266 expression
= driver
.context_
;
269 case CYDriver::AutoIndirect
:
270 expression
= $
CYIndirect(driver
.context_
);
273 case CYDriver::AutoMessage
: {
274 CYDriver::Context
&thing(driver
.contexts_
.back());
275 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
276 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
277 prefix
<< (*part
)->word_
<< ':';
284 std::string
begin(prefix
.str());
286 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
287 " function(object, prefix, word) {\n"
289 " var before = prefix.length;\n"
291 " var entire = prefix.length;\n"
292 " for (name in object)\n"
293 " if (name.substring(0, entire) == prefix)\n"
294 " names.push(name.substr(before));\n"
297 ), expression
, $
S(begin
.c_str()), $
S(word
))));
299 driver
.program_
->Replace(context
);
301 std::ostringstream str
;
302 CYOutput
out(str
, options
);
303 out
<< *driver
.program_
;
305 std::string
code(str
.str());
306 CYUTF8String
json(Run(pool
, client_
, code
));
307 // XXX: if this fails we should not try to parse it
309 CYExpression
*result(ParseExpression(json
));
313 CYArray
*array(dynamic_cast<CYArray
*>(result
));
317 Output(false, json
, out_
);
318 rl_forced_update_display();
322 // XXX: use an std::set?
323 typedef std::vector
<std::string
> Completions
;
324 Completions completions
;
329 CYForEach (element
, array
->elements_
) {
330 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
331 _assert(string
!= NULL
);
333 std::string completion
;
334 if (string
->size_
!= 0)
335 completion
.assign(string
->value_
, string
->size_
);
336 else if (driver
.mode_
== CYDriver::AutoMessage
)
341 completions
.push_back(completion
);
347 size_t limit(completion
.size()), size(common
.size());
349 common
= common
.substr(0, limit
);
352 for (limit
= 0; limit
!= size
; ++limit
)
353 if (common
[limit
] != completion
[limit
])
356 common
= common
.substr(0, limit
);
360 size_t count(completions
.size());
364 size_t colon(common
.find(':'));
365 if (colon
!= std::string::npos
)
366 common
= common
.substr(0, colon
+ 1);
367 if (completions
.size() == 1)
370 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
372 results
[0] = strdup(common
.c_str());
374 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
375 results
[++index
] = strdup(i
->c_str());
376 results
[count
+ 1] = NULL
;
381 // need char *, not const char *
382 static char name_
[] = "cycript";
383 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
385 static void Console(CYOptions
&options
) {
389 if (const char *username
= getenv("LOGNAME"))
390 passwd
= getpwnam(username
);
392 passwd
= getpwuid(getuid());
394 const char *basedir(apr_psprintf(pool
, "%s/.cycript", passwd
->pw_dir
));
395 const char *histfile(apr_psprintf(pool
, "%s/history", basedir
));
399 rl_readline_name
= name_
;
401 mkdir(basedir
, 0700);
402 read_history(histfile
);
411 // rl_completer_word_break_characters is broken in libedit
412 rl_basic_word_break_characters
= break_
;
414 rl_completer_word_break_characters
= break_
;
415 rl_attempted_completion_function
= &Complete
;
416 rl_bind_key('\t', rl_complete
);
418 struct sigaction action
;
419 sigemptyset(&action
.sa_mask
);
420 action
.sa_handler
= &sigint
;
422 sigaction(SIGINT
, &action
, NULL
);
426 std::vector
<std::string
> lines
;
429 const char *prompt("cy# ");
431 if (setjmp(ctrlc_
) != 0) {
439 char *line(readline(prompt
));
448 if (line
[0] == '?') {
449 std::string
data(line
+ 1);
450 if (data
== "bypass") {
452 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
453 } else if (data
== "debug") {
455 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
456 } else if (data
== "expand") {
458 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
459 } else if (data
== "syntax") {
461 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
471 char *begin(line
), *end(line
+ strlen(line
));
472 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
474 lines
.push_back(begin
);
478 lines
.push_back(begin
);
489 std::istringstream
stream(command_
);
490 CYDriver
driver(stream
);
492 cy::parser
parser(driver
);
493 Setup(driver
, parser
);
495 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
496 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
497 cy::position
begin(error
->location_
.begin
);
498 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
499 cy::position
end(error
->location_
.end
);
501 if (begin
.line
!= lines
.size()) {
503 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
507 for (size_t i(0); i
!= begin
.column
; ++i
)
509 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
511 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
513 std::cerr
<< std::endl
;
516 std::cerr
<< error
->message_
<< std::endl
;
518 add_history(command_
.c_str());
524 driver
.errors_
.clear();
531 if (driver
.program_
== NULL
)
537 std::ostringstream str
;
538 CYOutput
out(str
, options
);
539 Setup(out
, driver
, options
);
540 out
<< *driver
.program_
;
545 add_history(command_
.c_str());
549 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
550 std::cout
<< std::endl
;
553 Run(client_
, syntax
, code
, out_
, expand
);
556 if (append_history$
!= NULL
) {
557 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
558 (*append_history$
)(histlines
, histfile
);
560 write_history(histfile
);
566 static void *Map(const char *path
, size_t *psize
) {
568 _syscall(fd
= open(path
, O_RDONLY
));
571 _syscall(fstat(fd
, &stat
));
572 size_t size(stat
.st_size
);
577 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
583 void InjectLibrary(pid_t pid
);
585 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
586 bool tty(isatty(STDIN_FILENO
));
590 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
593 pid_t
pid(_not(pid_t
));
598 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
604 apr_status_t
status(apr_getopt(state
,
618 "usage: cycript [-c]"
622 " [<script> [<arg>...]]\n"
636 else if (strcmp(arg
, "rename") == 0)
637 options
.verbose_
= true;
639 else if (strcmp(arg
, "bison") == 0)
643 fprintf(stderr
, "invalid name for -g\n");
650 else if (strcmp(arg
, "minify") == 0)
653 fprintf(stderr
, "invalid name for -n\n");
660 size_t size(strlen(arg
));
663 pid
= strtoul(arg
, &end
, 0);
664 if (arg
+ size
!= end
) {
665 // XXX: arg needs to be escaped in some horrendous way of doom
666 const char *command(apr_psprintf(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg
));
668 if (FILE *pids
= popen(command
, "r")) {
673 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
678 if (size
== sizeof(value
)) {
688 if (value
[size
- 1] == '\n') {
694 size
= strlen(value
);
695 pid
= strtoul(value
, &end
, 0);
696 if (value
+ size
!= end
) fail
:
698 _syscall(pclose(pids
));
701 if (pid
== _not(pid_t
)) {
702 fprintf(stderr
, "invalid pid for -p\n");
719 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
720 fprintf(stderr
, "-p cannot set argv\n");
724 if (pid
!= _not(pid_t
) && compile
) {
725 fprintf(stderr
, "-p conflicts with -c\n");
734 // XXX: const_cast?! wtf gcc :(
735 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
738 if (strcmp(script
, "-") == 0)
743 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
744 fprintf(stderr
, "non-terminal attaching to remote console\n");
750 if (pid
== _not(pid_t
))
753 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
754 struct sockaddr_un address
;
755 memset(&address
, 0, sizeof(address
));
756 address
.sun_family
= AF_UNIX
;
758 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
760 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
761 _syscall(chmod(address
.sun_path
, 0777));
764 _syscall(listen(server
, 1));
766 client_
= _syscall(accept(server
, NULL
, NULL
));
769 unlink(address
.sun_path
);
773 _syscall(close(server
));
781 if (script
== NULL
&& tty
)
787 std::istream
*indirect
;
789 if (script
== NULL
) {
792 indirect
= &std::cin
;
795 start
= reinterpret_cast<char *>(Map(script
, &size
));
798 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
801 if (void *line
= memchr(start
, '\n', end
- start
))
802 start
= reinterpret_cast<char *>(line
);
810 CYStream
direct(start
, end
);
811 std::istream
&stream(indirect
== NULL
? direct
: *indirect
);
812 CYDriver
driver(stream
, script
?: "<stdin>");
814 cy::parser
parser(driver
);
815 Setup(driver
, parser
);
817 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
818 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
819 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
820 } else if (driver
.program_
!= NULL
)
822 // XXX: this code means that you can't pipe to another process
823 std::string
code(start
, end
-start
);
824 Run(client_
, false, code
, &std::cout
);
826 std::ostringstream str
;
827 CYOutput
out(str
, options
);
828 Setup(out
, driver
, options
);
829 out
<< *driver
.program_
;
830 std::string
code(str
.str());
834 Run(client_
, false, code
, &std::cout
);
841 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
842 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
844 if (status
!= APR_SUCCESS
) {
845 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
848 return Main(argc
, argv
, envp
);
849 } catch (const CYException
&error
) {
851 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));