1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2010 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()));
157 static void Output(CYUTF8String json
, FILE *fout
, bool expand
= false) {
158 const char *data(json
.data
);
159 size_t size(json
.size
);
161 if (data
== NULL
|| fout
== NULL
)
164 if (!expand
|| data
[0] != '"' && data
[0] != '\'')
166 else for (size_t i(0); i
!= size
; ++i
)
168 fputc(data
[i
], fout
);
169 else switch(data
[++i
]) {
170 case '\0': goto done
;
171 case '\\': fputc('\\', fout
); break;
172 case '\'': fputc('\'', fout
); break;
173 case '"': fputc('"', fout
); break;
174 case 'b': fputc('\b', fout
); break;
175 case 'f': fputc('\f', fout
); break;
176 case 'n': fputc('\n', fout
); break;
177 case 'r': fputc('\r', fout
); break;
178 case 't': fputc('\t', fout
); break;
179 case 'v': fputc('\v', fout
); break;
180 default: fputc('\\', fout
); --i
; break;
188 static void Run(int client
, const char *data
, size_t size
, FILE *fout
= NULL
, bool expand
= false) {
190 Output(Run(pool
, client
, CYUTF8String(data
, size
)), fout
, expand
);
193 static void Run(int client
, std::string
&code
, FILE *fout
= NULL
, bool expand
= false) {
194 Run(client
, code
.c_str(), code
.size(), fout
, expand
);
197 int (*append_history$
)(int, const char *);
199 static std::string command_
;
201 static CYExpression
*ParseExpression(CYUTF8String code
) {
202 std::ostringstream str
;
203 str
<< '(' << code
<< ')';
204 std::string
string(str
.str());
207 driver
.data_
= string
.c_str();
208 driver
.size_
= string
.size();
210 cy::parser
parser(driver
);
211 Setup(driver
, parser
);
213 if (parser
.parse() != 0 || !driver
.errors_
.empty())
216 CYExpress
*express(dynamic_cast<CYExpress
*>(driver
.program_
->statements_
));
217 _assert(express
!= NULL
);
218 return express
->expression_
;
223 static char **Complete(const char *word
, int start
, int end
) {
224 rl_attempted_completion_over
= TRUE
;
228 cy::parser
parser(driver
);
229 Setup(driver
, parser
);
231 std::string
line(rl_line_buffer
, start
);
232 std::string
command(command_
+ line
);
234 driver
.data_
= command
.c_str();
235 driver
.size_
= command
.size();
239 if (parser
.parse() != 0 || !driver
.errors_
.empty())
242 if (driver
.mode_
== CYDriver::AutoNone
)
245 CYExpression
*expression
;
248 CYContext
context(options
);
250 std::ostringstream prefix
;
252 switch (driver
.mode_
) {
253 case CYDriver::AutoPrimary
:
254 expression
= $
CYThis();
257 case CYDriver::AutoDirect
:
258 expression
= driver
.context_
;
261 case CYDriver::AutoIndirect
:
262 expression
= $
CYIndirect(driver
.context_
);
265 case CYDriver::AutoMessage
: {
266 CYDriver::Context
&thing(driver
.contexts_
.back());
267 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
268 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
269 prefix
<< (*part
)->word_
<< ':';
276 std::string
begin(prefix
.str());
278 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
279 " function(object, prefix, word) {\n"
281 " var pattern = '^' + prefix + word;\n"
282 " var length = prefix.length;\n"
283 " for (name in object)\n"
284 " if (name.match(pattern) != null)\n"
285 " names.push(name.substr(length));\n"
288 ), expression
, $
S(begin
.c_str()), $
S(word
))));
290 driver
.program_
->Replace(context
);
292 std::ostringstream str
;
293 CYOutput
out(str
, options
);
294 out
<< *driver
.program_
;
296 std::string
code(str
.str());
297 CYUTF8String
json(Run(pool
, client_
, code
));
299 CYExpression
*result(ParseExpression(json
));
303 CYArray
*array(dynamic_cast<CYArray
*>(result
));
306 fprintf(fout_
, "\n");
308 rl_forced_update_display();
312 // XXX: use an std::set?
313 typedef std::vector
<std::string
> Completions
;
314 Completions completions
;
319 CYForEach (element
, array
->elements_
) {
320 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
321 _assert(string
!= NULL
);
323 std::string completion
;
324 if (string
->size_
!= 0)
325 completion
.assign(string
->value_
, string
->size_
);
326 else if (driver
.mode_
== CYDriver::AutoMessage
)
331 completions
.push_back(completion
);
337 size_t limit(completion
.size()), size(common
.size());
339 common
= common
.substr(0, limit
);
342 for (limit
= 0; limit
!= size
; ++limit
)
343 if (common
[limit
] != completion
[limit
])
346 common
= common
.substr(0, limit
);
350 size_t count(completions
.size());
354 size_t colon(common
.find(':'));
355 if (colon
!= std::string::npos
)
356 common
= common
.substr(0, colon
+ 1);
357 if (completions
.size() == 1)
360 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
362 results
[0] = strdup(common
.c_str());
364 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
365 results
[++index
] = strdup(i
->c_str());
366 results
[count
+ 1] = NULL
;
371 // need char *, not const char *
372 static char name_
[] = "cycript";
373 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
375 static void Console(CYOptions
&options
) {
379 if (const char *username
= getenv("LOGNAME"))
380 passwd
= getpwnam(username
);
382 passwd
= getpwuid(getuid());
384 const char *basedir(apr_psprintf(pool
, "%s/.cycript", passwd
->pw_dir
));
385 const char *histfile(apr_psprintf(pool
, "%s/history", basedir
));
389 rl_readline_name
= name_
;
391 mkdir(basedir
, 0700);
392 read_history(histfile
);
400 // rl_completer_word_break_characters is broken in libedit
401 rl_basic_word_break_characters
= break_
;
403 rl_completer_word_break_characters
= break_
;
404 rl_attempted_completion_function
= &Complete
;
405 rl_bind_key('\t', rl_complete
);
407 struct sigaction action
;
408 sigemptyset(&action
.sa_mask
);
409 action
.sa_handler
= &sigint
;
411 sigaction(SIGINT
, &action
, NULL
);
415 std::vector
<std::string
> lines
;
418 const char *prompt("cy# ");
420 if (setjmp(ctrlc_
) != 0) {
429 char *line(readline(prompt
));
438 if (line
[0] == '?') {
439 std::string
data(line
+ 1);
440 if (data
== "bypass") {
442 fprintf(fout_
, "bypass == %s\n", bypass
? "true" : "false");
444 } else if (data
== "debug") {
446 fprintf(fout_
, "debug == %s\n", debug
? "true" : "false");
448 } else if (data
== "expand") {
450 fprintf(fout_
, "expand == %s\n", expand
? "true" : "false");
461 char *begin(line
), *end(line
+ strlen(line
));
462 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
464 lines
.push_back(begin
);
468 lines
.push_back(begin
);
479 cy::parser
parser(driver
);
480 Setup(driver
, parser
);
482 driver
.data_
= command_
.c_str();
483 driver
.size_
= command_
.size();
485 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
486 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
487 cy::position
begin(error
->location_
.begin
);
488 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
489 cy::position
end(error
->location_
.end
);
491 if (begin
.line
!= lines
.size()) {
493 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
497 for (size_t i(0); i
!= begin
.column
; ++i
)
499 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
501 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
503 std::cerr
<< std::endl
;
506 std::cerr
<< error
->message_
<< std::endl
;
508 add_history(command_
.c_str());
514 driver
.errors_
.clear();
521 if (driver
.program_
== NULL
)
527 std::ostringstream str
;
528 CYOutput
out(str
, options
);
529 Setup(out
, driver
, options
);
530 out
<< *driver
.program_
;
535 add_history(command_
.c_str());
539 std::cout
<< code
<< std::endl
;
541 Run(client_
, code
, fout_
, expand
);
544 if (append_history$
!= NULL
) {
545 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
546 (*append_history$
)(histlines
, histfile
);
548 write_history(histfile
);
555 static void *Map(const char *path
, size_t *psize
) {
557 _syscall(fd
= open(path
, O_RDONLY
));
560 _syscall(fstat(fd
, &stat
));
561 size_t size(stat
.st_size
);
566 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
572 void InjectLibrary(pid_t pid
);
574 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
575 bool tty(isatty(STDIN_FILENO
));
579 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
582 pid_t
pid(_not(pid_t
));
587 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
593 apr_status_t
status(apr_getopt(state
,
607 "usage: cycript [-c]"
611 " [<script> [<arg>...]]\n"
625 else if (strcmp(arg
, "rename") == 0)
626 options
.verbose_
= true;
628 else if (strcmp(arg
, "bison") == 0)
632 fprintf(stderr
, "invalid name for -g\n");
639 else if (strcmp(arg
, "minify") == 0)
642 fprintf(stderr
, "invalid name for -n\n");
649 size_t size(strlen(arg
));
652 pid
= strtoul(arg
, &end
, 0);
653 if (arg
+ size
!= end
) {
654 // XXX: arg needs to be escaped in some horrendous way of doom
655 const char *command(apr_psprintf(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg
));
657 if (FILE *pids
= popen(command
, "r")) {
662 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
667 if (size
== sizeof(value
)) {
677 if (value
[size
- 1] == '\n') {
683 size
= strlen(value
);
684 pid
= strtoul(value
, &end
, 0);
685 if (value
+ size
!= end
) fail
:
687 _syscall(pclose(pids
));
690 if (pid
== _not(pid_t
)) {
691 fprintf(stderr
, "invalid pid for -p\n");
708 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
709 fprintf(stderr
, "-p cannot set argv\n");
713 if (pid
!= _not(pid_t
) && compile
) {
714 fprintf(stderr
, "-p conflicts with -c\n");
723 // XXX: const_cast?! wtf gcc :(
724 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
727 if (strcmp(script
, "-") == 0)
732 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
733 fprintf(stderr
, "non-terminal attaching to remote console\n");
739 if (pid
== _not(pid_t
))
742 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
743 struct sockaddr_un address
;
744 memset(&address
, 0, sizeof(address
));
745 address
.sun_family
= AF_UNIX
;
747 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
749 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
750 _syscall(chmod(address
.sun_path
, 0777));
753 _syscall(listen(server
, 1));
755 client_
= _syscall(accept(server
, NULL
, NULL
));
758 unlink(address
.sun_path
);
762 _syscall(close(server
));
770 if (script
== NULL
&& tty
)
774 CYDriver
driver(script
?: "<stdin>");
775 cy::parser
parser(driver
);
776 Setup(driver
, parser
);
780 if (script
== NULL
) {
784 driver
.file_
= stdin
;
787 start
= reinterpret_cast<char *>(Map(script
, &size
));
790 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
793 if (void *line
= memchr(start
, '\n', end
- start
))
794 start
= reinterpret_cast<char *>(line
);
799 driver
.data_
= start
;
800 driver
.size_
= end
- start
;
803 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
804 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
805 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
806 } else if (driver
.program_
!= NULL
)
808 std::string
code(start
, end
-start
);
809 Run(client_
, code
, stdout
);
811 std::ostringstream str
;
812 CYOutput
out(str
, options
);
813 Setup(out
, driver
, options
);
814 out
<< *driver
.program_
;
815 std::string
code(str
.str());
819 Run(client_
, code
, stdout
);
826 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
827 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
829 if (status
!= APR_SUCCESS
) {
830 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
833 return Main(argc
, argv
, envp
);
834 } catch (const CYException
&error
) {
836 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));