1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2015 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. 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>
51 #include <sys/socket.h>
52 #include <sys/types.h>
57 #include <sys/types.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
65 #include "Display.hpp"
66 #include "Replace.hpp"
68 #include "Cycript.tab.hh"
71 static volatile enum {
79 static jmp_buf ctrlc_
;
81 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
, bool lower
) {
113 out
.pretty_
= pretty_
;
114 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 CYStatement
*statement(driver
.program_
->statements_
);
230 _assert(statement
!= NULL
);
231 _assert(statement
->next_
== NULL
);
233 CYExpress
*express(dynamic_cast<CYExpress
*>(driver
.program_
->statements_
));
234 _assert(express
!= NULL
);
236 return express
->expression_
;
241 static char **Complete(const char *word
, int start
, int end
) {
242 rl_attempted_completion_over
= ~0;
246 std::string
line(rl_line_buffer
, start
);
247 std::istringstream
stream(command_
+ line
);
248 CYDriver
driver(stream
);
252 cy::parser
parser(driver
);
253 Setup(driver
, parser
);
255 if (parser
.parse() != 0 || !driver
.errors_
.empty())
258 if (driver
.mode_
== CYDriver::AutoNone
)
261 CYExpression
*expression
;
264 CYContext
context(options
);
266 std::ostringstream prefix
;
268 switch (driver
.mode_
) {
269 case CYDriver::AutoPrimary
:
270 expression
= $
CYThis();
273 case CYDriver::AutoDirect
:
274 expression
= driver
.context_
;
277 case CYDriver::AutoIndirect
:
278 expression
= $
CYIndirect(driver
.context_
);
281 case CYDriver::AutoMessage
: {
282 CYDriver::Context
&thing(driver
.contexts_
.back());
283 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
284 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
285 prefix
<< (*part
)->word_
<< ':';
292 std::string
begin(prefix
.str());
294 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
295 " function(object, prefix, word) {\n"
297 " var before = prefix.length;\n"
299 " var entire = prefix.length;\n"
300 " for (var name in object)\n"
301 " if (name.substring(0, entire) == prefix)\n"
302 " names.push(name.substr(before));\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
));
315 // XXX: if this fails we should not try to parse it
317 CYExpression
*result(ParseExpression(json
));
321 CYArray
*array(dynamic_cast<CYArray
*>(result
->Primitive(context
)));
324 Output(false, json
, out_
);
325 rl_forced_update_display();
329 // XXX: use an std::set?
330 typedef std::vector
<std::string
> Completions
;
331 Completions completions
;
336 CYForEach (element
, array
->elements_
) {
337 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
338 _assert(string
!= NULL
);
340 std::string completion
;
341 if (string
->size_
!= 0)
342 completion
.assign(string
->value_
, string
->size_
);
343 else if (driver
.mode_
== CYDriver::AutoMessage
)
348 completions
.push_back(completion
);
354 size_t limit(completion
.size()), size(common
.size());
356 common
= common
.substr(0, limit
);
359 for (limit
= 0; limit
!= size
; ++limit
)
360 if (common
[limit
] != completion
[limit
])
363 common
= common
.substr(0, limit
);
367 size_t count(completions
.size());
371 size_t colon(common
.find(':'));
372 if (colon
!= std::string::npos
)
373 common
= common
.substr(0, colon
+ 1);
374 if (completions
.size() == 1)
377 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
379 results
[0] = strdup(common
.c_str());
381 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
382 results
[++index
] = strdup(i
->c_str());
383 results
[count
+ 1] = NULL
;
388 // need char *, not const char *
389 static char name_
[] = "cycript";
390 static char break_
[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]";
394 std::string histfile_
;
398 History(std::string histfile
) :
402 read_history(histfile_
.c_str());
406 if (append_history$
!= NULL
) {
407 int fd(_syscall(open(histfile_
.c_str(), O_CREAT
| O_WRONLY
, 0600)));
409 _assert((*append_history$
)(histlines_
, histfile_
.c_str()) == 0);
411 _assert(write_history(histfile_
.c_str()) == 0);
415 void operator +=(const std::string
&command
) {
416 add_history(command_
.c_str());
421 static void Console(CYOptions
&options
) {
423 if (const char *home
= getenv("HOME"))
427 if (const char *username
= getenv("LOGNAME"))
428 passwd
= getpwnam(username
);
430 passwd
= getpwuid(getuid());
431 basedir
= passwd
->pw_dir
;
434 basedir
+= "/.cycript";
435 mkdir(basedir
.c_str(), 0700);
438 rl_readline_name
= name_
;
440 History
history(basedir
+ "/history");
450 // rl_completer_word_break_characters is broken in libedit
451 rl_basic_word_break_characters
= break_
;
453 rl_completer_word_break_characters
= break_
;
454 rl_attempted_completion_function
= &Complete
;
455 rl_bind_key('\t', rl_complete
);
457 struct sigaction action
;
458 sigemptyset(&action
.sa_mask
);
459 action
.sa_handler
= &sigint
;
461 sigaction(SIGINT
, &action
, NULL
);
465 std::vector
<std::string
> lines
;
468 const char *prompt("cy# ");
470 if (setjmp(ctrlc_
) != 0) {
478 #if RL_READLINE_VERSION >= 0x0600
480 rl_redisplay_function
= CYDisplayUpdate
;
482 rl_redisplay_function
= rl_redisplay
;
486 char *line(readline(prompt
));
492 } else if (line
[0] == '\0')
497 if (line
[0] == '?') {
498 std::string
data(line
+ 1);
499 if (data
== "bypass") {
501 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
502 } else if (data
== "debug") {
504 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
505 } else if (data
== "destroy") {
507 } else if (data
== "gc") {
508 *out_
<< "collecting... " << std::flush
;
509 CYGarbageCollect(CYGetJSContext());
510 *out_
<< "done." << std::endl
;
511 } else if (data
== "exit") {
513 } else if (data
== "expand") {
515 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
516 } else if (data
== "lower") {
518 *out_
<< "lower == " << (lower
? "true" : "false") << std::endl
;
519 } else if (data
== "syntax") {
521 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
531 char *begin(line
), *end(line
+ strlen(line
));
532 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
534 lines
.push_back(begin
);
538 lines
.push_back(begin
);
549 std::istringstream
stream(command_
);
550 CYDriver
driver(stream
);
552 cy::parser
parser(driver
);
553 Setup(driver
, parser
);
555 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
556 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
557 CYPosition
begin(error
->location_
.begin
);
558 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
559 CYPosition
end(error
->location_
.end
);
561 if (begin
.line
!= lines
.size()) {
563 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
567 for (size_t i(0); i
!= begin
.column
; ++i
)
569 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
571 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
573 std::cerr
<< std::endl
;
576 std::cerr
<< error
->message_
<< std::endl
;
583 driver
.errors_
.clear();
590 if (driver
.program_
== NULL
)
593 std::ostringstream str
;
594 CYOutput
out(str
, options
);
595 Setup(out
, driver
, options
, lower
);
596 out
<< *driver
.program_
;
604 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
605 std::cout
<< std::endl
;
608 Run(client_
, syntax
, code
, out_
, expand
);
612 void InjectLibrary(pid_t
, int, const char *[]);
614 int Main(int argc
, char * const argv
[], char const * const envp
[]) {
615 bool tty(isatty(STDIN_FILENO
));
620 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
623 pid_t
pid(_not(pid_t
));
626 const char *host(NULL
);
627 const char *port(NULL
);
632 int option(getopt_long(argc
, argv
,
641 , (const struct option
[]) {
642 {NULL
, no_argument
, NULL
, 'c'},
643 {NULL
, required_argument
, NULL
, 'g'},
644 {NULL
, required_argument
, NULL
, 'n'},
646 {NULL
, required_argument
, NULL
, 'p'},
648 {NULL
, required_argument
, NULL
, 'r'},
649 {NULL
, no_argument
, NULL
, 's'},
650 {0, 0, 0, 0}}, NULL
));
659 "usage: cycript [-c]"
664 " [<script> [<arg>...]]\n"
672 fprintf(stderr
, "only one of -[c"
676 "r] may be used at a time\n");
687 else if (strcmp(optarg
, "rename") == 0)
688 options
.verbose_
= true;
690 else if (strcmp(optarg
, "bison") == 0)
694 fprintf(stderr
, "invalid name for -g\n");
701 else if (strcmp(optarg
, "minify") == 0)
704 fprintf(stderr
, "invalid name for -n\n");
711 size_t size(strlen(optarg
));
714 pid
= strtoul(optarg
, &end
, 0);
715 if (optarg
+ size
!= end
) {
716 // XXX: arg needs to be escaped in some horrendous way of doom
717 // XXX: this is a memory leak now because I just don't care enough
719 asprintf(&command
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg
);
721 if (FILE *pids
= popen(command
, "r")) {
726 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
731 if (size
== sizeof(value
))
739 if (value
[size
- 1] == '\n') {
745 size
= strlen(value
);
746 pid
= strtoul(value
, &end
, 0);
747 if (value
+ size
!= end
) fail
:
749 _syscall(pclose(pids
));
752 if (pid
== _not(pid_t
)) {
753 fprintf(stderr
, "unable to find process `%s' using ps\n", optarg
);
761 //size_t size(strlen(optarg));
763 char *colon(strrchr(optarg
, ':'));
765 fprintf(stderr
, "missing colon in hostspec\n");
770 port = strtoul(colon + 1, &end, 10);
771 if (end != optarg + size) {
772 fprintf(stderr, "invalid port in hostspec\n");
797 if (pid
!= _not(pid_t
) && argc
> 1) {
798 fprintf(stderr
, "-p cannot set argv\n");
807 // XXX: const_cast?! wtf gcc :(
808 CYSetArgs(argc
- 1, const_cast<const char **>(argv
+ 1));
811 if (strcmp(script
, "-") == 0)
816 if (pid
== _not(pid_t
))
834 } server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0)));
836 struct sockaddr_un address
;
837 memset(&address
, 0, sizeof(address
));
838 address
.sun_family
= AF_UNIX
;
841 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
842 tmp
= "/Library/Caches";
847 sprintf(address
.sun_path
, "%s/.s.cy.%u", tmp
, getpid());
848 unlink(address
.sun_path
);
853 File(const char *path
) :
861 } file(address
.sun_path
);
863 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
864 _syscall(chmod(address
.sun_path
, 0777));
866 _syscall(listen(server
, 1));
867 InjectLibrary(pid
, 1, (const char *[]) {address
.sun_path
, NULL
});
868 client_
= _syscall(accept(server
, NULL
, NULL
));
874 if (client_
== -1 && host
!= NULL
&& port
!= NULL
) {
875 struct addrinfo hints
;
876 memset(&hints
, 0, sizeof(hints
));
877 hints
.ai_family
= AF_UNSPEC
;
878 hints
.ai_socktype
= SOCK_STREAM
;
879 hints
.ai_protocol
= 0;
882 struct addrinfo
*infos
;
883 _syscall(getaddrinfo(host
, port
, &hints
, &infos
));
885 _assert(infos
!= NULL
); try {
886 for (struct addrinfo
*info(infos
); info
!= NULL
; info
= info
->ai_next
) {
887 int client(_syscall(socket(info
->ai_family
, info
->ai_socktype
, info
->ai_protocol
))); try {
888 _syscall(connect(client
, info
->ai_addr
, info
->ai_addrlen
));
892 _syscall(close(client
));
902 if (script
== NULL
&& tty
)
907 std::istream
*stream
;
908 if (script
== NULL
) {
912 stream
= new std::fstream(script
, std::ios::in
| std::ios::binary
);
913 _assert(!stream
->fail());
916 CYDriver
driver(*stream
, script
);
917 cy::parser
parser(driver
);
918 Setup(driver
, parser
);
920 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
921 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
922 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
923 } else if (driver
.program_
!= NULL
) {
924 std::ostringstream str
;
925 CYOutput
out(str
, options
);
926 Setup(out
, driver
, options
, true);
927 out
<< *driver
.program_
;
928 std::string
code(str
.str());
932 Run(client_
, false, code
, &std::cout
);
939 int main(int argc
, char * const argv
[], char const * const envp
[]) {
941 return Main(argc
, argv
, envp
);
942 } catch (const CYException
&error
) {
944 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));