1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU 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 <sys/types.h>
55 #include <sys/socket.h>
56 #include <netinet/in.h>
60 #include <apr_getopt.h>
61 #include <apr_pools.h>
62 #include <apr_strings.h>
66 #include "Display.hpp"
67 #include "Replace.hpp"
69 #include "Cycript.tab.hh"
72 static volatile enum {
80 static jmp_buf ctrlc_
;
82 static void sigint(int) {
103 void Setup(CYDriver
&driver
, cy::parser
&parser
) {
106 parser
.set_debug_level(1);
109 driver
.strict_
= true;
112 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
) {
113 out
.pretty_
= pretty_
;
114 CYContext
context(options
);
115 driver
.program_
->Replace(context
);
118 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
125 json
= CYExecute(pool
, code
);
137 CYSendAll(client
, &size
, sizeof(size
));
138 CYSendAll(client
, code
.data
, code
.size
);
140 CYRecvAll(client
, &size
, sizeof(size
));
141 if (size
== _not(uint32_t))
144 char *temp(new(pool
) char[size
+ 1]);
145 CYRecvAll(client
, temp
, size
);
152 return CYUTF8String(json
, size
);
155 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
156 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
159 static std::ostream
*out_
;
161 static void Write(bool syntax
, const char *data
, size_t size
, std::ostream
&out
) {
163 CYLexerHighlight(data
, size
, out
);
165 out
.write(data
, size
);
168 static void Output(bool syntax
, CYUTF8String json
, std::ostream
*out
, bool expand
= false) {
169 const char *data(json
.data
);
170 size_t size(json
.size
);
172 if (data
== NULL
|| out
== NULL
)
176 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
177 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
179 Write(syntax
, data
, size
, *out
);
180 else for (size_t i(0); i
!= size
; ++i
)
183 else switch(data
[++i
]) {
184 case '\0': goto done
;
185 case '\\': *out
<< '\\'; break;
186 case '\'': *out
<< '\''; break;
187 case '"': *out
<< '"'; break;
188 case 'b': *out
<< '\b'; break;
189 case 'f': *out
<< '\f'; break;
190 case 'n': *out
<< '\n'; break;
191 case 'r': *out
<< '\r'; break;
192 case 't': *out
<< '\t'; break;
193 case 'v': *out
<< '\v'; break;
194 default: *out
<< '\\'; --i
; break;
201 static void Run(int client
, bool syntax
, const char *data
, size_t size
, std::ostream
*out
= NULL
, bool expand
= false) {
203 Output(syntax
, Run(pool
, client
, CYUTF8String(data
, size
)), out
, expand
);
206 static void Run(int client
, bool syntax
, std::string
&code
, std::ostream
*out
= NULL
, bool expand
= false) {
207 Run(client
, syntax
, code
.c_str(), code
.size(), out
, expand
);
210 int (*append_history$
)(int, const char *);
212 static std::string command_
;
214 static CYExpression
*ParseExpression(CYUTF8String code
) {
215 std::stringstream stream
;
216 stream
<< '(' << code
<< ')';
217 CYDriver
driver(stream
);
219 cy::parser
parser(driver
);
220 Setup(driver
, parser
);
222 if (parser
.parse() != 0 || !driver
.errors_
.empty())
226 CYContext
context(options
);
228 // XXX: this could be replaced with a CYStatement::Primitive()
229 if (CYExpress
*express
= dynamic_cast<CYExpress
*>(driver
.program_
->statements_
))
230 return express
->expression_
->Primitive(context
);
237 static char **Complete(const char *word
, int start
, int end
) {
238 rl_attempted_completion_over
= TRUE
;
242 std::string
line(rl_line_buffer
, start
);
243 std::istringstream
stream(command_
+ line
);
244 CYDriver
driver(stream
);
248 cy::parser
parser(driver
);
249 Setup(driver
, parser
);
251 if (parser
.parse() != 0 || !driver
.errors_
.empty())
254 if (driver
.mode_
== CYDriver::AutoNone
)
257 CYExpression
*expression
;
260 CYContext
context(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($
C1($
V("object_getClass"), thing
.context_
), $
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());
290 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
291 " function(object, prefix, word) {\n"
293 " var before = prefix.length;\n"
295 " var entire = prefix.length;\n"
296 " for (name in object)\n"
297 " if (name.substring(0, entire) == prefix)\n"
298 " names.push(name.substr(before));\n"
301 ), expression
, $
S(begin
.c_str()), $
S(word
))));
303 driver
.program_
->Replace(context
);
305 std::ostringstream str
;
306 CYOutput
out(str
, options
);
307 out
<< *driver
.program_
;
309 std::string
code(str
.str());
310 CYUTF8String
json(Run(pool
, client_
, code
));
311 // XXX: if this fails we should not try to parse it
313 CYExpression
*result(ParseExpression(json
));
317 CYArray
*array(dynamic_cast<CYArray
*>(result
));
321 Output(false, json
, out_
);
322 rl_forced_update_display();
326 // XXX: use an std::set?
327 typedef std::vector
<std::string
> Completions
;
328 Completions completions
;
333 CYForEach (element
, array
->elements_
) {
334 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
335 _assert(string
!= NULL
);
337 std::string completion
;
338 if (string
->size_
!= 0)
339 completion
.assign(string
->value_
, string
->size_
);
340 else if (driver
.mode_
== CYDriver::AutoMessage
)
345 completions
.push_back(completion
);
351 size_t limit(completion
.size()), size(common
.size());
353 common
= common
.substr(0, limit
);
356 for (limit
= 0; limit
!= size
; ++limit
)
357 if (common
[limit
] != completion
[limit
])
360 common
= common
.substr(0, limit
);
364 size_t count(completions
.size());
368 size_t colon(common
.find(':'));
369 if (colon
!= std::string::npos
)
370 common
= common
.substr(0, colon
+ 1);
371 if (completions
.size() == 1)
374 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
376 results
[0] = strdup(common
.c_str());
378 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
379 results
[++index
] = strdup(i
->c_str());
380 results
[count
+ 1] = NULL
;
385 // need char *, not const char *
386 static char name_
[] = "cycript";
387 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
389 static void Console(CYOptions
&options
) {
393 if (const char *username
= getenv("LOGNAME"))
394 passwd
= getpwnam(username
);
396 passwd
= getpwuid(getuid());
398 const char *basedir(pool
.strcat(passwd
->pw_dir
, "/.cycript", NULL
));
399 const char *histfile(pool
.strcat(basedir
, "/history", NULL
));
403 rl_readline_name
= name_
;
405 mkdir(basedir
, 0700);
406 read_history(histfile
);
415 // rl_completer_word_break_characters is broken in libedit
416 rl_basic_word_break_characters
= break_
;
418 rl_completer_word_break_characters
= break_
;
419 rl_attempted_completion_function
= &Complete
;
420 rl_bind_key('\t', rl_complete
);
422 struct sigaction action
;
423 sigemptyset(&action
.sa_mask
);
424 action
.sa_handler
= &sigint
;
426 sigaction(SIGINT
, &action
, NULL
);
430 std::vector
<std::string
> lines
;
433 const char *prompt("cy# ");
435 if (setjmp(ctrlc_
) != 0) {
443 #if RL_READLINE_VERSION >= 0x0600
445 rl_prep_term_function
= CYDisplayStart
;
446 rl_redisplay_function
= CYDisplayUpdate
;
447 rl_deprep_term_function
= CYDisplayFinish
;
449 rl_prep_term_function
= rl_prep_terminal
;
450 rl_redisplay_function
= rl_redisplay
;
451 rl_deprep_term_function
= rl_deprep_terminal
;
456 char *line(readline(prompt
));
466 if (line
[0] == '?') {
467 std::string
data(line
+ 1);
468 if (data
== "bypass") {
470 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
471 } else if (data
== "debug") {
473 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
474 } else if (data
== "expand") {
476 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
477 } else if (data
== "syntax") {
479 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
489 char *begin(line
), *end(line
+ strlen(line
));
490 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
492 lines
.push_back(begin
);
496 lines
.push_back(begin
);
507 std::istringstream
stream(command_
);
508 CYDriver
driver(stream
);
510 cy::parser
parser(driver
);
511 Setup(driver
, parser
);
513 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
514 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
515 cy::position
begin(error
->location_
.begin
);
516 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
517 cy::position
end(error
->location_
.end
);
519 if (begin
.line
!= lines
.size()) {
521 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
525 for (size_t i(0); i
!= begin
.column
; ++i
)
527 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
529 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
531 std::cerr
<< std::endl
;
534 std::cerr
<< error
->message_
<< std::endl
;
536 add_history(command_
.c_str());
542 driver
.errors_
.clear();
549 if (driver
.program_
== NULL
)
555 std::ostringstream str
;
556 CYOutput
out(str
, options
);
557 Setup(out
, driver
, options
);
558 out
<< *driver
.program_
;
563 add_history(command_
.c_str());
567 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
568 std::cout
<< std::endl
;
571 Run(client_
, syntax
, code
, out_
, expand
);
574 if (append_history$
!= NULL
) {
575 _syscall(close(_syscall(open(histfile
, O_CREAT
| O_WRONLY
, 0600))));
576 (*append_history$
)(histlines
, histfile
);
578 write_history(histfile
);
584 static void *Map(const char *path
, size_t *psize
) {
586 _syscall(fd
= open(path
, O_RDONLY
));
589 _syscall(fstat(fd
, &stat
));
590 size_t size(stat
.st_size
);
595 _syscall(base
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, 0));
601 void InjectLibrary(pid_t pid
);
603 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
604 _aprcall(apr_initialize());
607 apr_pool_create(&pool
, NULL
);
609 bool tty(isatty(STDIN_FILENO
));
613 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
616 pid_t
pid(_not(pid_t
));
620 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
626 apr_status_t
status(apr_getopt(state
,
640 "usage: cycript [-c]"
644 " [<script> [<arg>...]]\n"
658 else if (strcmp(arg
, "rename") == 0)
659 options
.verbose_
= true;
661 else if (strcmp(arg
, "bison") == 0)
665 fprintf(stderr
, "invalid name for -g\n");
672 else if (strcmp(arg
, "minify") == 0)
675 fprintf(stderr
, "invalid name for -n\n");
682 size_t size(strlen(arg
));
685 pid
= strtoul(arg
, &end
, 0);
686 if (arg
+ size
!= end
) {
687 // XXX: arg needs to be escaped in some horrendous way of doom
688 const char *command(apr_pstrcat(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^", arg
, " /{s/^[^ ]* //;q;};};d'", NULL
));
690 if (FILE *pids
= popen(command
, "r")) {
695 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
700 if (size
== sizeof(value
)) {
710 if (value
[size
- 1] == '\n') {
716 size
= strlen(value
);
717 pid
= strtoul(value
, &end
, 0);
718 if (value
+ size
!= end
) fail
:
720 _syscall(pclose(pids
));
723 if (pid
== _not(pid_t
)) {
724 fprintf(stderr
, "invalid pid for -p\n");
741 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
742 fprintf(stderr
, "-p cannot set argv\n");
746 if (pid
!= _not(pid_t
) && compile
) {
747 fprintf(stderr
, "-p conflicts with -c\n");
756 // XXX: const_cast?! wtf gcc :(
757 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
760 if (strcmp(script
, "-") == 0)
765 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
766 fprintf(stderr
, "non-terminal attaching to remote console\n");
772 if (pid
== _not(pid_t
))
775 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
776 struct sockaddr_un address
;
777 memset(&address
, 0, sizeof(address
));
778 address
.sun_family
= AF_UNIX
;
780 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
782 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
783 _syscall(chmod(address
.sun_path
, 0777));
786 _syscall(listen(server
, 1));
788 client_
= _syscall(accept(server
, NULL
, NULL
));
791 unlink(address
.sun_path
);
795 _syscall(close(server
));
803 if (script
== NULL
&& tty
)
809 std::istream
*indirect
;
811 if (script
== NULL
) {
814 indirect
= &std::cin
;
817 start
= reinterpret_cast<char *>(Map(script
, &size
));
820 if (size
>= 2 && start
[0] == '#' && start
[1] == '!') {
823 if (void *line
= memchr(start
, '\n', end
- start
))
824 start
= reinterpret_cast<char *>(line
);
832 CYStream
direct(start
, end
);
833 std::istream
&stream(indirect
== NULL
? direct
: *indirect
);
834 CYDriver
driver(stream
, script
?: "<stdin>");
836 cy::parser
parser(driver
);
837 Setup(driver
, parser
);
839 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
840 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
841 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
842 } else if (driver
.program_
!= NULL
)
844 // XXX: this code means that you can't pipe to another process
845 std::string
code(start
, end
-start
);
846 Run(client_
, false, code
, &std::cout
);
848 std::ostringstream str
;
849 CYOutput
out(str
, options
);
850 Setup(out
, driver
, options
);
851 out
<< *driver
.program_
;
852 std::string
code(str
.str());
856 Run(client_
, false, code
, &std::cout
);
860 apr_pool_destroy(pool
);
865 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
866 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
868 if (status
!= APR_SUCCESS
) {
869 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
872 return Main(argc
, argv
, envp
);
873 } catch (const CYException
&error
) {
875 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));