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) {
102 void Setup(CYDriver
&driver
, cy::parser
&parser
) {
105 parser
.set_debug_level(1);
108 driver
.strict_
= true;
111 void Setup(CYOutput
&out
, CYDriver
&driver
, CYOptions
&options
, bool lower
) {
112 out
.pretty_
= pretty_
;
113 CYContext
context(options
);
115 driver
.program_
->Replace(context
);
118 static CYUTF8String
Run(CYPool
&pool
, int client
, CYUTF8String code
) {
125 json
= CYExecute(CYGetJSContext(), pool
, code
);
137 _assert(CYSendAll(client
, &size
, sizeof(size
)));
138 _assert(CYSendAll(client
, code
.data
, code
.size
));
140 _assert(CYRecvAll(client
, &size
, sizeof(size
)));
141 if (size
== _not(uint32_t))
144 char *temp(new(pool
) char[size
+ 1]);
145 _assert(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 CYStatement
*statement(driver
.program_
->statements_
);
229 _assert(statement
!= NULL
);
230 _assert(statement
->next_
== NULL
);
232 CYExpress
*express(dynamic_cast<CYExpress
*>(driver
.program_
->statements_
));
233 _assert(express
!= NULL
);
235 return express
->expression_
;
240 static char **Complete(const char *word
, int start
, int end
) {
241 rl_attempted_completion_over
= ~0;
245 std::string
line(rl_line_buffer
, start
);
246 std::istringstream
stream(command_
+ line
);
247 CYDriver
driver(stream
);
251 cy::parser
parser(driver
);
252 Setup(driver
, parser
);
254 if (parser
.parse() != 0 || !driver
.errors_
.empty())
257 if (driver
.mode_
== CYDriver::AutoNone
)
260 CYExpression
*expression
;
263 CYContext
context(options
);
265 std::ostringstream prefix
;
267 switch (driver
.mode_
) {
268 case CYDriver::AutoPrimary
:
269 expression
= $
CYThis();
272 case CYDriver::AutoDirect
:
273 expression
= driver
.context_
;
276 case CYDriver::AutoIndirect
:
277 expression
= $
CYIndirect(driver
.context_
);
280 case CYDriver::AutoMessage
: {
281 CYDriver::Context
&thing(driver
.contexts_
.back());
282 expression
= $
M($
C1($
V("object_getClass"), thing
.context_
), $
S("messages"));
283 for (CYDriver::Context::Words::const_iterator
part(thing
.words_
.begin()); part
!= thing
.words_
.end(); ++part
)
284 prefix
<< (*part
)->word_
<< ':';
291 std::string
begin(prefix
.str());
293 driver
.program_
= $
CYProgram($
CYExpress($
C3(ParseExpression(
294 " function(object, prefix, word) {\n"
296 " var before = prefix.length;\n"
298 " var entire = prefix.length;\n"
299 " for (var name in object)\n"
300 " if (name.substring(0, entire) == prefix)\n"
301 " names.push(name.substr(before));\n"
304 ), expression
, $
S(begin
.c_str()), $
S(word
))));
306 driver
.program_
->Replace(context
);
308 std::ostringstream str
;
309 CYOutput
out(str
, options
);
310 out
<< *driver
.program_
;
312 std::string
code(str
.str());
313 CYUTF8String
json(Run(pool
, client_
, code
));
314 // XXX: if this fails we should not try to parse it
316 CYExpression
*result(ParseExpression(json
));
320 CYArray
*array(dynamic_cast<CYArray
*>(result
->Primitive(context
)));
323 Output(false, json
, out_
);
324 rl_forced_update_display();
328 // XXX: use an std::set?
329 typedef std::vector
<std::string
> Completions
;
330 Completions completions
;
335 CYForEach (element
, array
->elements_
) {
336 CYString
*string(dynamic_cast<CYString
*>(element
->value_
));
337 _assert(string
!= NULL
);
339 std::string completion
;
340 if (string
->size_
!= 0)
341 completion
.assign(string
->value_
, string
->size_
);
342 else if (driver
.mode_
== CYDriver::AutoMessage
)
347 completions
.push_back(completion
);
353 size_t limit(completion
.size()), size(common
.size());
355 common
= common
.substr(0, limit
);
358 for (limit
= 0; limit
!= size
; ++limit
)
359 if (common
[limit
] != completion
[limit
])
362 common
= common
.substr(0, limit
);
366 size_t count(completions
.size());
370 size_t colon(common
.find(':'));
371 if (colon
!= std::string::npos
)
372 common
= common
.substr(0, colon
+ 1);
373 if (completions
.size() == 1)
376 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count
+ 2))));
378 results
[0] = strdup(common
.c_str());
380 for (Completions::const_iterator
i(completions
.begin()); i
!= completions
.end(); ++i
)
381 results
[++index
] = strdup(i
->c_str());
382 results
[count
+ 1] = NULL
;
387 // need char *, not const char *
388 static char name_
[] = "cycript";
389 static char break_
[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
393 std::string histfile_
;
397 History(std::string histfile
) :
401 read_history(histfile_
.c_str());
405 if (append_history$
!= NULL
) {
406 int fd(_syscall(open(histfile_
.c_str(), O_CREAT
| O_WRONLY
, 0600)));
408 _assert((*append_history$
)(histlines_
, histfile_
.c_str()) == 0);
410 _assert(write_history(histfile_
.c_str()) == 0);
414 void operator +=(const std::string
&command
) {
415 add_history(command_
.c_str());
420 static void Console(CYOptions
&options
) {
422 if (const char *home
= getenv("HOME"))
426 if (const char *username
= getenv("LOGNAME"))
427 passwd
= getpwnam(username
);
429 passwd
= getpwuid(getuid());
430 basedir
= passwd
->pw_dir
;
433 basedir
+= "/.cycript";
434 mkdir(basedir
.c_str(), 0700);
437 rl_readline_name
= name_
;
439 History
history(basedir
+ "/history");
449 // rl_completer_word_break_characters is broken in libedit
450 rl_basic_word_break_characters
= break_
;
452 rl_completer_word_break_characters
= break_
;
453 rl_attempted_completion_function
= &Complete
;
454 rl_bind_key('\t', rl_complete
);
456 struct sigaction action
;
457 sigemptyset(&action
.sa_mask
);
458 action
.sa_handler
= &sigint
;
460 sigaction(SIGINT
, &action
, NULL
);
464 std::vector
<std::string
> lines
;
467 const char *prompt("cy# ");
469 if (setjmp(ctrlc_
) != 0) {
477 #if RL_READLINE_VERSION >= 0x0600
479 rl_redisplay_function
= CYDisplayUpdate
;
481 rl_redisplay_function
= rl_redisplay
;
485 char *line(readline(prompt
));
491 } else if (line
[0] == '\0')
496 if (line
[0] == '?') {
497 std::string
data(line
+ 1);
498 if (data
== "bypass") {
500 *out_
<< "bypass == " << (bypass
? "true" : "false") << std::endl
;
501 } else if (data
== "debug") {
503 *out_
<< "debug == " << (debug
? "true" : "false") << std::endl
;
504 } else if (data
== "destroy") {
506 } else if (data
== "gc") {
507 *out_
<< "collecting... " << std::flush
;
508 CYGarbageCollect(CYGetJSContext());
509 *out_
<< "done." << std::endl
;
510 } else if (data
== "exit") {
512 } else if (data
== "expand") {
514 *out_
<< "expand == " << (expand
? "true" : "false") << std::endl
;
515 } else if (data
== "lower") {
517 *out_
<< "lower == " << (lower
? "true" : "false") << std::endl
;
518 } else if (data
== "syntax") {
520 *out_
<< "syntax == " << (syntax
? "true" : "false") << std::endl
;
530 char *begin(line
), *end(line
+ strlen(line
));
531 while (char *nl
= reinterpret_cast<char *>(memchr(begin
, '\n', end
- begin
))) {
533 lines
.push_back(begin
);
537 lines
.push_back(begin
);
548 std::istringstream
stream(command_
);
549 CYDriver
driver(stream
);
551 cy::parser
parser(driver
);
552 Setup(driver
, parser
);
554 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
555 for (CYDriver::Errors::const_iterator
error(driver
.errors_
.begin()); error
!= driver
.errors_
.end(); ++error
) {
556 CYPosition
begin(error
->location_
.begin
);
557 if (begin
.line
!= lines
.size() || begin
.column
< lines
.back().size() || error
->warning_
) {
558 CYPosition
end(error
->location_
.end
);
560 if (begin
.line
!= lines
.size()) {
562 std::cerr
<< lines
[begin
.line
- 1] << std::endl
;
566 for (size_t i(0); i
!= begin
.column
; ++i
)
568 if (begin
.line
!= end
.line
|| begin
.column
== end
.column
)
570 else for (size_t i(0), e(end
.column
- begin
.column
); i
!= e
; ++i
)
572 std::cerr
<< std::endl
;
575 std::cerr
<< error
->message_
<< std::endl
;
582 driver
.errors_
.clear();
589 if (driver
.program_
== NULL
)
592 std::ostringstream str
;
593 CYOutput
out(str
, options
);
594 Setup(out
, driver
, options
, lower
);
595 out
<< *driver
.program_
;
603 Write(syntax
, code
.c_str(), code
.size(), std::cout
);
604 std::cout
<< std::endl
;
607 Run(client_
, syntax
, code
, out_
, expand
);
611 void InjectLibrary(pid_t
, int, const char *[]);
613 int Main(int argc
, char * const argv
[], char const * const envp
[]) {
614 bool tty(isatty(STDIN_FILENO
));
619 append_history$
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history"));
622 pid_t
pid(_not(pid_t
));
625 const char *host(NULL
);
626 const char *port(NULL
);
631 int option(getopt_long(argc
, argv
,
640 , (const struct option
[]) {
641 {NULL
, no_argument
, NULL
, 'c'},
642 {NULL
, required_argument
, NULL
, 'g'},
643 {NULL
, required_argument
, NULL
, 'n'},
645 {NULL
, required_argument
, NULL
, 'p'},
647 {NULL
, required_argument
, NULL
, 'r'},
648 {NULL
, no_argument
, NULL
, 's'},
649 {0, 0, 0, 0}}, NULL
));
658 "usage: cycript [-c]"
663 " [<script> [<arg>...]]\n"
671 fprintf(stderr
, "only one of -[c"
675 "r] may be used at a time\n");
686 else if (strcmp(optarg
, "rename") == 0)
687 options
.verbose_
= true;
689 else if (strcmp(optarg
, "bison") == 0)
693 fprintf(stderr
, "invalid name for -g\n");
700 else if (strcmp(optarg
, "minify") == 0)
703 fprintf(stderr
, "invalid name for -n\n");
710 size_t size(strlen(optarg
));
713 pid
= strtoul(optarg
, &end
, 0);
714 if (optarg
+ size
!= end
) {
715 // XXX: arg needs to be escaped in some horrendous way of doom
716 // XXX: this is a memory leak now because I just don't care enough
718 asprintf(&command
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg
);
720 if (FILE *pids
= popen(command
, "r")) {
725 size_t read(fread(value
+ size
, 1, sizeof(value
) - size
, pids
));
730 if (size
== sizeof(value
))
738 if (value
[size
- 1] == '\n') {
744 size
= strlen(value
);
745 pid
= strtoul(value
, &end
, 0);
746 if (value
+ size
!= end
) fail
:
748 _syscall(pclose(pids
));
751 if (pid
== _not(pid_t
)) {
752 fprintf(stderr
, "unable to find process `%s' using ps\n", optarg
);
760 //size_t size(strlen(optarg));
762 char *colon(strrchr(optarg
, ':'));
764 fprintf(stderr
, "missing colon in hostspec\n");
769 port = strtoul(colon + 1, &end, 10);
770 if (end != optarg + size) {
771 fprintf(stderr, "invalid port in hostspec\n");
796 if (pid
!= _not(pid_t
) && argc
> 1) {
797 fprintf(stderr
, "-p cannot set argv\n");
806 // XXX: const_cast?! wtf gcc :(
807 CYSetArgs(argc
- 1, const_cast<const char **>(argv
+ 1));
810 if (strcmp(script
, "-") == 0)
815 if (pid
== _not(pid_t
))
833 } server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0)));
835 struct sockaddr_un address
;
836 memset(&address
, 0, sizeof(address
));
837 address
.sun_family
= AF_UNIX
;
840 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
841 tmp
= "/Library/Caches";
846 sprintf(address
.sun_path
, "%s/.s.cy.%u", tmp
, getpid());
847 unlink(address
.sun_path
);
852 File(const char *path
) :
860 } file(address
.sun_path
);
862 _syscall(bind(server
, reinterpret_cast<sockaddr
*>(&address
), SUN_LEN(&address
)));
863 _syscall(chmod(address
.sun_path
, 0777));
865 _syscall(listen(server
, 1));
866 InjectLibrary(pid
, 1, (const char *[]) {address
.sun_path
, NULL
});
867 client_
= _syscall(accept(server
, NULL
, NULL
));
873 if (client_
== -1 && host
!= NULL
&& port
!= NULL
) {
874 struct addrinfo hints
;
875 memset(&hints
, 0, sizeof(hints
));
876 hints
.ai_family
= AF_UNSPEC
;
877 hints
.ai_socktype
= SOCK_STREAM
;
878 hints
.ai_protocol
= 0;
881 struct addrinfo
*infos
;
882 _syscall(getaddrinfo(host
, port
, &hints
, &infos
));
884 _assert(infos
!= NULL
); try {
885 for (struct addrinfo
*info(infos
); info
!= NULL
; info
= info
->ai_next
) {
886 int client(_syscall(socket(info
->ai_family
, info
->ai_socktype
, info
->ai_protocol
))); try {
887 _syscall(connect(client
, info
->ai_addr
, info
->ai_addrlen
));
891 _syscall(close(client
));
901 if (script
== NULL
&& tty
)
906 std::istream
*stream
;
907 if (script
== NULL
) {
911 stream
= new std::fstream(script
, std::ios::in
| std::ios::binary
);
912 _assert(!stream
->fail());
915 CYDriver
driver(*stream
, script
);
916 cy::parser
parser(driver
);
917 Setup(driver
, parser
);
919 if (parser
.parse() != 0 || !driver
.errors_
.empty()) {
920 for (CYDriver::Errors::const_iterator
i(driver
.errors_
.begin()); i
!= driver
.errors_
.end(); ++i
)
921 std::cerr
<< i
->location_
.begin
<< ": " << i
->message_
<< std::endl
;
922 } else if (driver
.program_
!= NULL
) {
923 std::ostringstream str
;
924 CYOutput
out(str
, options
);
925 Setup(out
, driver
, options
, true);
926 out
<< *driver
.program_
;
927 std::string
code(str
.str());
931 Run(client_
, false, code
, &std::cout
);
938 int main(int argc
, char * const argv
[], char const * const envp
[]) {
940 return Main(argc
, argv
, envp
);
941 } catch (const CYException
&error
) {
943 fprintf(stderr
, "%s\n", error
.PoolCString(pool
));