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>
66 #include "Replace.hpp"
67 #include "Display.hpp"
69 static volatile enum {
77 static jmp_buf ctrlc_
;
79 static void sigint(int) {
100 void Setup(CYDriver
&driver
, cy::parser
&parser
) {
103 parser
.set_debug_level(1);
106 driver
.strict_
= true;
109 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
) {
110 out
.pretty_
= pretty_
;
111 CYContext
context(options
);
112 driver
.program_
->Replace(context
);
115 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
122 json
= CYExecute(pool
, code
);
134 CYSendAll(client
, &size
, sizeof(size
));
135 CYSendAll(client
, code
.data
, code
.size
);
137 CYRecvAll(client
, &size
, sizeof(size
));
138 if (size
== _not(size_t))
141 char *temp(new(pool
) char[size
+ 1]);
142 CYRecvAll(client
, temp
, size
);
149 return CYUTF8String(json
, size
);
152 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
153 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
156 static std::ostream
*out_
;
158 static void Write(bool syntax
, const char *data
, size_t size
, std::ostream
&out
) {
160 CYLexerHighlight(data
, size
, out
);
162 out
.write(data
, size
);
165 static void Output(bool syntax
, CYUTF8String json
, std::ostream
*out
, bool expand
= false) {
166 const char *data(json
.data
);
167 size_t size(json
.size
);
169 if (data
== NULL
|| out
== NULL
)
173 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
174 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
176 Write(syntax
, data
, size
, *out
);
177 else for (size_t i(0); i
!= size
; ++i
)
180 else switch(data
[++i
]) {
181 case '\0': goto done
;
182 case '\\': *out
<< '\\'; break;
183 case '\'': *out
<< '\''; break;
184 case '"': *out
<< '"'; break;
185 case 'b': *out
<< '\b'; break;
186 case 'f': *out
<< '\f'; break;
187 case 'n': *out
<< '\n'; break;
188 case 'r': *out
<< '\r'; break;
189 case 't': *out
<< '\t'; break;
190 case 'v': *out
<< '\v'; break;
191 default: *out
<< '\\'; --i
; break;
198 static void Run(int client
, bool syntax
, const char *data
, size_t size
, std::ostream
*out
= NULL
, bool expand
= false) {
200 Output(syntax
, Run(pool
, client
, CYUTF8String(data
, size
)), out
, expand
);
203 static void Run(int client
, bool syntax
, std::string
&code
, std::ostream
*out
= NULL
, bool expand
= false) {
204 Run(client
, syntax
, code
.c_str(), code
.size(), out
, expand
);
207 int (*append_history$
)(int, const char *);
209 static std::string command_
;
211 static CYExpression
*ParseExpression(CYUTF8String code
) {
212 std::stringstream stream
;
213 stream
<< '(' << code
<< ')';
214 CYDriver
driver(stream
);
216 cy::parser
parser(driver
);
217 Setup(driver
, parser
);
219 if (parser
.parse() != 0 || !driver
.errors_
.empty())
223 CYContext
context(options
);
225 // XXX: this could be replaced with a CYStatement::Primitive()
226 if (CYExpress
*express
= dynamic_cast<CYExpress
*>(driver
.program_
->statements_
))
227 return express
->expression_
->Primitive(context
);
234 static char **Complete(const char *word
, int start
, int end
) {
235 rl_attempted_completion_over
= TRUE
;
239 std::string
line(rl_line_buffer
, start
);
240 std::istringstream
stream(command_
+ line
);
241 CYDriver
driver(stream
);
245 cy::parser
parser(driver
);
246 Setup(driver
, parser
);
248 if (parser
.parse() != 0 || !driver
.errors_
.empty())
251 if (driver
.mode_
== CYDriver::AutoNone
)
254 CYExpression
*expression
;
257 CYContext
context(options
);
259 std::ostringstream prefix
;
261 switch (driver
.mode_
) {
262 case CYDriver::AutoPrimary
:
263 expression
= $
CYThis();
266 case CYDriver::AutoDirect
:
267 expression
= driver
.context_
;
270 case CYDriver::AutoIndirect
:
271 expression
= $
CYIndirect(driver
.context_
);
274 case CYDriver::AutoMessage
: {
275 CYDriver::Context
&thing(driver
.contexts_
.back());
276 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
277 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
278 prefix
<< (*part
)->word_
<< ':';
285 std::string
begin(prefix
.str());
287 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
288 " function(object, prefix, word) {\n"
290 " var before = prefix.length;\n"
292 " var entire = prefix.length;\n"
293 " for (name in object)\n"
294 " if (name.substring(0, entire) == prefix)\n"
295 " names.push(name.substr(before));\n"
298 ), expression
, $
S(begin
.c_str()), $
S(word
))));
300 driver
.program_
->Replace(context
);
302 std::ostringstream str
;
303 CYOutput
out(str
, options
);
304 out
<< *driver
.program_
;
306 std::string
code(str
.str());
307 CYUTF8String
json(Run(pool
, client_
, code
));
308 // XXX: if this fails we should not try to parse it
310 CYExpression
*result(ParseExpression(json
));
314 CYArray
*array(dynamic_cast<CYArray
*>(result
));
318 Output(false, json
, out_
);
319 rl_forced_update_display();
323 // XXX: use an std::set?
324 typedef std::vector
<std::string
> Completions
;
325 Completions completions
;
330 CYForEach (element
, array
->elements_
) {
331 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
332 _assert(string
!= NULL
);
334 std::string completion
;
335 if (string
->size_
!= 0)
336 completion
.assign(string
->value_
, string
->size_
);
337 else if (driver
.mode_
== CYDriver::AutoMessage
)
342 completions
.push_back(completion
);
348 size_t limit(completion
.size()), size(common
.size());
350 common
= common
.substr(0, limit
);
353 for (limit
= 0; limit
!= size
; ++limit
)
354 if (common
[limit
] != completion
[limit
])
357 common
= common
.substr(0, limit
);
361 size_t count(completions
.size());
365 size_t colon(common
.find(':'));
366 if (colon
!= std::string::npos
)
367 common
= common
.substr(0, colon
+ 1);
368 if (completions
.size() == 1)
371 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
373 results
[0] = strdup(common
.c_str());
375 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
376 results
[++index
] = strdup(i
->c_str());
377 results
[count
+ 1] = NULL
;
382 // need char *, not const char *
383 static char name_
[] = "cycript";
384 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
386 static void Console(CYOptions
&options
) {
390 if (const char *username
= getenv("LOGNAME"))
391 passwd
= getpwnam(username
);
393 passwd
= getpwuid(getuid());
395 const char *basedir(pool
.sprintf("%s/.cycript", passwd
->pw_dir
));
396 const char *histfile(pool
.sprintf("%s/history", basedir
));
400 rl_readline_name
= name_
;
402 mkdir(basedir
, 0700);
403 read_history(histfile
);
412 // rl_completer_word_break_characters is broken in libedit
413 rl_basic_word_break_characters
= break_
;
415 rl_completer_word_break_characters
= break_
;
416 rl_attempted_completion_function
= &Complete
;
417 rl_bind_key('\t', rl_complete
);
419 struct sigaction action
;
420 sigemptyset(&action
.sa_mask
);
421 action
.sa_handler
= &sigint
;
423 sigaction(SIGINT
, &action
, NULL
);
427 std::vector
<std::string
> lines
;
430 const char *prompt("cy# ");
432 if (setjmp(ctrlc_
) != 0) {
440 #if RL_READLINE_VERSION >= 0x0600
442 rl_prep_term_function
= CYDisplayStart
;
443 rl_redisplay_function
= CYDisplayUpdate
;
444 rl_deprep_term_function
= CYDisplayFinish
;
446 rl_prep_term_function
= rl_prep_terminal
;
447 rl_redisplay_function
= rl_redisplay
;
448 rl_deprep_term_function
= rl_deprep_terminal
;
453 char *line(readline(prompt
));
463 if (line
[0] == '?') {
464 std::string
data(line
+ 1);
465 if (data
== "bypass") {
467 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
468 } else if (data
== "debug") {
470 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
471 } else if (data
== "expand") {
473 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
474 } else if (data
== "syntax") {
476 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
486 char *begin(line
), *end(line
+ strlen(line
));
487 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
489 lines
.push_back(begin
);
493 lines
.push_back(begin
);
504 std::istringstream
stream(command_
);
505 CYDriver
driver(stream
);
507 cy::parser
parser(driver
);
508 Setup(driver
, parser
);
510 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
511 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
512 cy::position
begin(error
->location_
.begin
);
513 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
514 cy::position
end(error
->location_
.end
);
516 if (begin
.line
!= lines
.size()) {
518 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
522 for (size_t i(0); i
!= begin
.column
; ++i
)
524 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
526 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
528 std::cerr
<< std::endl
;
531 std::cerr
<< error
->message_
<< std::endl
;
533 add_history(command_
.c_str());
539 driver
.errors_
.clear();
546 if (driver
.program_
== NULL
)
552 std::ostringstream str
;
553 CYOutput
out(str
, options
);
554 Setup(out
, driver
, options
);
555 out
<< *driver
.program_
;
560 add_history(command_
.c_str());
564 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
565 std::cout
<< std::endl
;
568 Run(client_
, syntax
, code
, out_
, expand
);
571 if (append_history$
!= NULL
) {
572 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
573 (*append_history$
)(histlines
, histfile
);
575 write_history(histfile
);
581 static void *Map(const char *path
, size_t *psize
) {
583 _syscall(fd
= open(path
, O_RDONLY
));
586 _syscall(fstat(fd
, &stat
));
587 size_t size(stat
.st_size
);
592 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
598 void InjectLibrary(pid_t pid
);
600 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
601 bool tty(isatty(STDIN_FILENO
));
605 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
608 pid_t
pid(_not(pid_t
));
613 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
619 apr_status_t
status(apr_getopt(state
,
633 "usage: cycript [-c]"
637 " [<script> [<arg>...]]\n"
651 else if (strcmp(arg
, "rename") == 0)
652 options
.verbose_
= true;
654 else if (strcmp(arg
, "bison") == 0)
658 fprintf(stderr
, "invalid name for -g\n");
665 else if (strcmp(arg
, "minify") == 0)
668 fprintf(stderr
, "invalid name for -n\n");
675 size_t size(strlen(arg
));
678 pid
= strtoul(arg
, &end
, 0);
679 if (arg
+ size
!= end
) {
680 // XXX: arg needs to be escaped in some horrendous way of doom
681 const char *command(pool
.sprintf("ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg
));
683 if (FILE *pids
= popen(command
, "r")) {
688 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
693 if (size
== sizeof(value
)) {
703 if (value
[size
- 1] == '\n') {
709 size
= strlen(value
);
710 pid
= strtoul(value
, &end
, 0);
711 if (value
+ size
!= end
) fail
:
713 _syscall(pclose(pids
));
716 if (pid
== _not(pid_t
)) {
717 fprintf(stderr
, "invalid pid for -p\n");
734 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
735 fprintf(stderr
, "-p cannot set argv\n");
739 if (pid
!= _not(pid_t
) && compile
) {
740 fprintf(stderr
, "-p conflicts with -c\n");
749 // XXX: const_cast?! wtf gcc :(
750 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
753 if (strcmp(script
, "-") == 0)
758 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
759 fprintf(stderr
, "non-terminal attaching to remote console\n");
765 if (pid
== _not(pid_t
))
768 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
769 struct sockaddr_un address
;
770 memset(&address
, 0, sizeof(address
));
771 address
.sun_family
= AF_UNIX
;
773 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
775 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
776 _syscall(chmod(address
.sun_path
, 0777));
779 _syscall(listen(server
, 1));
781 client_
= _syscall(accept(server
, NULL
, NULL
));
784 unlink(address
.sun_path
);
788 _syscall(close(server
));
796 if (script
== NULL
&& tty
)
802 std::istream
*indirect
;
804 if (script
== NULL
) {
807 indirect
= &std::cin
;
810 start
= reinterpret_cast<char *>(Map(script
, &size
));
813 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
816 if (void *line
= memchr(start
, '\n', end
- start
))
817 start
= reinterpret_cast<char *>(line
);
825 CYStream
direct(start
, end
);
826 std::istream
&stream(indirect
== NULL
? direct
: *indirect
);
827 CYDriver
driver(stream
, script
?: "<stdin>");
829 cy::parser
parser(driver
);
830 Setup(driver
, parser
);
832 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
833 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
834 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
835 } else if (driver
.program_
!= NULL
)
837 // XXX: this code means that you can't pipe to another process
838 std::string
code(start
, end
-start
);
839 Run(client_
, false, code
, &std::cout
);
841 std::ostringstream str
;
842 CYOutput
out(str
, options
);
843 Setup(out
, driver
, options
);
844 out
<< *driver
.program_
;
845 std::string
code(str
.str());
849 Run(client_
, false, code
, &std::cout
);
856 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
857 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
859 if (status
!= APR_SUCCESS
) {
860 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
863 return Main(argc
, argv
, envp
);
864 } catch (const CYException
&error
) {
866 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));