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
.data
);
148 CYSendAll(client
, &size
, sizeof(size
));
149 CYSendAll(client
, code
.data
, size
);
151 CYRecvAll(client
, &size
, sizeof(size
));
152 if (size
== _not(size_t))
155 char *temp(new(pool
) char[size
+ 1]);
156 CYRecvAll(client
, temp
, size
);
163 return CYUTF8String(json
, size
);
166 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
167 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
170 void Run(int client
, const char *data
, size_t size
, FILE *fout
= NULL
, bool expand
= false) {
172 CYUTF8String
json(Run(pool
, client
, CYUTF8String(data
, size
)));
177 if (data
!= NULL
&& fout
!= NULL
) {
178 if (!expand
|| data
[0] != '"' && data
[0] != '\'')
180 else for (size_t i(0); i
!= size
; ++i
)
182 fputc(data
[i
], fout
);
183 else switch(data
[++i
]) {
184 case '\0': goto done
;
185 case '\\': fputc('\\', fout
); break;
186 case '\'': fputc('\'', fout
); break;
187 case '"': fputc('"', fout
); break;
188 case 'b': fputc('\b', fout
); break;
189 case 'f': fputc('\f', fout
); break;
190 case 'n': fputc('\n', fout
); break;
191 case 'r': fputc('\r', fout
); break;
192 case 't': fputc('\t', fout
); break;
193 case 'v': fputc('\v', fout
); break;
194 default: fputc('\\', fout
); --i
; break;
203 static void Run(int client
, std::string
&code
, FILE *fout
= NULL
, bool expand
= false) {
204 Run(client
, code
.c_str(), code
.size(), fout
, expand
);
207 int (*append_history$
)(int, const char *);
209 static std::string command_
;
211 static CYExpression
*ParseExpression(CYPool
&pool
, CYUTF8String code
) {
212 std::ostringstream str
;
213 str
<< '(' << code
<< ')';
214 std::string
string(str
.str());
216 CYDriver
driver(pool
);
217 driver
.data_
= string
.c_str();
218 driver
.size_
= string
.size();
220 cy::parser
parser(driver
);
221 Setup(driver
, parser
);
223 if (parser
.parse() != 0 || !driver
.errors_
.empty())
226 CYExpress
*express(dynamic_cast<CYExpress
*>(driver
.program_
->statements_
));
227 _assert(express
!= NULL
);
228 return express
->expression_
;
233 static char **Complete(const char *word
, int start
, int end
) {
234 rl_attempted_completion_over
= TRUE
;
238 CYDriver
driver(pool
);
239 cy::parser
parser(driver
);
240 Setup(driver
, parser
);
242 std::string
line(rl_line_buffer
, start
);
243 std::string
command(command_
+ line
);
245 driver
.data_
= command
.c_str();
246 driver
.size_
= command
.size();
250 if (parser
.parse() != 0 || !driver
.errors_
.empty())
253 if (driver
.mode_
== CYDriver::AutoNone
)
256 CYExpression
*expression
;
259 CYContext
context(driver
.pool_
, options
);
261 std::ostringstream prefix
;
263 switch (driver
.mode_
) {
264 case CYDriver::AutoPrimary
:
265 expression
= $
CYThis();
268 case CYDriver::AutoDirect
:
269 expression
= driver
.context_
;
272 case CYDriver::AutoIndirect
:
273 expression
= $
CYIndirect(driver
.context_
);
276 case CYDriver::AutoMessage
: {
277 CYDriver::Context
&thing(driver
.contexts_
.back());
278 expression
= $
M($
M($
CYIndirect(thing
.context_
), $
S("isa")), $
S("messages"));
279 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
280 prefix
<< (*part
)->word_
<< ':';
287 std::string
begin(prefix
.str() + word
);
289 driver
.program_
= $
CYProgram($
CYExpress($
C2(ParseExpression(pool
,
290 " function(object, prefix) {\n"
292 " var pattern = '^' + prefix;\n"
293 " for (name in object)\n"
294 " if (name.match(pattern) != null)\n"
295 " names.push(name);\n"
298 ), expression
, $
S(begin
.c_str()))));
300 driver
.program_
->Replace(context
);
302 std::ostringstream str
;
303 CYOutput
out(str
, options
);
304 out
<< *driver
.program_
;
306 std::string
code(str
.str());
307 CYUTF8String
json(Run(pool
, client_
, code
));
309 CYExpression
*result(ParseExpression(pool
, json
));
310 CYArray
*array(dynamic_cast<CYArray
*>(result
));
311 _assert(array
!= NULL
);
313 // XXX: use an std::set?
314 typedef std::vector
<std::string
> Completions
;
315 Completions completions
;
320 for (CYElement
*element(array
->elements_
); element
!= NULL
; element
= element
->next_
) {
321 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
322 _assert(string
!= NULL
);
324 std::string
completion(string
->value_
, string
->size_
);
325 completions
.push_back(completion
);
331 size_t limit(completion
.size()), size(common
.size());
333 common
= common
.substr(0, limit
);
336 for (limit
= 0; limit
!= size
; ++limit
)
337 if (common
[limit
] != completion
[limit
])
340 common
= common
.substr(0, limit
);
344 size_t count(completions
.size());
348 if (!common
.empty()) {
349 size_t size(prefix
.str().size());
350 _assert(common
.size() >= size
);
351 common
= common
.substr(size
);
354 size_t colon(common
.find(':'));
355 if (colon
!= std::string::npos
)
356 common
= common
.substr(0, colon
+ 1);
358 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
360 results
[0] = strdup(common
.c_str());
362 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
363 results
[++index
] = strdup(i
->c_str());
364 results
[count
+ 1] = NULL
;
369 // need char *, not const char *
370 static char name_
[] = "cycript";
371 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ".:";
373 static void Console(apr_pool_t
*pool
, CYOptions
&options
) {
375 if (const char *username
= getenv("LOGNAME"))
376 passwd
= getpwnam(username
);
378 passwd
= getpwuid(getuid());
380 const char *basedir(apr_psprintf(pool
, "%s/.cycript", passwd
->pw_dir
));
381 const char *histfile(apr_psprintf(pool
, "%s/history", basedir
));
385 rl_readline_name
= name_
;
387 mkdir(basedir
, 0700);
388 read_history(histfile
);
396 // rl_completer_word_break_characters is broken in libedit
397 rl_basic_word_break_characters
= break_
;
399 rl_completer_word_break_characters
= break_
;
400 rl_attempted_completion_function
= &Complete
;
401 rl_bind_key('\t', rl_complete
);
403 struct sigaction action
;
404 sigemptyset(&action
.sa_mask
);
405 action
.sa_handler
= &sigint
;
407 sigaction(SIGINT
, &action
, NULL
);
411 std::vector
<std::string
> lines
;
414 const char *prompt("cy# ");
416 if (setjmp(ctrlc_
) != 0) {
425 char *line(readline(prompt
));
434 if (line
[0] == '?') {
435 std::string
data(line
+ 1);
436 if (data
== "bypass") {
438 fprintf(fout
, "bypass == %s\n", bypass
? "true" : "false");
440 } else if (data
== "debug") {
442 fprintf(fout
, "debug == %s\n", debug
? "true" : "false");
444 } else if (data
== "expand") {
446 fprintf(fout
, "expand == %s\n", expand
? "true" : "false");
457 char *begin(line
), *end(line
+ strlen(line
));
458 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
460 lines
.push_back(begin
);
464 lines
.push_back(begin
);
474 cy::parser
parser(driver
);
475 Setup(driver
, parser
);
477 driver
.data_
= command_
.c_str();
478 driver
.size_
= command_
.size();
480 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
481 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
482 cy::position
begin(error
->location_
.begin
);
483 if (begin
.line
!= lines
.size() || begin
.column
- 1 != lines
.back().size() || error
->warning_
) {
484 cy::position
end(error
->location_
.end
);
486 if (begin
.line
!= lines
.size()) {
488 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
492 for (size_t i(0); i
!= begin
.column
- 1; ++i
)
494 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
496 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
498 std::cerr
<< std::endl
;
501 std::cerr
<< error
->message_
<< std::endl
;
503 add_history(command_
.c_str());
509 driver
.errors_
.clear();
516 if (driver
.program_
== NULL
)
522 std::ostringstream str
;
523 CYOutput
out(str
, options
);
524 Setup(out
, driver
, options
);
525 out
<< *driver
.program_
;
530 add_history(command_
.c_str());
534 std::cout
<< code
<< std::endl
;
536 Run(client_
, code
, fout
, expand
);
539 if (append_history$
!= NULL
) {
540 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
541 (*append_history$
)(histlines
, histfile
);
543 write_history(histfile
);
550 static void *Map(const char *path
, size_t *psize
) {
552 _syscall(fd
= open(path
, O_RDONLY
));
555 _syscall(fstat(fd
, &stat
));
556 size_t size(stat
.st_size
);
561 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
567 void InjectLibrary(pid_t pid
);
569 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
570 bool tty(isatty(STDIN_FILENO
));
574 append_history$
= reinterpret_cast<int (*)(int, const char *)>(dlsym(RTLD_DEFAULT
, "append_history"));
577 pid_t
pid(_not(pid_t
));
582 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
588 apr_status_t
status(apr_getopt(state
,
602 "usage: cycript [-c]"
606 " [<script> [<arg>...]]\n"
620 else if (strcmp(arg
, "rename") == 0)
621 options
.verbose_
= true;
623 else if (strcmp(arg
, "bison") == 0)
627 fprintf(stderr
, "invalid name for -g\n");
634 else if (strcmp(arg
, "minify") == 0)
637 fprintf(stderr
, "invalid name for -n\n");
644 size_t size(strlen(arg
));
647 pid
= strtoul(arg
, &end
, 0);
648 if (arg
+ size
!= end
) {
649 // XXX: arg needs to be escaped in some horrendous way of doom
650 const char *command(apr_psprintf(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg
));
652 if (FILE *pids
= popen(command
, "r")) {
657 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
662 if (size
== sizeof(value
)) {
672 if (value
[size
- 1] == '\n') {
678 size
= strlen(value
);
679 pid
= strtoul(value
, &end
, 0);
680 if (value
+ size
!= end
) fail
:
682 _syscall(pclose(pids
));
685 if (pid
== _not(pid_t
)) {
686 fprintf(stderr
, "invalid pid for -p\n");
703 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
704 fprintf(stderr
, "-p cannot set argv\n");
708 if (pid
!= _not(pid_t
) && compile
) {
709 fprintf(stderr
, "-p conflicts with -c\n");
718 // XXX: const_cast?! wtf gcc :(
719 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
722 if (strcmp(script
, "-") == 0)
727 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
728 fprintf(stderr
, "non-terminal attaching to remote console\n");
734 if (pid
== _not(pid_t
))
737 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
738 struct sockaddr_un address
;
739 memset(&address
, 0, sizeof(address
));
740 address
.sun_family
= AF_UNIX
;
742 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
744 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
745 _syscall(chmod(address
.sun_path
, 0777));
748 _syscall(listen(server
, 1));
750 client_
= _syscall(accept(server
, NULL
, NULL
));
753 unlink(address
.sun_path
);
757 _syscall(close(server
));
765 if (script
== NULL
&& tty
)
766 Console(pool
, options
);
768 CYDriver
driver(pool
, script
?: "<stdin>");
769 cy::parser
parser(driver
);
770 Setup(driver
, parser
);
774 if (script
== NULL
) {
778 driver
.file_
= stdin
;
781 start
= reinterpret_cast<char *>(Map(script
, &size
));
784 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
787 if (void *line
= memchr(start
, '\n', end
- start
))
788 start
= reinterpret_cast<char *>(line
);
793 driver
.data_
= start
;
794 driver
.size_
= end
- start
;
797 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
798 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
799 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
800 } else if (driver
.program_
!= NULL
)
802 std::string
code(start
, end
-start
);
803 Run(client_
, code
, stdout
);
805 std::ostringstream str
;
806 CYOutput
out(str
, options
);
807 Setup(out
, driver
, options
);
808 out
<< *driver
.program_
;
809 std::string
code(str
.str());
813 Run(client_
, code
, stdout
);
820 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
821 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
823 if (status
!= APR_SUCCESS
) {
824 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
827 return Main(argc
, argv
, envp
);
828 } catch (const CYException
&error
) {
830 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));