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()));
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())
217 CYContext
context(options
);
219 // XXX: this could be replaced with a CYStatement::Primitive()
220 if (CYExpress
*express
= dynamic_cast<CYExpress
*>(driver
.program_
->statements_
))
221 return express
->expression_
->Primitive(context
);
228 static char **Complete(const char *word
, int start
, int end
) {
229 rl_attempted_completion_over
= TRUE
;
233 cy::parser
parser(driver
);
234 Setup(driver
, parser
);
236 std::string
line(rl_line_buffer
, start
);
237 std::string
command(command_
+ line
);
239 driver
.data_
= command
.c_str();
240 driver
.size_
= command
.size();
244 if (parser
.parse() != 0 || !driver
.errors_
.empty())
247 if (driver
.mode_
== CYDriver::AutoNone
)
250 CYExpression
*expression
;
253 CYContext
context(options
);
255 std::ostringstream prefix
;
257 switch (driver
.mode_
) {
258 case CYDriver::AutoPrimary
:
259 expression
= $
CYThis();
262 case CYDriver::AutoDirect
:
263 expression
= driver
.context_
;
266 case CYDriver::AutoIndirect
:
267 expression
= $
CYIndirect(driver
.context_
);
270 case CYDriver::AutoMessage
: {
271 CYDriver::Context
&thing(driver
.contexts_
.back());
272 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
273 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
274 prefix
<< (*part
)->word_
<< ':';
281 std::string
begin(prefix
.str());
283 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
284 " function(object, prefix, word) {\n"
286 " var pattern = '^' + prefix + word;\n"
287 " var length = prefix.length;\n"
288 " for (name in object)\n"
289 " if (name.match(pattern) != null)\n"
290 " names.push(name.substr(length));\n"
293 ), expression
, $
S(begin
.c_str()), $
S(word
))));
295 driver
.program_
->Replace(context
);
297 std::ostringstream str
;
298 CYOutput
out(str
, options
);
299 out
<< *driver
.program_
;
301 std::string
code(str
.str());
302 CYUTF8String
json(Run(pool
, client_
, code
));
304 CYExpression
*result(ParseExpression(json
));
308 CYArray
*array(dynamic_cast<CYArray
*>(result
));
311 fprintf(fout_
, "\n");
313 rl_forced_update_display();
317 // XXX: use an std::set?
318 typedef std::vector
<std::string
> Completions
;
319 Completions completions
;
324 CYForEach (element
, array
->elements_
) {
325 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
326 _assert(string
!= NULL
);
328 std::string completion
;
329 if (string
->size_
!= 0)
330 completion
.assign(string
->value_
, string
->size_
);
331 else if (driver
.mode_
== CYDriver::AutoMessage
)
336 completions
.push_back(completion
);
342 size_t limit(completion
.size()), size(common
.size());
344 common
= common
.substr(0, limit
);
347 for (limit
= 0; limit
!= size
; ++limit
)
348 if (common
[limit
] != completion
[limit
])
351 common
= common
.substr(0, limit
);
355 size_t count(completions
.size());
359 size_t colon(common
.find(':'));
360 if (colon
!= std::string::npos
)
361 common
= common
.substr(0, colon
+ 1);
362 if (completions
.size() == 1)
365 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
367 results
[0] = strdup(common
.c_str());
369 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
370 results
[++index
] = strdup(i
->c_str());
371 results
[count
+ 1] = NULL
;
376 // need char *, not const char *
377 static char name_
[] = "cycript";
378 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
380 static void Console(CYOptions
&options
) {
384 if (const char *username
= getenv("LOGNAME"))
385 passwd
= getpwnam(username
);
387 passwd
= getpwuid(getuid());
389 const char *basedir(apr_psprintf(pool
, "%s/.cycript", passwd
->pw_dir
));
390 const char *histfile(apr_psprintf(pool
, "%s/history", basedir
));
394 rl_readline_name
= name_
;
396 mkdir(basedir
, 0700);
397 read_history(histfile
);
405 // rl_completer_word_break_characters is broken in libedit
406 rl_basic_word_break_characters
= break_
;
408 rl_completer_word_break_characters
= break_
;
409 rl_attempted_completion_function
= &Complete
;
410 rl_bind_key('\t', rl_complete
);
412 struct sigaction action
;
413 sigemptyset(&action
.sa_mask
);
414 action
.sa_handler
= &sigint
;
416 sigaction(SIGINT
, &action
, NULL
);
420 std::vector
<std::string
> lines
;
423 const char *prompt("cy# ");
425 if (setjmp(ctrlc_
) != 0) {
434 char *line(readline(prompt
));
443 if (line
[0] == '?') {
444 std::string
data(line
+ 1);
445 if (data
== "bypass") {
447 fprintf(fout_
, "bypass == %s\n", bypass
? "true" : "false");
449 } else if (data
== "debug") {
451 fprintf(fout_
, "debug == %s\n", debug
? "true" : "false");
453 } else if (data
== "expand") {
455 fprintf(fout_
, "expand == %s\n", expand
? "true" : "false");
466 char *begin(line
), *end(line
+ strlen(line
));
467 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
469 lines
.push_back(begin
);
473 lines
.push_back(begin
);
484 cy::parser
parser(driver
);
485 Setup(driver
, parser
);
487 driver
.data_
= command_
.c_str();
488 driver
.size_
= command_
.size();
490 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
491 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
492 cy::position
begin(error
->location_
.begin
);
493 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
494 cy::position
end(error
->location_
.end
);
496 if (begin
.line
!= lines
.size()) {
498 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
502 for (size_t i(0); i
!= begin
.column
; ++i
)
504 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
506 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
508 std::cerr
<< std::endl
;
511 std::cerr
<< error
->message_
<< std::endl
;
513 add_history(command_
.c_str());
519 driver
.errors_
.clear();
526 if (driver
.program_
== NULL
)
532 std::ostringstream str
;
533 CYOutput
out(str
, options
);
534 Setup(out
, driver
, options
);
535 out
<< *driver
.program_
;
540 add_history(command_
.c_str());
544 std::cout
<< code
<< std::endl
;
546 Run(client_
, code
, fout_
, expand
);
549 if (append_history$
!= NULL
) {
550 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
551 (*append_history$
)(histlines
, histfile
);
553 write_history(histfile
);
560 static void *Map(const char *path
, size_t *psize
) {
562 _syscall(fd
= open(path
, O_RDONLY
));
565 _syscall(fstat(fd
, &stat
));
566 size_t size(stat
.st_size
);
571 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
577 void InjectLibrary(pid_t pid
);
579 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
580 bool tty(isatty(STDIN_FILENO
));
584 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
587 pid_t
pid(_not(pid_t
));
592 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
598 apr_status_t
status(apr_getopt(state
,
612 "usage: cycript [-c]"
616 " [<script> [<arg>...]]\n"
630 else if (strcmp(arg
, "rename") == 0)
631 options
.verbose_
= true;
633 else if (strcmp(arg
, "bison") == 0)
637 fprintf(stderr
, "invalid name for -g\n");
644 else if (strcmp(arg
, "minify") == 0)
647 fprintf(stderr
, "invalid name for -n\n");
654 size_t size(strlen(arg
));
657 pid
= strtoul(arg
, &end
, 0);
658 if (arg
+ size
!= end
) {
659 // XXX: arg needs to be escaped in some horrendous way of doom
660 const char *command(apr_psprintf(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg
));
662 if (FILE *pids
= popen(command
, "r")) {
667 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
672 if (size
== sizeof(value
)) {
682 if (value
[size
- 1] == '\n') {
688 size
= strlen(value
);
689 pid
= strtoul(value
, &end
, 0);
690 if (value
+ size
!= end
) fail
:
692 _syscall(pclose(pids
));
695 if (pid
== _not(pid_t
)) {
696 fprintf(stderr
, "invalid pid for -p\n");
713 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
714 fprintf(stderr
, "-p cannot set argv\n");
718 if (pid
!= _not(pid_t
) && compile
) {
719 fprintf(stderr
, "-p conflicts with -c\n");
728 // XXX: const_cast?! wtf gcc :(
729 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
732 if (strcmp(script
, "-") == 0)
737 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
738 fprintf(stderr
, "non-terminal attaching to remote console\n");
744 if (pid
== _not(pid_t
))
747 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
748 struct sockaddr_un address
;
749 memset(&address
, 0, sizeof(address
));
750 address
.sun_family
= AF_UNIX
;
752 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
754 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
755 _syscall(chmod(address
.sun_path
, 0777));
758 _syscall(listen(server
, 1));
760 client_
= _syscall(accept(server
, NULL
, NULL
));
763 unlink(address
.sun_path
);
767 _syscall(close(server
));
775 if (script
== NULL
&& tty
)
779 CYDriver
driver(script
?: "<stdin>");
780 cy::parser
parser(driver
);
781 Setup(driver
, parser
);
785 if (script
== NULL
) {
789 driver
.file_
= stdin
;
792 start
= reinterpret_cast<char *>(Map(script
, &size
));
795 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
798 if (void *line
= memchr(start
, '\n', end
- start
))
799 start
= reinterpret_cast<char *>(line
);
804 driver
.data_
= start
;
805 driver
.size_
= end
- start
;
808 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
809 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
810 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
811 } else if (driver
.program_
!= NULL
)
813 std::string
code(start
, end
-start
);
814 Run(client_
, code
, stdout
);
816 std::ostringstream str
;
817 CYOutput
out(str
, options
);
818 Setup(out
, driver
, options
);
819 out
<< *driver
.program_
;
820 std::string
code(str
.str());
824 Run(client_
, code
, stdout
);
831 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
832 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
834 if (status
!= APR_SUCCESS
) {
835 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
838 return Main(argc
, argv
, envp
);
839 } catch (const CYException
&error
) {
841 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));