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()));
171 void Run(int client
, const char *data
, size_t size
, FILE *fout
= NULL
, bool expand
= false) {
173 CYUTF8String
json(Run(pool
, client
, CYUTF8String(data
, size
)));
178 if (data
!= NULL
&& fout
!= NULL
) {
179 if (!expand
|| data
[0] != '"' && data
[0] != '\'')
181 else for (size_t i(0); i
!= size
; ++i
)
183 fputc(data
[i
], fout
);
184 else switch(data
[++i
]) {
185 case '\0': goto done
;
186 case '\\': fputc('\\', fout
); break;
187 case '\'': fputc('\'', fout
); break;
188 case '"': fputc('"', fout
); break;
189 case 'b': fputc('\b', fout
); break;
190 case 'f': fputc('\f', fout
); break;
191 case 'n': fputc('\n', fout
); break;
192 case 'r': fputc('\r', fout
); break;
193 case 't': fputc('\t', fout
); break;
194 case 'v': fputc('\v', fout
); break;
195 default: fputc('\\', fout
); --i
; break;
204 static void Run(int client
, std::string
&code
, FILE *fout
= NULL
, bool expand
= false) {
205 Run(client
, code
.c_str(), code
.size(), fout
, expand
);
208 int (*append_history$
)(int, const char *);
210 static std::string command_
;
212 static CYExpression
*ParseExpression(CYPool
&pool
, CYUTF8String code
) {
213 std::ostringstream str
;
214 str
<< '(' << code
<< ')';
215 std::string
string(str
.str());
217 CYDriver
driver(pool
);
218 driver
.data_
= string
.c_str();
219 driver
.size_
= string
.size();
221 cy::parser
parser(driver
);
222 Setup(driver
, parser
);
224 if (parser
.parse() != 0 || !driver
.errors_
.empty())
227 CYExpress
*express(dynamic_cast<CYExpress
*>(driver
.program_
->statements_
));
228 _assert(express
!= NULL
);
229 return express
->expression_
;
234 static char **Complete(const char *word
, int start
, int end
) {
235 rl_attempted_completion_over
= TRUE
;
239 CYDriver
driver(pool
);
240 cy::parser
parser(driver
);
241 Setup(driver
, parser
);
243 std::string
line(rl_line_buffer
, start
);
244 std::string
command(command_
+ line
);
246 driver
.data_
= command
.c_str();
247 driver
.size_
= command
.size();
251 if (parser
.parse() != 0 || !driver
.errors_
.empty())
254 if (driver
.mode_
== CYDriver::AutoNone
)
257 CYExpression
*expression
;
260 CYContext
context(driver
.pool_
, options
);
262 std::ostringstream prefix
;
264 switch (driver
.mode_
) {
265 case CYDriver::AutoPrimary
:
266 expression
= $
CYThis();
269 case CYDriver::AutoDirect
:
270 expression
= driver
.context_
;
273 case CYDriver::AutoIndirect
:
274 expression
= $
CYIndirect(driver
.context_
);
277 case CYDriver::AutoMessage
: {
278 CYDriver::Context
&thing(driver
.contexts_
.back());
279 expression
= $
M($
M($
CYIndirect(thing
.context_
), $
S("isa")), $
S("messages"));
280 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
281 prefix
<< (*part
)->word_
<< ':';
288 std::string
begin(prefix
.str() + word
);
290 driver
.program_
= $
CYProgram($
CYExpress($
C2(ParseExpression(pool
,
291 " function(object, prefix) {\n"
293 " var pattern = '^' + prefix;\n"
294 " for (name in object)\n"
295 " if (name.match(pattern) != null)\n"
296 " names.push(name);\n"
299 ), expression
, $
S(begin
.c_str()))));
301 driver
.program_
->Replace(context
);
303 std::ostringstream str
;
304 CYOutput
out(str
, options
);
305 out
<< *driver
.program_
;
307 std::string
code(str
.str());
308 CYUTF8String
json(Run(pool
, client_
, code
));
310 CYExpression
*result(ParseExpression(pool
, json
));
311 CYArray
*array(dynamic_cast<CYArray
*>(result
));
312 _assert(array
!= NULL
);
314 // XXX: use an std::set?
315 typedef std::vector
<std::string
> Completions
;
316 Completions completions
;
321 for (CYElement
*element(array
->elements_
); element
!= NULL
; element
= element
->next_
) {
322 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
323 _assert(string
!= NULL
);
325 std::string
completion(string
->value_
, string
->size_
);
326 completions
.push_back(completion
);
332 size_t limit(completion
.size()), size(common
.size());
334 common
= common
.substr(0, limit
);
337 for (limit
= 0; limit
!= size
; ++limit
)
338 if (common
[limit
] != completion
[limit
])
341 common
= common
.substr(0, limit
);
345 size_t count(completions
.size());
349 if (!common
.empty()) {
350 size_t size(prefix
.str().size());
351 _assert(common
.size() >= size
);
352 common
= common
.substr(size
);
355 size_t colon(common
.find(':'));
356 if (colon
!= std::string::npos
)
357 common
= common
.substr(0, colon
+ 1);
359 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
361 results
[0] = strdup(common
.c_str());
363 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
364 results
[++index
] = strdup(i
->c_str());
365 results
[count
+ 1] = NULL
;
370 // need char *, not const char *
371 static char name_
[] = "cycript";
372 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ".:";
374 static void Console(apr_pool_t
*pool
, CYOptions
&options
) {
376 if (const char *username
= getenv("LOGNAME"))
377 passwd
= getpwnam(username
);
379 passwd
= getpwuid(getuid());
381 const char *basedir(apr_psprintf(pool
, "%s/.cycript", passwd
->pw_dir
));
382 const char *histfile(apr_psprintf(pool
, "%s/history", basedir
));
386 rl_readline_name
= name_
;
388 mkdir(basedir
, 0700);
389 read_history(histfile
);
397 // rl_completer_word_break_characters is broken in libedit
398 rl_basic_word_break_characters
= break_
;
400 rl_completer_word_break_characters
= break_
;
401 rl_attempted_completion_function
= &Complete
;
402 rl_bind_key('\t', rl_complete
);
404 struct sigaction action
;
405 sigemptyset(&action
.sa_mask
);
406 action
.sa_handler
= &sigint
;
408 sigaction(SIGINT
, &action
, NULL
);
412 std::vector
<std::string
> lines
;
415 const char *prompt("cy# ");
417 if (setjmp(ctrlc_
) != 0) {
426 char *line(readline(prompt
));
435 if (line
[0] == '?') {
436 std::string
data(line
+ 1);
437 if (data
== "bypass") {
439 fprintf(fout
, "bypass == %s\n", bypass
? "true" : "false");
441 } else if (data
== "debug") {
443 fprintf(fout
, "debug == %s\n", debug
? "true" : "false");
445 } else if (data
== "expand") {
447 fprintf(fout
, "expand == %s\n", expand
? "true" : "false");
458 char *begin(line
), *end(line
+ strlen(line
));
459 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
461 lines
.push_back(begin
);
465 lines
.push_back(begin
);
475 cy::parser
parser(driver
);
476 Setup(driver
, parser
);
478 driver
.data_
= command_
.c_str();
479 driver
.size_
= command_
.size();
481 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
482 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
483 cy::position
begin(error
->location_
.begin
);
484 if (begin
.line
!= lines
.size() || begin
.column
- 1 != lines
.back().size() || error
->warning_
) {
485 cy::position
end(error
->location_
.end
);
487 if (begin
.line
!= lines
.size()) {
489 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
493 for (size_t i(0); i
!= begin
.column
- 1; ++i
)
495 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
497 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
499 std::cerr
<< std::endl
;
502 std::cerr
<< error
->message_
<< std::endl
;
504 add_history(command_
.c_str());
510 driver
.errors_
.clear();
517 if (driver
.program_
== NULL
)
523 std::ostringstream str
;
524 CYOutput
out(str
, options
);
525 Setup(out
, driver
, options
);
526 out
<< *driver
.program_
;
531 add_history(command_
.c_str());
535 std::cout
<< code
<< std::endl
;
537 Run(client_
, code
, fout
, expand
);
540 if (append_history$
!= NULL
) {
541 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
542 (*append_history$
)(histlines
, histfile
);
544 write_history(histfile
);
551 static void *Map(const char *path
, size_t *psize
) {
553 _syscall(fd
= open(path
, O_RDONLY
));
556 _syscall(fstat(fd
, &stat
));
557 size_t size(stat
.st_size
);
562 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
568 void InjectLibrary(pid_t pid
);
570 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
571 bool tty(isatty(STDIN_FILENO
));
575 append_history$
= reinterpret_cast<int (*)(int, const char *)>(dlsym(RTLD_DEFAULT
, "append_history"));
578 pid_t
pid(_not(pid_t
));
583 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
589 apr_status_t
status(apr_getopt(state
,
603 "usage: cycript [-c]"
607 " [<script> [<arg>...]]\n"
621 else if (strcmp(arg
, "rename") == 0)
622 options
.verbose_
= true;
624 else if (strcmp(arg
, "bison") == 0)
628 fprintf(stderr
, "invalid name for -g\n");
635 else if (strcmp(arg
, "minify") == 0)
638 fprintf(stderr
, "invalid name for -n\n");
645 size_t size(strlen(arg
));
648 pid
= strtoul(arg
, &end
, 0);
649 if (arg
+ size
!= end
) {
650 // XXX: arg needs to be escaped in some horrendous way of doom
651 const char *command(apr_psprintf(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg
));
653 if (FILE *pids
= popen(command
, "r")) {
658 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
663 if (size
== sizeof(value
)) {
673 if (value
[size
- 1] == '\n') {
679 size
= strlen(value
);
680 pid
= strtoul(value
, &end
, 0);
681 if (value
+ size
!= end
) fail
:
683 _syscall(pclose(pids
));
686 if (pid
== _not(pid_t
)) {
687 fprintf(stderr
, "invalid pid for -p\n");
704 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
705 fprintf(stderr
, "-p cannot set argv\n");
709 if (pid
!= _not(pid_t
) && compile
) {
710 fprintf(stderr
, "-p conflicts with -c\n");
719 // XXX: const_cast?! wtf gcc :(
720 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
723 if (strcmp(script
, "-") == 0)
728 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
729 fprintf(stderr
, "non-terminal attaching to remote console\n");
735 if (pid
== _not(pid_t
))
738 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
739 struct sockaddr_un address
;
740 memset(&address
, 0, sizeof(address
));
741 address
.sun_family
= AF_UNIX
;
743 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
745 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
746 _syscall(chmod(address
.sun_path
, 0777));
749 _syscall(listen(server
, 1));
751 client_
= _syscall(accept(server
, NULL
, NULL
));
754 unlink(address
.sun_path
);
758 _syscall(close(server
));
766 if (script
== NULL
&& tty
)
767 Console(pool
, options
);
769 CYDriver
driver(pool
, script
?: "<stdin>");
770 cy::parser
parser(driver
);
771 Setup(driver
, parser
);
775 if (script
== NULL
) {
779 driver
.file_
= stdin
;
782 start
= reinterpret_cast<char *>(Map(script
, &size
));
785 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
788 if (void *line
= memchr(start
, '\n', end
- start
))
789 start
= reinterpret_cast<char *>(line
);
794 driver
.data_
= start
;
795 driver
.size_
= end
- start
;
798 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
799 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
800 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
801 } else if (driver
.program_
!= NULL
)
803 std::string
code(start
, end
-start
);
804 Run(client_
, code
, stdout
);
806 std::ostringstream str
;
807 CYOutput
out(str
, options
);
808 Setup(out
, driver
, options
);
809 out
<< *driver
.program_
;
810 std::string
code(str
.str());
814 Run(client_
, code
, stdout
);
821 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
822 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
824 if (status
!= APR_SUCCESS
) {
825 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
828 return Main(argc
, argv
, envp
);
829 } catch (const CYException
&error
) {
831 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));