1 /* Cycript - Inlining/Optimizing JavaScript Compiler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 #include "cycript.hpp"
43 #include "JavaScript.hpp"
51 #ifdef HAVE_READLINE_H
54 #include <readline/readline.h>
60 #include <readline/history.h>
68 #include <sys/types.h>
72 #include "Cycript.tab.hh"
74 #include <sys/types.h>
75 #include <sys/socket.h>
76 #include <netinet/in.h>
80 #include <apr_getopt.h>
84 #include "Replace.hpp"
86 static volatile enum {
94 static jmp_buf ctrlc_
;
96 static void sigint(int) {
117 void Setup(CYDriver
&driver
, cy::parser
&parser
) {
120 parser
.set_debug_level(1);
123 driver
.strict_
= true;
126 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
) {
127 out
.pretty_
= pretty_
;
128 CYContext
context(driver
.pool_
, options
);
129 driver
.program_
->Replace(context
);
132 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
139 json
= CYExecute(pool
, code
);
149 CYSendAll(client
, &size
, sizeof(size
));
150 CYSendAll(client
, code
.data
, code
.size
);
152 CYRecvAll(client
, &size
, sizeof(size
));
153 if (size
== _not(size_t))
156 char *temp(new(pool
) char[size
+ 1]);
157 CYRecvAll(client
, temp
, size
);
164 return CYUTF8String(json
, size
);
167 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
168 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
173 static void Output(CYUTF8String json
, FILE *fout
, bool expand
= false) {
174 const char *data(json
.data
);
175 size_t size(json
.size
);
177 if (data
== NULL
|| fout
== NULL
)
180 if (!expand
|| data
[0] != '"' && data
[0] != '\'')
182 else for (size_t i(0); i
!= size
; ++i
)
184 fputc(data
[i
], fout
);
185 else switch(data
[++i
]) {
186 case '\0': goto done
;
187 case '\\': fputc('\\', fout
); break;
188 case '\'': fputc('\'', fout
); break;
189 case '"': fputc('"', fout
); break;
190 case 'b': fputc('\b', fout
); break;
191 case 'f': fputc('\f', fout
); break;
192 case 'n': fputc('\n', fout
); break;
193 case 'r': fputc('\r', fout
); break;
194 case 't': fputc('\t', fout
); break;
195 case 'v': fputc('\v', fout
); break;
196 default: fputc('\\', fout
); --i
; break;
204 static void Run(int client
, const char *data
, size_t size
, FILE *fout
= NULL
, bool expand
= false) {
206 Output(Run(pool
, client
, CYUTF8String(data
, size
)), fout
, expand
);
209 static void Run(int client
, std::string
&code
, FILE *fout
= NULL
, bool expand
= false) {
210 Run(client
, code
.c_str(), code
.size(), fout
, expand
);
213 int (*append_history$
)(int, const char *);
215 static std::string command_
;
217 static CYExpression
*ParseExpression(CYPool
&pool
, CYUTF8String code
) {
218 std::ostringstream str
;
219 str
<< '(' << code
<< ')';
220 std::string
string(str
.str());
222 CYDriver
driver(pool
);
223 driver
.data_
= string
.c_str();
224 driver
.size_
= string
.size();
226 cy::parser
parser(driver
);
227 Setup(driver
, parser
);
229 if (parser
.parse() != 0 || !driver
.errors_
.empty())
232 CYExpress
*express(dynamic_cast<CYExpress
*>(driver
.program_
->statements_
));
233 _assert(express
!= NULL
);
234 return express
->expression_
;
239 static char **Complete(const char *word
, int start
, int end
) {
240 rl_attempted_completion_over
= TRUE
;
244 CYDriver
driver(pool
);
245 cy::parser
parser(driver
);
246 Setup(driver
, parser
);
248 std::string
line(rl_line_buffer
, start
);
249 std::string
command(command_
+ line
);
251 driver
.data_
= command
.c_str();
252 driver
.size_
= command
.size();
256 if (parser
.parse() != 0 || !driver
.errors_
.empty())
259 if (driver
.mode_
== CYDriver::AutoNone
)
262 CYExpression
*expression
;
265 CYContext
context(driver
.pool_
, options
);
267 std::ostringstream prefix
;
269 switch (driver
.mode_
) {
270 case CYDriver::AutoPrimary
:
271 expression
= $
CYThis();
274 case CYDriver::AutoDirect
:
275 expression
= driver
.context_
;
278 case CYDriver::AutoIndirect
:
279 expression
= $
CYIndirect(driver
.context_
);
282 case CYDriver::AutoMessage
: {
283 CYDriver::Context
&thing(driver
.contexts_
.back());
284 expression
= $
M($
M($
CYIndirect(thing
.context_
), $
S("isa")), $
S("messages"));
285 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
286 prefix
<< (*part
)->word_
<< ':';
293 std::string
begin(prefix
.str());
295 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(pool
,
296 " function(object, prefix, word) {\n"
298 " var pattern = '^' + prefix + word;\n"
299 " var length = prefix.length;\n"
300 " for (name in object)\n"
301 " if (name.match(pattern) != null)\n"
302 " names.push(name.substr(length));\n"
305 ), expression
, $
S(begin
.c_str()), $
S(word
))));
307 driver
.program_
->Replace(context
);
309 std::ostringstream str
;
310 CYOutput
out(str
, options
);
311 out
<< *driver
.program_
;
313 std::string
code(str
.str());
314 CYUTF8String
json(Run(pool
, client_
, code
));
316 CYExpression
*result(ParseExpression(pool
, json
));
317 CYArray
*array(dynamic_cast<CYArray
*>(result
));
320 fprintf(fout_
, "\n");
322 rl_forced_update_display();
326 // XXX: use an std::set?
327 typedef std::vector
<std::string
> Completions
;
328 Completions completions
;
333 for (CYElement
*element(array
->elements_
); element
!= NULL
; element
= element
->next_
) {
334 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
335 _assert(string
!= NULL
);
337 std::string
completion(string
->value_
, string
->size_
);
338 completions
.push_back(completion
);
344 size_t limit(completion
.size()), size(common
.size());
346 common
= common
.substr(0, limit
);
349 for (limit
= 0; limit
!= size
; ++limit
)
350 if (common
[limit
] != completion
[limit
])
353 common
= common
.substr(0, limit
);
357 size_t count(completions
.size());
361 size_t colon(common
.find(':'));
362 if (colon
!= std::string::npos
)
363 common
= common
.substr(0, colon
+ 1);
364 if (completions
.size() == 1)
367 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
369 results
[0] = strdup(common
.c_str());
371 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
372 results
[++index
] = strdup(i
->c_str());
373 results
[count
+ 1] = NULL
;
378 // need char *, not const char *
379 static char name_
[] = "cycript";
380 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
382 static void Console(apr_pool_t
*pool
, 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
);
483 cy::parser
parser(driver
);
484 Setup(driver
, parser
);
486 driver
.data_
= command_
.c_str();
487 driver
.size_
= command_
.size();
489 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
490 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
491 cy::position
begin(error
->location_
.begin
);
492 if (begin
.line
!= lines
.size() || begin
.column
- 1 != lines
.back().size() || error
->warning_
) {
493 cy::position
end(error
->location_
.end
);
495 if (begin
.line
!= lines
.size()) {
497 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
501 for (size_t i(0); i
!= begin
.column
- 1; ++i
)
503 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
505 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
507 std::cerr
<< std::endl
;
510 std::cerr
<< error
->message_
<< std::endl
;
512 add_history(command_
.c_str());
518 driver
.errors_
.clear();
525 if (driver
.program_
== NULL
)
531 std::ostringstream str
;
532 CYOutput
out(str
, options
);
533 Setup(out
, driver
, options
);
534 out
<< *driver
.program_
;
539 add_history(command_
.c_str());
543 std::cout
<< code
<< std::endl
;
545 Run(client_
, code
, fout_
, expand
);
548 if (append_history$
!= NULL
) {
549 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
550 (*append_history$
)(histlines
, histfile
);
552 write_history(histfile
);
559 static void *Map(const char *path
, size_t *psize
) {
561 _syscall(fd
= open(path
, O_RDONLY
));
564 _syscall(fstat(fd
, &stat
));
565 size_t size(stat
.st_size
);
570 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
576 void InjectLibrary(pid_t pid
);
578 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
579 bool tty(isatty(STDIN_FILENO
));
583 append_history$
= reinterpret_cast<int (*)(int, const char *)>(dlsym(RTLD_DEFAULT
, "append_history"));
586 pid_t
pid(_not(pid_t
));
591 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
597 apr_status_t
status(apr_getopt(state
,
611 "usage: cycript [-c]"
615 " [<script> [<arg>...]]\n"
629 else if (strcmp(arg
, "rename") == 0)
630 options
.verbose_
= true;
632 else if (strcmp(arg
, "bison") == 0)
636 fprintf(stderr
, "invalid name for -g\n");
643 else if (strcmp(arg
, "minify") == 0)
646 fprintf(stderr
, "invalid name for -n\n");
653 size_t size(strlen(arg
));
656 pid
= strtoul(arg
, &end
, 0);
657 if (arg
+ size
!= end
) {
658 // XXX: arg needs to be escaped in some horrendous way of doom
659 const char *command(apr_psprintf(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg
));
661 if (FILE *pids
= popen(command
, "r")) {
666 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
671 if (size
== sizeof(value
)) {
681 if (value
[size
- 1] == '\n') {
687 size
= strlen(value
);
688 pid
= strtoul(value
, &end
, 0);
689 if (value
+ size
!= end
) fail
:
691 _syscall(pclose(pids
));
694 if (pid
== _not(pid_t
)) {
695 fprintf(stderr
, "invalid pid for -p\n");
712 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
713 fprintf(stderr
, "-p cannot set argv\n");
717 if (pid
!= _not(pid_t
) && compile
) {
718 fprintf(stderr
, "-p conflicts with -c\n");
727 // XXX: const_cast?! wtf gcc :(
728 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
731 if (strcmp(script
, "-") == 0)
736 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
737 fprintf(stderr
, "non-terminal attaching to remote console\n");
743 if (pid
== _not(pid_t
))
746 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
747 struct sockaddr_un address
;
748 memset(&address
, 0, sizeof(address
));
749 address
.sun_family
= AF_UNIX
;
751 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
753 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
754 _syscall(chmod(address
.sun_path
, 0777));
757 _syscall(listen(server
, 1));
759 client_
= _syscall(accept(server
, NULL
, NULL
));
762 unlink(address
.sun_path
);
766 _syscall(close(server
));
774 if (script
== NULL
&& tty
)
775 Console(pool
, options
);
777 CYDriver
driver(pool
, script
?: "<stdin>");
778 cy::parser
parser(driver
);
779 Setup(driver
, parser
);
783 if (script
== NULL
) {
787 driver
.file_
= stdin
;
790 start
= reinterpret_cast<char *>(Map(script
, &size
));
793 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
796 if (void *line
= memchr(start
, '\n', end
- start
))
797 start
= reinterpret_cast<char *>(line
);
802 driver
.data_
= start
;
803 driver
.size_
= end
- start
;
806 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
807 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
808 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
809 } else if (driver
.program_
!= NULL
)
811 std::string
code(start
, end
-start
);
812 Run(client_
, code
, stdout
);
814 std::ostringstream str
;
815 CYOutput
out(str
, options
);
816 Setup(out
, driver
, options
);
817 out
<< *driver
.program_
;
818 std::string
code(str
.str());
822 Run(client_
, code
, stdout
);
829 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
830 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
832 if (status
!= APR_SUCCESS
) {
833 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
836 return Main(argc
, argv
, envp
);
837 } catch (const CYException
&error
) {
839 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));