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
)
165 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
166 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
169 else for (size_t i(0); i
!= size
; ++i
)
171 fputc(data
[i
], fout
);
172 else switch(data
[++i
]) {
173 case '\0': goto done
;
174 case '\\': fputc('\\', fout
); break;
175 case '\'': fputc('\'', fout
); break;
176 case '"': fputc('"', fout
); break;
177 case 'b': fputc('\b', fout
); break;
178 case 'f': fputc('\f', fout
); break;
179 case 'n': fputc('\n', fout
); break;
180 case 'r': fputc('\r', fout
); break;
181 case 't': fputc('\t', fout
); break;
182 case 'v': fputc('\v', fout
); break;
183 default: fputc('\\', fout
); --i
; break;
191 static void Run(int client
, const char *data
, size_t size
, FILE *fout
= NULL
, bool expand
= false) {
193 Output(Run(pool
, client
, CYUTF8String(data
, size
)), fout
, expand
);
196 static void Run(int client
, std::string
&code
, FILE *fout
= NULL
, bool expand
= false) {
197 Run(client
, code
.c_str(), code
.size(), fout
, expand
);
200 int (*append_history$
)(int, const char *);
202 static std::string command_
;
204 static CYExpression
*ParseExpression(CYUTF8String code
) {
205 std::ostringstream str
;
206 str
<< '(' << code
<< ')';
207 std::string
string(str
.str());
210 driver
.data_
= string
.c_str();
211 driver
.size_
= string
.size();
213 cy::parser
parser(driver
);
214 Setup(driver
, parser
);
216 if (parser
.parse() != 0 || !driver
.errors_
.empty())
220 CYContext
context(options
);
222 // XXX: this could be replaced with a CYStatement::Primitive()
223 if (CYExpress
*express
= dynamic_cast<CYExpress
*>(driver
.program_
->statements_
))
224 return express
->expression_
->Primitive(context
);
231 static char **Complete(const char *word
, int start
, int end
) {
232 rl_attempted_completion_over
= TRUE
;
236 cy::parser
parser(driver
);
237 Setup(driver
, parser
);
239 std::string
line(rl_line_buffer
, start
);
240 std::string
command(command_
+ line
);
242 driver
.data_
= command
.c_str();
243 driver
.size_
= command
.size();
247 if (parser
.parse() != 0 || !driver
.errors_
.empty())
250 if (driver
.mode_
== CYDriver::AutoNone
)
253 CYExpression
*expression
;
256 CYContext
context(options
);
258 std::ostringstream prefix
;
260 switch (driver
.mode_
) {
261 case CYDriver::AutoPrimary
:
262 expression
= $
CYThis();
265 case CYDriver::AutoDirect
:
266 expression
= driver
.context_
;
269 case CYDriver::AutoIndirect
:
270 expression
= $
CYIndirect(driver
.context_
);
273 case CYDriver::AutoMessage
: {
274 CYDriver::Context
&thing(driver
.contexts_
.back());
275 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
276 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
277 prefix
<< (*part
)->word_
<< ':';
284 std::string
begin(prefix
.str());
286 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
287 " function(object, prefix, word) {\n"
289 " var before = prefix.length;\n"
291 " var entire = prefix.length;\n"
292 " for (name in object)\n"
293 " if (name.substring(0, entire) == prefix)\n"
294 " names.push(name.substr(before));\n"
297 ), expression
, $
S(begin
.c_str()), $
S(word
))));
299 driver
.program_
->Replace(context
);
301 std::ostringstream str
;
302 CYOutput
out(str
, options
);
303 out
<< *driver
.program_
;
305 std::string
code(str
.str());
306 CYUTF8String
json(Run(pool
, client_
, code
));
308 CYExpression
*result(ParseExpression(json
));
312 CYArray
*array(dynamic_cast<CYArray
*>(result
));
315 fprintf(fout_
, "\n");
317 rl_forced_update_display();
321 // XXX: use an std::set?
322 typedef std::vector
<std::string
> Completions
;
323 Completions completions
;
328 CYForEach (element
, array
->elements_
) {
329 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
330 _assert(string
!= NULL
);
332 std::string completion
;
333 if (string
->size_
!= 0)
334 completion
.assign(string
->value_
, string
->size_
);
335 else if (driver
.mode_
== CYDriver::AutoMessage
)
340 completions
.push_back(completion
);
346 size_t limit(completion
.size()), size(common
.size());
348 common
= common
.substr(0, limit
);
351 for (limit
= 0; limit
!= size
; ++limit
)
352 if (common
[limit
] != completion
[limit
])
355 common
= common
.substr(0, limit
);
359 size_t count(completions
.size());
363 size_t colon(common
.find(':'));
364 if (colon
!= std::string::npos
)
365 common
= common
.substr(0, colon
+ 1);
366 if (completions
.size() == 1)
369 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
371 results
[0] = strdup(common
.c_str());
373 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
374 results
[++index
] = strdup(i
->c_str());
375 results
[count
+ 1] = NULL
;
380 // need char *, not const char *
381 static char name_
[] = "cycript";
382 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
384 static void Console(CYOptions
&options
) {
388 if (const char *username
= getenv("LOGNAME"))
389 passwd
= getpwnam(username
);
391 passwd
= getpwuid(getuid());
393 const char *basedir(apr_psprintf(pool
, "%s/.cycript", passwd
->pw_dir
));
394 const char *histfile(apr_psprintf(pool
, "%s/history", basedir
));
398 rl_readline_name
= name_
;
400 mkdir(basedir
, 0700);
401 read_history(histfile
);
409 // rl_completer_word_break_characters is broken in libedit
410 rl_basic_word_break_characters
= break_
;
412 rl_completer_word_break_characters
= break_
;
413 rl_attempted_completion_function
= &Complete
;
414 rl_bind_key('\t', rl_complete
);
416 struct sigaction action
;
417 sigemptyset(&action
.sa_mask
);
418 action
.sa_handler
= &sigint
;
420 sigaction(SIGINT
, &action
, NULL
);
424 std::vector
<std::string
> lines
;
427 const char *prompt("cy# ");
429 if (setjmp(ctrlc_
) != 0) {
438 char *line(readline(prompt
));
447 if (line
[0] == '?') {
448 std::string
data(line
+ 1);
449 if (data
== "bypass") {
451 fprintf(fout_
, "bypass == %s\n", bypass
? "true" : "false");
453 } else if (data
== "debug") {
455 fprintf(fout_
, "debug == %s\n", debug
? "true" : "false");
457 } else if (data
== "expand") {
459 fprintf(fout_
, "expand == %s\n", expand
? "true" : "false");
470 char *begin(line
), *end(line
+ strlen(line
));
471 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
473 lines
.push_back(begin
);
477 lines
.push_back(begin
);
488 cy::parser
parser(driver
);
489 Setup(driver
, parser
);
491 driver
.data_
= command_
.c_str();
492 driver
.size_
= command_
.size();
494 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
495 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
496 cy::position
begin(error
->location_
.begin
);
497 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
498 cy::position
end(error
->location_
.end
);
500 if (begin
.line
!= lines
.size()) {
502 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
506 for (size_t i(0); i
!= begin
.column
; ++i
)
508 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
510 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
512 std::cerr
<< std::endl
;
515 std::cerr
<< error
->message_
<< std::endl
;
517 add_history(command_
.c_str());
523 driver
.errors_
.clear();
530 if (driver
.program_
== NULL
)
536 std::ostringstream str
;
537 CYOutput
out(str
, options
);
538 Setup(out
, driver
, options
);
539 out
<< *driver
.program_
;
544 add_history(command_
.c_str());
548 std::cout
<< code
<< std::endl
;
550 Run(client_
, code
, fout_
, expand
);
553 if (append_history$
!= NULL
) {
554 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
555 (*append_history$
)(histlines
, histfile
);
557 write_history(histfile
);
564 static void *Map(const char *path
, size_t *psize
) {
566 _syscall(fd
= open(path
, O_RDONLY
));
569 _syscall(fstat(fd
, &stat
));
570 size_t size(stat
.st_size
);
575 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
581 void InjectLibrary(pid_t pid
);
583 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
584 bool tty(isatty(STDIN_FILENO
));
588 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
591 pid_t
pid(_not(pid_t
));
596 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
602 apr_status_t
status(apr_getopt(state
,
616 "usage: cycript [-c]"
620 " [<script> [<arg>...]]\n"
634 else if (strcmp(arg
, "rename") == 0)
635 options
.verbose_
= true;
637 else if (strcmp(arg
, "bison") == 0)
641 fprintf(stderr
, "invalid name for -g\n");
648 else if (strcmp(arg
, "minify") == 0)
651 fprintf(stderr
, "invalid name for -n\n");
658 size_t size(strlen(arg
));
661 pid
= strtoul(arg
, &end
, 0);
662 if (arg
+ size
!= end
) {
663 // XXX: arg needs to be escaped in some horrendous way of doom
664 const char *command(apr_psprintf(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg
));
666 if (FILE *pids
= popen(command
, "r")) {
671 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
676 if (size
== sizeof(value
)) {
686 if (value
[size
- 1] == '\n') {
692 size
= strlen(value
);
693 pid
= strtoul(value
, &end
, 0);
694 if (value
+ size
!= end
) fail
:
696 _syscall(pclose(pids
));
699 if (pid
== _not(pid_t
)) {
700 fprintf(stderr
, "invalid pid for -p\n");
717 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
718 fprintf(stderr
, "-p cannot set argv\n");
722 if (pid
!= _not(pid_t
) && compile
) {
723 fprintf(stderr
, "-p conflicts with -c\n");
732 // XXX: const_cast?! wtf gcc :(
733 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
736 if (strcmp(script
, "-") == 0)
741 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
742 fprintf(stderr
, "non-terminal attaching to remote console\n");
748 if (pid
== _not(pid_t
))
751 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
752 struct sockaddr_un address
;
753 memset(&address
, 0, sizeof(address
));
754 address
.sun_family
= AF_UNIX
;
756 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
758 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
759 _syscall(chmod(address
.sun_path
, 0777));
762 _syscall(listen(server
, 1));
764 client_
= _syscall(accept(server
, NULL
, NULL
));
767 unlink(address
.sun_path
);
771 _syscall(close(server
));
779 if (script
== NULL
&& tty
)
783 CYDriver
driver(script
?: "<stdin>");
784 cy::parser
parser(driver
);
785 Setup(driver
, parser
);
789 if (script
== NULL
) {
793 driver
.file_
= stdin
;
796 start
= reinterpret_cast<char *>(Map(script
, &size
));
799 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
802 if (void *line
= memchr(start
, '\n', end
- start
))
803 start
= reinterpret_cast<char *>(line
);
808 driver
.data_
= start
;
809 driver
.size_
= end
- start
;
812 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
813 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
814 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
815 } else if (driver
.program_
!= NULL
)
817 std::string
code(start
, end
-start
);
818 Run(client_
, code
, stdout
);
820 std::ostringstream str
;
821 CYOutput
out(str
, options
);
822 Setup(out
, driver
, options
);
823 out
<< *driver
.program_
;
824 std::string
code(str
.str());
828 Run(client_
, code
, stdout
);
835 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
836 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
838 if (status
!= APR_SUCCESS
) {
839 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
842 return Main(argc
, argv
, envp
);
843 } catch (const CYException
&error
) {
845 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));