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> 
  66 #include <mach/mach_time.h> 
  69 #include "Display.hpp" 
  71 #include "Highlight.hpp" 
  72 #include "Replace.hpp" 
  74 static volatile enum { 
  82 static jmp_buf ctrlc_
; 
  84 static void sigint(int) { 
 105 void Setup(CYDriver 
&driver
) { 
 109         driver
.strict_ 
= true; 
 112 void Setup(CYOutput 
&out
, CYDriver 
&driver
, CYOptions 
&options
, bool lower
) { 
 113     out
.pretty_ 
= pretty_
; 
 115         driver
.Replace(options
); 
 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_
; 
 216 static CYUTF8String 
Run(CYPool 
&pool
, const std::string 
&code
) { 
 217     return Run(pool
, client_
, code
); 
 220 static char **Complete(const char *word
, int start
, int end
) { 
 221     rl_attempted_completion_over 
= ~0; 
 222     std::string 
line(rl_line_buffer
, start
); 
 223     return CYComplete(word
, command_ 
+ line
, &Run
); 
 226 // need char *, not const char * 
 227 static char name_
[] = "cycript"; 
 228 static char break_
[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]"; 
 232     std::string histfile_
; 
 236     History(std::string histfile
) : 
 240         read_history(histfile_
.c_str()); 
 244         if (append_history$ 
!= NULL
) { 
 245             int fd(_syscall(open(histfile_
.c_str(), O_CREAT 
| O_WRONLY
, 0600))); 
 247             _assert((*append_history$
)(histlines_
, histfile_
.c_str()) == 0); 
 249             _assert(write_history(histfile_
.c_str()) == 0); 
 253     void operator +=(const std::string 
&command
) { 
 254         add_history(command
.c_str()); 
 259 static void Console(CYOptions 
&options
) { 
 261     if (const char *home 
= getenv("HOME")) 
 265         if (const char *username 
= getenv("LOGNAME")) 
 266             passwd 
= getpwnam(username
); 
 268             passwd 
= getpwuid(getuid()); 
 269         basedir 
= passwd
->pw_dir
; 
 272     basedir 
+= "/.cycript"; 
 273     mkdir(basedir
.c_str(), 0700); 
 276     rl_readline_name 
= name_
; 
 278     History 
history(basedir 
+ "/history"); 
 288     // rl_completer_word_break_characters is broken in libedit 
 289     rl_basic_word_break_characters 
= break_
; 
 291     rl_completer_word_break_characters 
= break_
; 
 292     rl_attempted_completion_function 
= &Complete
; 
 293     rl_bind_key('\t', rl_complete
); 
 295     struct sigaction action
; 
 296     sigemptyset(&action
.sa_mask
); 
 297     action
.sa_handler 
= &sigint
; 
 299     sigaction(SIGINT
, &action
, NULL
); 
 303         std::vector
<std::string
> lines
; 
 306         const char *prompt("cy# "); 
 308         if (setjmp(ctrlc_
) != 0) { 
 316 #if RL_READLINE_VERSION >= 0x0600 
 318             rl_redisplay_function 
= CYDisplayUpdate
; 
 320             rl_redisplay_function 
= rl_redisplay
; 
 324         char *line(readline(prompt
)); 
 330         } else if (line
[0] == '\0') 
 335             if (line
[0] == '?') { 
 336                 std::string 
data(line 
+ 1); 
 337                 if (data 
== "bypass") { 
 339                     *out_ 
<< "bypass == " << (bypass 
? "true" : "false") << std::endl
; 
 340                 } else if (data 
== "debug") { 
 342                     *out_ 
<< "debug == " << (debug 
? "true" : "false") << std::endl
; 
 343                 } else if (data 
== "destroy") { 
 345                 } else if (data 
== "gc") { 
 346                     *out_ 
<< "collecting... " << std::flush
; 
 347                     CYGarbageCollect(CYGetJSContext()); 
 348                     *out_ 
<< "done." << std::endl
; 
 349                 } else if (data 
== "exit") { 
 351                 } else if (data 
== "expand") { 
 353                     *out_ 
<< "expand == " << (expand 
? "true" : "false") << std::endl
; 
 354                 } else if (data 
== "lower") { 
 356                     *out_ 
<< "lower == " << (lower 
? "true" : "false") << std::endl
; 
 357                 } else if (data 
== "syntax") { 
 359                     *out_ 
<< "syntax == " << (syntax 
? "true" : "false") << std::endl
; 
 370         char *begin(line
), *end(line 
+ strlen(line
)); 
 371         while (char *nl 
= reinterpret_cast<char *>(memchr(begin
, '\n', end 
- begin
))) { 
 373             lines
.push_back(begin
); 
 377         lines
.push_back(begin
); 
 386             std::istringstream 
stream(command_
); 
 389             CYDriver 
driver(pool
, stream
); 
 392             bool failed(driver
.Parse()); 
 394             if (failed 
|| !driver
.errors_
.empty()) { 
 395                 for (CYDriver::Errors::const_iterator 
error(driver
.errors_
.begin()); error 
!= driver
.errors_
.end(); ++error
) { 
 396                     CYPosition 
begin(error
->location_
.begin
); 
 397                     if (begin
.line 
!= lines
.size() + 1 || error
->warning_
) { 
 398                         CYPosition 
end(error
->location_
.end
); 
 400                         if (begin
.line 
!= lines
.size()) { 
 402                             std::cerr 
<< lines
[begin
.line 
- 1] << std::endl
; 
 406                         for (size_t i(0); i 
!= begin
.column
; ++i
) 
 408                         if (begin
.line 
!= end
.line 
|| begin
.column 
== end
.column
) 
 410                         else for (size_t i(0), e(end
.column 
- begin
.column
); i 
!= e
; ++i
) 
 412                         std::cerr 
<< std::endl
; 
 415                         std::cerr 
<< error
->message_ 
<< std::endl
; 
 417                         history 
+= command_
.substr(0, command_
.size() - 1); 
 422                 driver
.errors_
.clear(); 
 428             if (driver
.program_ 
== NULL
) 
 432             CYOutput 
out(str
, options
); 
 433             Setup(out
, driver
, options
, lower
); 
 434             out 
<< *driver
.program_
; 
 438         history 
+= command_
.substr(0, command_
.size() - 1); 
 442             Write(syntax
, code
.c_str(), code
.size(), std::cout
); 
 443             std::cout 
<< std::endl
; 
 446         Run(client_
, syntax
, code
, out_
, expand
); 
 450 void InjectLibrary(pid_t
, int, const char *const []); 
 452 static uint64_t CYGetTime() { 
 454     return mach_absolute_time(); 
 456     struct timespec spec
; 
 457     clock_gettime(CLOCK_MONOTONIC
, &spec
); 
 458     return spec
.tv_sec 
* UINT64_C(1000000000) + spec
.tv_nsec
; 
 462 int Main(int argc
, char * const argv
[], char const * const envp
[]) { 
 463     bool tty(isatty(STDIN_FILENO
)); 
 468     append_history$ 
= (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT
, "append_history")); 
 471     pid_t 
pid(_not(pid_t
)); 
 474     const char *host(NULL
); 
 475     const char *port(NULL
); 
 480         int option(getopt_long(argc
, argv
, 
 489         , (const struct option
[]) { 
 490             {NULL
, no_argument
, NULL
, 'c'}, 
 491             {NULL
, required_argument
, NULL
, 'g'}, 
 492             {NULL
, required_argument
, NULL
, 'n'}, 
 494             {NULL
, required_argument
, NULL
, 'p'}, 
 496             {NULL
, required_argument
, NULL
, 'r'}, 
 497             {NULL
, no_argument
, NULL
, 's'}, 
 498         {0, 0, 0, 0}}, NULL
)); 
 507                     "usage: cycript [-c]" 
 512                     " [<script> [<arg>...]]\n" 
 520                     fprintf(stderr
, "only one of -[c" 
 524                     "r] may be used at a time\n"); 
 535                 else if (strcmp(optarg
, "rename") == 0) 
 536                     options
.verbose_ 
= true; 
 537                 else if (strcmp(optarg
, "bison") == 0) 
 539                 else if (strcmp(optarg
, "timing") == 0) 
 542                     fprintf(stderr
, "invalid name for -g\n"); 
 549                 else if (strcmp(optarg
, "minify") == 0) 
 552                     fprintf(stderr
, "invalid name for -n\n"); 
 559                 size_t size(strlen(optarg
)); 
 562                 pid 
= strtoul(optarg
, &end
, 0); 
 563                 if (optarg 
+ size 
!= end
) { 
 564                     // XXX: arg needs to be escaped in some horrendous way of doom 
 565                     // XXX: this is a memory leak now because I just don't care enough 
 567                     int writ(asprintf(&command
, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg
)); 
 570                     if (FILE *pids 
= popen(command
, "r")) { 
 575                             size_t read(fread(value 
+ size
, 1, sizeof(value
) - size
, pids
)); 
 580                                 if (size 
== sizeof(value
)) 
 588                         if (value
[size 
- 1] == '\n') { 
 594                         size 
= strlen(value
); 
 595                         pid 
= strtoul(value
, &end
, 0); 
 596                         if (value 
+ size 
!= end
) fail
: 
 598                         _syscall(pclose(pids
)); 
 601                     if (pid 
== _not(pid_t
)) { 
 602                         fprintf(stderr
, "unable to find process `%s' using ps\n", optarg
); 
 610                 //size_t size(strlen(optarg)); 
 612                 char *colon(strrchr(optarg
, ':')); 
 614                     fprintf(stderr
, "missing colon in hostspec\n"); 
 619                 port = strtoul(colon + 1, &end, 10); 
 620                 if (end != optarg + size) { 
 621                     fprintf(stderr, "invalid port in hostspec\n"); 
 646     if (pid 
!= _not(pid_t
) && argc 
> 1) { 
 647         fprintf(stderr
, "-p cannot set argv\n"); 
 656         // XXX: const_cast?! wtf gcc :( 
 657         CYSetArgs(argc 
- 1, const_cast<const char **>(argv 
+ 1)); 
 660         if (strcmp(script
, "-") == 0) 
 665     if (pid 
== _not(pid_t
)) 
 683         } server(_syscall(socket(PF_UNIX
, SOCK_STREAM
, 0))); 
 685         struct sockaddr_un address
; 
 686         memset(&address
, 0, sizeof(address
)); 
 687         address
.sun_family 
= AF_UNIX
; 
 690 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__)) 
 691         tmp 
= "/Library/Caches"; 
 696         sprintf(address
.sun_path
, "%s/.s.cy.%u", tmp
, getpid()); 
 697         unlink(address
.sun_path
); 
 702             File(const char *path
) : 
 710         } file(address
.sun_path
); 
 712         _syscall(bind(server
, reinterpret_cast<sockaddr 
*>(&address
), SUN_LEN(&address
))); 
 713         _syscall(chmod(address
.sun_path
, 0777)); 
 715         _syscall(listen(server
, 1)); 
 716         const char *const argv
[] = {address
.sun_path
, NULL
}; 
 717         InjectLibrary(pid
, 1, argv
); 
 718         client_ 
= _syscall(accept(server
, NULL
, NULL
)); 
 724     if (client_ 
== -1 && host 
!= NULL 
&& port 
!= NULL
) { 
 725         struct addrinfo hints
; 
 726         memset(&hints
, 0, sizeof(hints
)); 
 727         hints
.ai_family 
= AF_UNSPEC
; 
 728         hints
.ai_socktype 
= SOCK_STREAM
; 
 729         hints
.ai_protocol 
= 0; 
 732         struct addrinfo 
*infos
; 
 733         _syscall(getaddrinfo(host
, port
, &hints
, &infos
)); 
 735         _assert(infos 
!= NULL
); try { 
 736             for (struct addrinfo 
*info(infos
); info 
!= NULL
; info 
= info
->ai_next
) { 
 737                 int client(_syscall(socket(info
->ai_family
, info
->ai_socktype
, info
->ai_protocol
))); try { 
 738                     _syscall(connect(client
, info
->ai_addr
, info
->ai_addrlen
)); 
 742                     _syscall(close(client
)); 
 752     if (script 
== NULL 
&& tty
) 
 755         std::istream 
*stream
; 
 756         if (script 
== NULL
) { 
 760             stream 
= new std::fstream(script
, std::ios::in 
| std::ios::binary
); 
 761             _assert(!stream
->fail()); 
 765             std::stringbuf buffer
; 
 766             stream
->get(buffer
, '\0'); 
 767             _assert(!stream
->fail()); 
 771             uint64_t start(CYGetTime()); 
 774                 stream 
= new std::istringstream(buffer
.str()); 
 777                 CYDriver 
driver(pool
, *stream
, script
); 
 780                 uint64_t begin(CYGetTime()); 
 782                 uint64_t end(CYGetTime()); 
 786                 average 
+= (end 
- begin 
- average
) / ++samples
; 
 788                 uint64_t now(CYGetTime()); 
 791                 else if ((now 
- start
) / 1000000000 >= 1) 
 792                     std::cout 
<< std::fixed 
<< average 
<< '\t' << (end 
- begin
) << '\t' << samples 
<< std::endl
; 
 798             stream 
= new std::istringstream(buffer
.str()); 
 803         CYDriver 
driver(pool
, *stream
, script
); 
 806         bool failed(driver
.Parse()); 
 808         if (failed 
|| !driver
.errors_
.empty()) { 
 809             for (CYDriver::Errors::const_iterator 
i(driver
.errors_
.begin()); i 
!= driver
.errors_
.end(); ++i
) 
 810                 std::cerr 
<< i
->location_
.begin 
<< ": " << i
->message_ 
<< std::endl
; 
 811         } else if (driver
.program_ 
!= NULL
) { 
 813             CYOutput 
out(str
, options
); 
 814             Setup(out
, driver
, options
, true); 
 815             out 
<< *driver
.program_
; 
 816             std::string 
code(str
.str()); 
 820                 Run(client_
, false, code
, &std::cout
); 
 827 int main(int argc
, char * const argv
[], char const * const envp
[]) { 
 829         return Main(argc
, argv
, envp
); 
 830     } catch (const CYException 
&error
) { 
 832         fprintf(stderr
, "%s\n", error
.PoolCString(pool
));