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"
34 #ifdef HAVE_READLINE_H
37 #include <readline/readline.h>
43 #include <readline/history.h>
49 #include <sys/socket.h>
50 #include <sys/types.h>
55 #include <sys/types.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
61 #include <apr_getopt.h>
62 #include <apr_pools.h>
63 #include <apr_strings.h>
67 #include "Display.hpp"
68 #include "Replace.hpp"
70 #include "Cycript.tab.hh"
73 static volatile enum {
81 static jmp_buf ctrlc_
;
83 static void sigint(int) {
104 void Setup(CYDriver
&driver
, cy::parser
&parser
) {
107 parser
.set_debug_level(1);
110 driver
.strict_
= true;
113 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
) {
114 out
.pretty_
= pretty_
;
115 CYContext
context(options
);
116 driver
.program_
->Replace(context
);
119 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
126 json
= CYExecute(CYGetJSContext(), pool
, code
);
138 _assert(CYSendAll(client
, &size
, sizeof(size
)));
139 _assert(CYSendAll(client
, code
.data
, code
.size
));
141 _assert(CYRecvAll(client
, &size
, sizeof(size
)));
142 if (size
== _not(uint32_t))
145 char *temp(new(pool
) char[size
+ 1]);
146 _assert(CYRecvAll(client
, temp
, size
));
153 return CYUTF8String(json
, size
);
156 static CYUTF8String
Run(CYPool
&pool
, int client
, const std::string
&code
) {
157 return Run(pool
, client
, CYUTF8String(code
.c_str(), code
.size()));
160 static std::ostream
*out_
;
162 static void Write(bool syntax
, const char *data
, size_t size
, std::ostream
&out
) {
164 CYLexerHighlight(data
, size
, out
);
166 out
.write(data
, size
);
169 static void Output(bool syntax
, CYUTF8String json
, std::ostream
*out
, bool expand
= false) {
170 const char *data(json
.data
);
171 size_t size(json
.size
);
173 if (data
== NULL
|| out
== NULL
)
177 data
[0] != '@' && data
[0] != '"' && data
[0] != '\'' ||
178 data
[0] == '@' && data
[1] != '"' && data
[1] != '\''
180 Write(syntax
, data
, size
, *out
);
181 else for (size_t i(0); i
!= size
; ++i
)
184 else switch(data
[++i
]) {
185 case '\0': goto done
;
186 case '\\': *out
<< '\\'; break;
187 case '\'': *out
<< '\''; break;
188 case '"': *out
<< '"'; break;
189 case 'b': *out
<< '\b'; break;
190 case 'f': *out
<< '\f'; break;
191 case 'n': *out
<< '\n'; break;
192 case 'r': *out
<< '\r'; break;
193 case 't': *out
<< '\t'; break;
194 case 'v': *out
<< '\v'; break;
195 default: *out
<< '\\'; --i
; break;
202 static void Run(int client
, bool syntax
, const char *data
, size_t size
, std::ostream
*out
= NULL
, bool expand
= false) {
204 Output(syntax
, Run(pool
, client
, CYUTF8String(data
, size
)), out
, expand
);
207 static void Run(int client
, bool syntax
, std::string
&code
, std::ostream
*out
= NULL
, bool expand
= false) {
208 Run(client
, syntax
, code
.c_str(), code
.size(), out
, expand
);
211 int (*append_history$
)(int, const char *);
213 static std::string command_
;
215 static CYExpression
*ParseExpression(CYUTF8String code
) {
216 std::stringstream stream
;
217 stream
<< '(' << code
<< ')';
218 CYDriver
driver(stream
);
220 cy::parser
parser(driver
);
221 Setup(driver
, parser
);
223 if (parser
.parse() != 0 || !driver
.errors_
.empty())
227 CYContext
context(options
);
229 // XXX: this could be replaced with a CYStatement::Primitive()
230 if (CYExpress
*express
= dynamic_cast<CYExpress
*>(driver
.program_
->statements_
))
231 return express
->expression_
->Primitive(context
);
238 static char **Complete(const char *word
, int start
, int end
) {
239 rl_attempted_completion_over
= TRUE
;
243 std::string
line(rl_line_buffer
, start
);
244 std::istringstream
stream(command_
+ line
);
245 CYDriver
driver(stream
);
249 cy::parser
parser(driver
);
250 Setup(driver
, parser
);
252 if (parser
.parse() != 0 || !driver
.errors_
.empty())
255 if (driver
.mode_
== CYDriver::AutoNone
)
258 CYExpression
*expression
;
261 CYContext
context(options
);
263 std::ostringstream prefix
;
265 switch (driver
.mode_
) {
266 case CYDriver::AutoPrimary
:
267 expression
= $
CYThis();
270 case CYDriver::AutoDirect
:
271 expression
= driver
.context_
;
274 case CYDriver::AutoIndirect
:
275 expression
= $
CYIndirect(driver
.context_
);
278 case CYDriver::AutoMessage
: {
279 CYDriver::Context
&thing(driver
.contexts_
.back());
280 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
281 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
282 prefix
<< (*part
)->word_
<< ':';
289 std::string
begin(prefix
.str());
291 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
292 " function(object, prefix, word) {\n"
294 " var before = prefix.length;\n"
296 " var entire = prefix.length;\n"
297 " for (name in object)\n"
298 " if (name.substring(0, entire) == prefix)\n"
299 " names.push(name.substr(before));\n"
302 ), expression
, $
S(begin
.c_str()), $
S(word
))));
304 driver
.program_
->Replace(context
);
306 std::ostringstream str
;
307 CYOutput
out(str
, options
);
308 out
<< *driver
.program_
;
310 std::string
code(str
.str());
311 CYUTF8String
json(Run(pool
, client_
, code
));
312 // XXX: if this fails we should not try to parse it
314 CYExpression
*result(ParseExpression(json
));
318 CYArray
*array(dynamic_cast<CYArray
*>(result
));
322 Output(false, json
, out_
);
323 rl_forced_update_display();
327 // XXX: use an std::set?
328 typedef std::vector
<std::string
> Completions
;
329 Completions completions
;
334 CYForEach (element
, array
->elements_
) {
335 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
336 _assert(string
!= NULL
);
338 std::string completion
;
339 if (string
->size_
!= 0)
340 completion
.assign(string
->value_
, string
->size_
);
341 else if (driver
.mode_
== CYDriver::AutoMessage
)
346 completions
.push_back(completion
);
352 size_t limit(completion
.size()), size(common
.size());
354 common
= common
.substr(0, limit
);
357 for (limit
= 0; limit
!= size
; ++limit
)
358 if (common
[limit
] != completion
[limit
])
361 common
= common
.substr(0, limit
);
365 size_t count(completions
.size());
369 size_t colon(common
.find(':'));
370 if (colon
!= std::string::npos
)
371 common
= common
.substr(0, colon
+ 1);
372 if (completions
.size() == 1)
375 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
377 results
[0] = strdup(common
.c_str());
379 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
380 results
[++index
] = strdup(i
->c_str());
381 results
[count
+ 1] = NULL
;
386 // need char *, not const char *
387 static char name_
[] = "cycript";
388 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
392 std::string histfile_
;
396 History(std::string histfile
) :
400 read_history(histfile_
.c_str());
404 if (append_history$
!= NULL
) {
405 _syscall(close(_syscall(open(histfile_
.c_str(), O_CREAT
| O_WRONLY
, 0600))));
406 _assert((*append_history$
)(histlines_
, histfile_
.c_str()) == 0);
408 _assert(write_history(histfile_
.c_str()) == 0);
412 void operator +=(const std::string
&command
) {
413 add_history(command_
.c_str());
418 static void Console(CYOptions
&options
) {
422 if (const char *username
= getenv("LOGNAME"))
423 passwd
= getpwnam(username
);
425 passwd
= getpwuid(getuid());
427 std::string
basedir(passwd
->pw_dir
);
428 basedir
+= "/.cycript";
429 mkdir(basedir
.c_str(), 0700);
432 rl_readline_name
= name_
;
434 History
history(basedir
+ "/history");
443 // rl_completer_word_break_characters is broken in libedit
444 rl_basic_word_break_characters
= break_
;
446 rl_completer_word_break_characters
= break_
;
447 rl_attempted_completion_function
= &Complete
;
448 rl_bind_key('\t', rl_complete
);
450 struct sigaction action
;
451 sigemptyset(&action
.sa_mask
);
452 action
.sa_handler
= &sigint
;
454 sigaction(SIGINT
, &action
, NULL
);
458 std::vector
<std::string
> lines
;
461 const char *prompt("cy# ");
463 if (setjmp(ctrlc_
) != 0) {
471 #if RL_READLINE_VERSION >= 0x0600
473 rl_redisplay_function
= CYDisplayUpdate
;
475 rl_redisplay_function
= rl_redisplay
;
479 char *line(readline(prompt
));
485 } else if (line
[0] == '\0')
490 if (line
[0] == '?') {
491 std::string
data(line
+ 1);
492 if (data
== "bypass") {
494 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
495 } else if (data
== "debug") {
497 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
498 } else if (data
== "expand") {
500 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
501 } else if (data
== "syntax") {
503 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
513 char *begin(line
), *end(line
+ strlen(line
));
514 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
516 lines
.push_back(begin
);
520 lines
.push_back(begin
);
531 std::istringstream
stream(command_
);
532 CYDriver
driver(stream
);
534 cy::parser
parser(driver
);
535 Setup(driver
, parser
);
537 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
538 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
539 cy::position
begin(error
->location_
.begin
);
540 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
541 cy::position
end(error
->location_
.end
);
543 if (begin
.line
!= lines
.size()) {
545 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
549 for (size_t i(0); i
!= begin
.column
; ++i
)
551 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
553 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
555 std::cerr
<< std::endl
;
558 std::cerr
<< error
->message_
<< std::endl
;
565 driver
.errors_
.clear();
572 if (driver
.program_
== NULL
)
575 std::ostringstream str
;
576 CYOutput
out(str
, options
);
577 Setup(out
, driver
, options
);
578 out
<< *driver
.program_
;
585 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
586 std::cout
<< std::endl
;
589 Run(client_
, syntax
, code
, out_
, expand
);
593 void InjectLibrary(pid_t pid
);
595 int Main(int argc
, char const * const argv
[], char const * const envp
[]) {
596 _aprcall(apr_initialize());
599 apr_pool_create(&pool
, NULL
);
601 bool tty(isatty(STDIN_FILENO
));
605 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
608 pid_t
pid(_not(pid_t
));
611 const char *host(NULL
);
612 const char *port(NULL
);
615 _aprcall(apr_getopt_init(&state
, pool
, argc
, argv
));
621 apr_status_t
status(apr_getopt(state
,
636 "usage: cycript [-c]"
641 " [<script> [<arg>...]]\n"
655 else if (strcmp(arg
, "rename") == 0)
656 options
.verbose_
= true;
658 else if (strcmp(arg
, "bison") == 0)
662 fprintf(stderr
, "invalid name for -g\n");
669 else if (strcmp(arg
, "minify") == 0)
672 fprintf(stderr
, "invalid name for -n\n");
679 size_t size(strlen(arg
));
682 pid
= strtoul(arg
, &end
, 0);
683 if (arg
+ size
!= end
) {
684 // XXX: arg needs to be escaped in some horrendous way of doom
685 const char *command(apr_pstrcat(pool
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^", arg
, " /{s/^[^ ]* //;q;};};d'", NULL
));
687 if (FILE *pids
= popen(command
, "r")) {
692 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
697 if (size
== sizeof(value
)) {
707 if (value
[size
- 1] == '\n') {
713 size
= strlen(value
);
714 pid
= strtoul(value
, &end
, 0);
715 if (value
+ size
!= end
) fail
:
717 _syscall(pclose(pids
));
720 if (pid
== _not(pid_t
)) {
721 fprintf(stderr
, "invalid pid for -p\n");
729 //size_t size(strlen(arg));
731 char *colon(strrchr(arg
, ':'));
733 fprintf(stderr
, "missing colon in hostspec\n");
738 port = strtoul(colon + 1, &end, 10);
739 if (end != arg + size) {
740 fprintf(stderr, "invalid port in hostspec\n");
759 if (pid
!= _not(pid_t
) && ind
< argc
- 1) {
760 fprintf(stderr
, "-p cannot set argv\n");
764 if (pid
!= _not(pid_t
) && compile
) {
765 fprintf(stderr
, "-p conflicts with -c\n");
774 // XXX: const_cast?! wtf gcc :(
775 CYSetArgs(argc
- ind
- 1, const_cast<const char **>(argv
+ ind
+ 1));
778 if (strcmp(script
, "-") == 0)
783 if (pid
!= _not(pid_t
) && script
== NULL
&& !tty
) {
784 fprintf(stderr
, "non-terminal attaching to remote console\n");
790 if (pid
== _not(pid_t
))
793 int server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); try {
794 struct sockaddr_un address
;
795 memset(&address
, 0, sizeof(address
));
796 address
.sun_family
= AF_UNIX
;
798 sprintf(address
.sun_path
, "/tmp/.s.cy.%u", getpid());
800 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
801 _syscall(chmod(address
.sun_path
, 0777));
804 _syscall(listen(server
, 1));
806 client_
= _syscall(accept(server
, NULL
, NULL
));
809 unlink(address
.sun_path
);
813 _syscall(close(server
));
821 if (client_
== -1 && host
!= NULL
&& port
!= NULL
) {
822 struct addrinfo hints
;
823 memset(&hints
, 0, sizeof(hints
));
824 hints
.ai_family
= AF_UNSPEC
;
825 hints
.ai_socktype
= SOCK_STREAM
;
826 hints
.ai_protocol
= 0;
829 struct addrinfo
*infos
;
830 _syscall(getaddrinfo(host
, port
, &hints
, &infos
));
832 _assert(infos
!= NULL
); try {
833 for (struct addrinfo
*info(infos
); info
!= NULL
; info
= info
->ai_next
) {
834 int client(_syscall(socket(info
->ai_family
, info
->ai_socktype
, info
->ai_protocol
))); try {
835 _syscall(connect(client
, info
->ai_addr
, info
->ai_addrlen
));
839 _syscall(close(client
));
849 if (script
== NULL
&& tty
)
854 std::istream
*stream
;
855 if (script
== NULL
) {
859 stream
= new std::fstream(script
, std::ios::in
| std::ios::binary
);
860 _assert(!stream
->fail());
863 CYDriver
driver(*stream
, script
);
864 cy::parser
parser(driver
);
865 Setup(driver
, parser
);
867 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
868 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
869 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
870 } else if (driver
.program_
!= NULL
) {
871 std::ostringstream str
;
872 CYOutput
out(str
, options
);
873 Setup(out
, driver
, options
);
874 out
<< *driver
.program_
;
875 std::string
code(str
.str());
879 Run(client_
, false, code
, &std::cout
);
883 apr_pool_destroy(pool
);
888 int main(int argc
, char const * const argv
[], char const * const envp
[]) {
889 apr_status_t
status(apr_app_initialize(&argc
, &argv
, &envp
));
891 if (status
!= APR_SUCCESS
) {
892 fprintf(stderr
, "apr_app_initialize() != APR_SUCCESS\n");
895 return Main(argc
, argv
, envp
);
896 } catch (const CYException
&error
) {
898 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));