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"
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(apr_psprintf(pool
, "%s/.cycript", passwd
->pw_dir
));
396 const char *histfile(apr_psprintf(pool
, "%s/history", basedir
));
400 rl_readline_name
= name_
;
402 #if RL_READLINE_VERSION >= 0x0600
403 rl_prep_term_function
= CYDisplayStart
;
404 rl_redisplay_function
= CYDisplayUpdate
;
405 rl_deprep_term_function
= CYDisplayFinish
;
408 mkdir(basedir
, 0700);
409 read_history(histfile
);
418 // rl_completer_word_break_characters is broken in libedit
419 rl_basic_word_break_characters
= break_
;
421 rl_completer_word_break_characters
= break_
;
422 rl_attempted_completion_function
= &Complete
;
423 rl_bind_key('\t', rl_complete
);
425 struct sigaction action
;
426 sigemptyset(&action
.sa_mask
);
427 action
.sa_handler
= &sigint
;
429 sigaction(SIGINT
, &action
, NULL
);
433 std::vector
<std::string
> lines
;
436 const char *prompt("cy# ");
438 if (setjmp(ctrlc_
) != 0) {
446 char *line(readline(prompt
));
455 if (line
[0] == '?') {
456 std::string
data(line
+ 1);
457 if (data
== "bypass") {
459 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
460 } else if (data
== "debug") {
462 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
463 } else if (data
== "expand") {
465 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
466 } else if (data
== "syntax") {
468 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
478 char *begin(line
), *end(line
+ strlen(line
));
479 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
481 lines
.push_back(begin
);
485 lines
.push_back(begin
);
496 std::istringstream
stream(command_
);
497 CYDriver
driver(stream
);
499 cy::parser
parser(driver
);
500 Setup(driver
, parser
);
502 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
503 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
504 cy::position
begin(error
->location_
.begin
);
505 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
506 cy::position
end(error
->location_
.end
);
508 if (begin
.line
!= lines
.size()) {
510 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
514 for (size_t i(0); i
!= begin
.column
; ++i
)
516 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
518 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
520 std::cerr
<< std::endl
;
523 std::cerr
<< error
->message_
<< std::endl
;
525 add_history(command_
.c_str());
531 driver
.errors_
.clear();
538 if (driver
.program_
== NULL
)
544 std::ostringstream str
;
545 CYOutput
out(str
, options
);
546 Setup(out
, driver
, options
);
547 out
<< *driver
.program_
;
552 add_history(command_
.c_str());
556 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
557 std::cout
<< std::endl
;
560 Run(client_
, syntax
, code
, out_
, expand
);
563 if (append_history$
!= NULL
) {
564 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
565 (*append_history$
)(histlines
, histfile
);
567 write_history(histfile
);
573 static void *Map(const char *path
, size_t *psize
) {
575 _syscall(fd
= open(path
, O_RDONLY
));
578 _syscall(fstat(fd
, &stat
));
579 size_t size(stat
.st_size
);
584 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
590 void InjectLibrary(pid_t pid
);
592 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
593 bool tty(isatty(STDIN_FILENO
));
597 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
600 pid_t
pid(_not(pid_t
));
605 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
611 apr_status_t
status(apr_getopt(state
,
625 "usage: cycript [-c]"
629 " [<script> [<arg>...]]\n"
643 else if (strcmp(arg
, "rename") == 0)
644 options
.verbose_
= true;
646 else if (strcmp(arg
, "bison") == 0)
650 fprintf(stderr
, "invalid name for -g\n");
657 else if (strcmp(arg
, "minify") == 0)
660 fprintf(stderr
, "invalid name for -n\n");
667 size_t size(strlen(arg
));
670 pid
= strtoul(arg
, &end
, 0);
671 if (arg
+ size
!= end
) {
672 // XXX: arg needs to be escaped in some horrendous way of doom
673 const char *command(apr_psprintf(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg
));
675 if (FILE *pids
= popen(command
, "r")) {
680 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
685 if (size
== sizeof(value
)) {
695 if (value
[size
- 1] == '\n') {
701 size
= strlen(value
);
702 pid
= strtoul(value
, &end
, 0);
703 if (value
+ size
!= end
) fail
:
705 _syscall(pclose(pids
));
708 if (pid
== _not(pid_t
)) {
709 fprintf(stderr
, "invalid pid for -p\n");
726 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
727 fprintf(stderr
, "-p cannot set argv\n");
731 if (pid
!= _not(pid_t
) && compile
) {
732 fprintf(stderr
, "-p conflicts with -c\n");
741 // XXX: const_cast?! wtf gcc :(
742 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
745 if (strcmp(script
, "-") == 0)
750 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
751 fprintf(stderr
, "non-terminal attaching to remote console\n");
757 if (pid
== _not(pid_t
))
760 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
761 struct sockaddr_un address
;
762 memset(&address
, 0, sizeof(address
));
763 address
.sun_family
= AF_UNIX
;
765 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
767 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
768 _syscall(chmod(address
.sun_path
, 0777));
771 _syscall(listen(server
, 1));
773 client_
= _syscall(accept(server
, NULL
, NULL
));
776 unlink(address
.sun_path
);
780 _syscall(close(server
));
788 if (script
== NULL
&& tty
)
794 std::istream
*indirect
;
796 if (script
== NULL
) {
799 indirect
= &std::cin
;
802 start
= reinterpret_cast<char *>(Map(script
, &size
));
805 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
808 if (void *line
= memchr(start
, '\n', end
- start
))
809 start
= reinterpret_cast<char *>(line
);
817 CYStream
direct(start
, end
);
818 std::istream
&stream(indirect
== NULL
? direct
: *indirect
);
819 CYDriver
driver(stream
, script
?: "<stdin>");
821 cy::parser
parser(driver
);
822 Setup(driver
, parser
);
824 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
825 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
826 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
827 } else if (driver
.program_
!= NULL
)
829 // XXX: this code means that you can't pipe to another process
830 std::string
code(start
, end
-start
);
831 Run(client_
, false, code
, &std::cout
);
833 std::ostringstream str
;
834 CYOutput
out(str
, options
);
835 Setup(out
, driver
, options
);
836 out
<< *driver
.program_
;
837 std::string
code(str
.str());
841 Run(client_
, false, code
, &std::cout
);
848 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
849 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
851 if (status
!= APR_SUCCESS
) {
852 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
855 return Main(argc
, argv
, envp
);
856 } catch (const CYException
&error
) {
858 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));