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"
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>
63 #include <apr_pools.h>
64 #include <apr_strings.h>
68 #include "Replace.hpp"
69 #include "Display.hpp"
71 static volatile enum {
79 static jmp_buf ctrlc_
;
81 static void sigint(int) {
102 void Setup(CYDriver
&driver
, cy::parser
&parser
) {
105 parser
.set_debug_level(1);
108 driver
.strict_
= true;
111 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
) {
112 out
.pretty_
= pretty_
;
113 CYContext
context(options
);
114 driver
.program_
->Replace(context
);
117 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
124 json
= CYExecute(pool
, code
);
136 CYSendAll(client
, &size
, sizeof(size
));
137 CYSendAll(client
, code
.data
, code
.size
);
139 CYRecvAll(client
, &size
, sizeof(size
));
140 if (size
== _not(uint32_t))
143 char *temp(new(pool
) char[size
+ 1]);
144 CYRecvAll(client
, temp
, size
);
151 return CYUTF8String(json
, size
);
154 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
155 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
158 static std::ostream
*out_
;
160 static void Write(bool syntax
, const char *data
, size_t size
, std::ostream
&out
) {
162 CYLexerHighlight(data
, size
, out
);
164 out
.write(data
, size
);
167 static void Output(bool syntax
, CYUTF8String json
, std::ostream
*out
, bool expand
= false) {
168 const char *data(json
.data
);
169 size_t size(json
.size
);
171 if (data
== NULL
|| out
== NULL
)
175 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
176 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
178 Write(syntax
, data
, size
, *out
);
179 else for (size_t i(0); i
!= size
; ++i
)
182 else switch(data
[++i
]) {
183 case '\0': goto done
;
184 case '\\': *out
<< '\\'; break;
185 case '\'': *out
<< '\''; break;
186 case '"': *out
<< '"'; break;
187 case 'b': *out
<< '\b'; break;
188 case 'f': *out
<< '\f'; break;
189 case 'n': *out
<< '\n'; break;
190 case 'r': *out
<< '\r'; break;
191 case 't': *out
<< '\t'; break;
192 case 'v': *out
<< '\v'; break;
193 default: *out
<< '\\'; --i
; break;
200 static void Run(int client
, bool syntax
, const char *data
, size_t size
, std::ostream
*out
= NULL
, bool expand
= false) {
202 Output(syntax
, Run(pool
, client
, CYUTF8String(data
, size
)), out
, expand
);
205 static void Run(int client
, bool syntax
, std::string
&code
, std::ostream
*out
= NULL
, bool expand
= false) {
206 Run(client
, syntax
, code
.c_str(), code
.size(), out
, expand
);
209 int (*append_history$
)(int, const char *);
211 static std::string command_
;
213 static CYExpression
*ParseExpression(CYUTF8String code
) {
214 std::stringstream stream
;
215 stream
<< '(' << code
<< ')';
216 CYDriver
driver(stream
);
218 cy::parser
parser(driver
);
219 Setup(driver
, parser
);
221 if (parser
.parse() != 0 || !driver
.errors_
.empty())
225 CYContext
context(options
);
227 // XXX: this could be replaced with a CYStatement::Primitive()
228 if (CYExpress
*express
= dynamic_cast<CYExpress
*>(driver
.program_
->statements_
))
229 return express
->expression_
->Primitive(context
);
236 static char **Complete(const char *word
, int start
, int end
) {
237 rl_attempted_completion_over
= TRUE
;
241 std::string
line(rl_line_buffer
, start
);
242 std::istringstream
stream(command_
+ line
);
243 CYDriver
driver(stream
);
247 cy::parser
parser(driver
);
248 Setup(driver
, parser
);
250 if (parser
.parse() != 0 || !driver
.errors_
.empty())
253 if (driver
.mode_
== CYDriver::AutoNone
)
256 CYExpression
*expression
;
259 CYContext
context(options
);
261 std::ostringstream prefix
;
263 switch (driver
.mode_
) {
264 case CYDriver::AutoPrimary
:
265 expression
= $
CYThis();
268 case CYDriver::AutoDirect
:
269 expression
= driver
.context_
;
272 case CYDriver::AutoIndirect
:
273 expression
= $
CYIndirect(driver
.context_
);
276 case CYDriver::AutoMessage
: {
277 CYDriver::Context
&thing(driver
.contexts_
.back());
278 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
279 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
280 prefix
<< (*part
)->word_
<< ':';
287 std::string
begin(prefix
.str());
289 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
290 " function(object, prefix, word) {\n"
292 " var before = prefix.length;\n"
294 " var entire = prefix.length;\n"
295 " for (name in object)\n"
296 " if (name.substring(0, entire) == prefix)\n"
297 " names.push(name.substr(before));\n"
300 ), expression
, $
S(begin
.c_str()), $
S(word
))));
302 driver
.program_
->Replace(context
);
304 std::ostringstream str
;
305 CYOutput
out(str
, options
);
306 out
<< *driver
.program_
;
308 std::string
code(str
.str());
309 CYUTF8String
json(Run(pool
, client_
, code
));
310 // XXX: if this fails we should not try to parse it
312 CYExpression
*result(ParseExpression(json
));
316 CYArray
*array(dynamic_cast<CYArray
*>(result
));
320 Output(false, json
, out_
);
321 rl_forced_update_display();
325 // XXX: use an std::set?
326 typedef std::vector
<std::string
> Completions
;
327 Completions completions
;
332 CYForEach (element
, array
->elements_
) {
333 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
334 _assert(string
!= NULL
);
336 std::string completion
;
337 if (string
->size_
!= 0)
338 completion
.assign(string
->value_
, string
->size_
);
339 else if (driver
.mode_
== CYDriver::AutoMessage
)
344 completions
.push_back(completion
);
350 size_t limit(completion
.size()), size(common
.size());
352 common
= common
.substr(0, limit
);
355 for (limit
= 0; limit
!= size
; ++limit
)
356 if (common
[limit
] != completion
[limit
])
359 common
= common
.substr(0, limit
);
363 size_t count(completions
.size());
367 size_t colon(common
.find(':'));
368 if (colon
!= std::string::npos
)
369 common
= common
.substr(0, colon
+ 1);
370 if (completions
.size() == 1)
373 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
375 results
[0] = strdup(common
.c_str());
377 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
378 results
[++index
] = strdup(i
->c_str());
379 results
[count
+ 1] = NULL
;
384 // need char *, not const char *
385 static char name_
[] = "cycript";
386 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
388 static void Console(CYOptions
&options
) {
392 if (const char *username
= getenv("LOGNAME"))
393 passwd
= getpwnam(username
);
395 passwd
= getpwuid(getuid());
397 const char *basedir(pool
.strcat(passwd
->pw_dir
, "/.cycript", NULL
));
398 const char *histfile(pool
.strcat(basedir
, "/history", NULL
));
402 rl_readline_name
= name_
;
404 mkdir(basedir
, 0700);
405 read_history(histfile
);
414 // rl_completer_word_break_characters is broken in libedit
415 rl_basic_word_break_characters
= break_
;
417 rl_completer_word_break_characters
= break_
;
418 rl_attempted_completion_function
= &Complete
;
419 rl_bind_key('\t', rl_complete
);
421 struct sigaction action
;
422 sigemptyset(&action
.sa_mask
);
423 action
.sa_handler
= &sigint
;
425 sigaction(SIGINT
, &action
, NULL
);
429 std::vector
<std::string
> lines
;
432 const char *prompt("cy# ");
434 if (setjmp(ctrlc_
) != 0) {
442 #if RL_READLINE_VERSION >= 0x0600
444 rl_prep_term_function
= CYDisplayStart
;
445 rl_redisplay_function
= CYDisplayUpdate
;
446 rl_deprep_term_function
= CYDisplayFinish
;
448 rl_prep_term_function
= rl_prep_terminal
;
449 rl_redisplay_function
= rl_redisplay
;
450 rl_deprep_term_function
= rl_deprep_terminal
;
455 char *line(readline(prompt
));
465 if (line
[0] == '?') {
466 std::string
data(line
+ 1);
467 if (data
== "bypass") {
469 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
470 } else if (data
== "debug") {
472 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
473 } else if (data
== "expand") {
475 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
476 } else if (data
== "syntax") {
478 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
488 char *begin(line
), *end(line
+ strlen(line
));
489 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
491 lines
.push_back(begin
);
495 lines
.push_back(begin
);
506 std::istringstream
stream(command_
);
507 CYDriver
driver(stream
);
509 cy::parser
parser(driver
);
510 Setup(driver
, parser
);
512 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
513 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
514 cy::position
begin(error
->location_
.begin
);
515 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
516 cy::position
end(error
->location_
.end
);
518 if (begin
.line
!= lines
.size()) {
520 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
524 for (size_t i(0); i
!= begin
.column
; ++i
)
526 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
528 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
530 std::cerr
<< std::endl
;
533 std::cerr
<< error
->message_
<< std::endl
;
535 add_history(command_
.c_str());
541 driver
.errors_
.clear();
548 if (driver
.program_
== NULL
)
554 std::ostringstream str
;
555 CYOutput
out(str
, options
);
556 Setup(out
, driver
, options
);
557 out
<< *driver
.program_
;
562 add_history(command_
.c_str());
566 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
567 std::cout
<< std::endl
;
570 Run(client_
, syntax
, code
, out_
, expand
);
573 if (append_history$
!= NULL
) {
574 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
575 (*append_history$
)(histlines
, histfile
);
577 write_history(histfile
);
583 static void *Map(const char *path
, size_t *psize
) {
585 _syscall(fd
= open(path
, O_RDONLY
));
588 _syscall(fstat(fd
, &stat
));
589 size_t size(stat
.st_size
);
594 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
600 void InjectLibrary(pid_t pid
);
602 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
603 _aprcall(apr_initialize());
606 apr_pool_create(&pool
, NULL
);
608 bool tty(isatty(STDIN_FILENO
));
612 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
615 pid_t
pid(_not(pid_t
));
619 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
625 apr_status_t
status(apr_getopt(state
,
639 "usage: cycript [-c]"
643 " [<script> [<arg>...]]\n"
657 else if (strcmp(arg
, "rename") == 0)
658 options
.verbose_
= true;
660 else if (strcmp(arg
, "bison") == 0)
664 fprintf(stderr
, "invalid name for -g\n");
671 else if (strcmp(arg
, "minify") == 0)
674 fprintf(stderr
, "invalid name for -n\n");
681 size_t size(strlen(arg
));
684 pid
= strtoul(arg
, &end
, 0);
685 if (arg
+ size
!= end
) {
686 // XXX: arg needs to be escaped in some horrendous way of doom
687 const char *command(apr_pstrcat(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^", arg
, " /{s/^[^ ]* //;q;};};d'", NULL
));
689 if (FILE *pids
= popen(command
, "r")) {
694 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
699 if (size
== sizeof(value
)) {
709 if (value
[size
- 1] == '\n') {
715 size
= strlen(value
);
716 pid
= strtoul(value
, &end
, 0);
717 if (value
+ size
!= end
) fail
:
719 _syscall(pclose(pids
));
722 if (pid
== _not(pid_t
)) {
723 fprintf(stderr
, "invalid pid for -p\n");
740 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
741 fprintf(stderr
, "-p cannot set argv\n");
745 if (pid
!= _not(pid_t
) && compile
) {
746 fprintf(stderr
, "-p conflicts with -c\n");
755 // XXX: const_cast?! wtf gcc :(
756 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
759 if (strcmp(script
, "-") == 0)
764 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
765 fprintf(stderr
, "non-terminal attaching to remote console\n");
771 if (pid
== _not(pid_t
))
774 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
775 struct sockaddr_un address
;
776 memset(&address
, 0, sizeof(address
));
777 address
.sun_family
= AF_UNIX
;
779 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
781 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
782 _syscall(chmod(address
.sun_path
, 0777));
785 _syscall(listen(server
, 1));
787 client_
= _syscall(accept(server
, NULL
, NULL
));
790 unlink(address
.sun_path
);
794 _syscall(close(server
));
802 if (script
== NULL
&& tty
)
808 std::istream
*indirect
;
810 if (script
== NULL
) {
813 indirect
= &std::cin
;
816 start
= reinterpret_cast<char *>(Map(script
, &size
));
819 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
822 if (void *line
= memchr(start
, '\n', end
- start
))
823 start
= reinterpret_cast<char *>(line
);
831 CYStream
direct(start
, end
);
832 std::istream
&stream(indirect
== NULL
? direct
: *indirect
);
833 CYDriver
driver(stream
, script
?: "<stdin>");
835 cy::parser
parser(driver
);
836 Setup(driver
, parser
);
838 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
839 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
840 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
841 } else if (driver
.program_
!= NULL
)
843 // XXX: this code means that you can't pipe to another process
844 std::string
code(start
, end
-start
);
845 Run(client_
, false, code
, &std::cout
);
847 std::ostringstream str
;
848 CYOutput
out(str
, options
);
849 Setup(out
, driver
, options
);
850 out
<< *driver
.program_
;
851 std::string
code(str
.str());
855 Run(client_
, false, code
, &std::cout
);
859 apr_pool_destroy(pool
);
864 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
865 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
867 if (status
!= APR_SUCCESS
) {
868 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
871 return Main(argc
, argv
, envp
);
872 } catch (const CYException
&error
) {
874 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));