]> git.saurik.com Git - cycript.git/blame - Console.cpp
Add a local install target (why not?) to xcode.mk.
[cycript.git] / Console.cpp
CommitLineData
b3378a02 1/* Cycript - Optimizing JavaScript Compiler/Runtime
c15969fd 2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
b4aa79af
JF
3*/
4
c15969fd 5/* GNU General Public License, Version 3 {{{ */
b4aa79af 6/*
c15969fd
JF
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.
b4aa79af 11 *
c15969fd
JF
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.
b4aa79af 16 *
c15969fd 17 * You should have received a copy of the GNU General Public License
b3378a02
JF
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
19**/
b4aa79af
JF
20/* }}} */
21
30ddc20c 22#include "cycript.hpp"
057f943f 23
9cad30fa
JF
24#ifdef CY_EXECUTE
25#include "JavaScript.hpp"
26#endif
27
057f943f 28#include <cstdio>
0df6a201 29#include <fstream>
057f943f
JF
30#include <sstream>
31
32#include <setjmp.h>
33
aff87425
DWT
34#ifdef HAVE_READLINE_H
35#include <readline.h>
36#else
057f943f 37#include <readline/readline.h>
aff87425
DWT
38#endif
39
40#ifdef HAVE_HISTORY_H
41#include <history.h>
42#else
057f943f 43#include <readline/history.h>
aff87425 44#endif
057f943f 45
b09da87b
JF
46#include <errno.h>
47#include <unistd.h>
48
666eedb9 49#include <sys/socket.h>
b09da87b
JF
50#include <sys/types.h>
51#include <sys/stat.h>
52#include <fcntl.h>
666eedb9 53#include <netdb.h>
b09da87b 54
967067aa
JF
55#include <sys/types.h>
56#include <sys/socket.h>
57#include <netinet/in.h>
58#include <sys/un.h>
b1589845 59#include <pwd.h>
967067aa 60
06edab7d 61#include <apr_getopt.h>
0cbeddf8
JF
62#include <apr_pools.h>
63#include <apr_strings.h>
06edab7d 64
da858962
JF
65#include <dlfcn.h>
66
74296173 67#include "Display.hpp"
b12a9965
JF
68#include "Replace.hpp"
69
70#include "Cycript.tab.hh"
71#include "Driver.hpp"
7e5391fd 72
4e39dc0b
JF
73static volatile enum {
74 Working,
75 Parsing,
76 Running,
77 Sending,
78 Waiting,
79} mode_;
80
057f943f
JF
81static jmp_buf ctrlc_;
82
579ed526 83static void sigint(int) {
4e39dc0b
JF
84 switch (mode_) {
85 case Working:
86 return;
87 case Parsing:
88 longjmp(ctrlc_, 1);
89 case Running:
90 throw "*** Ctrl-C";
91 case Sending:
92 return;
93 case Waiting:
94 return;
95 }
057f943f
JF
96}
97
cac61857
JF
98#if YYDEBUG
99static bool bison_;
100#endif
b10bd496 101static bool strict_;
11c1cc16 102static bool pretty_;
cac61857 103
b10bd496 104void Setup(CYDriver &driver, cy::parser &parser) {
cac61857
JF
105#if YYDEBUG
106 if (bison_)
107 parser.set_debug_level(1);
108#endif
b10bd496
JF
109 if (strict_)
110 driver.strict_ = true;
cac61857
JF
111}
112
36bf49c4 113void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) {
11c1cc16 114 out.pretty_ = pretty_;
2eb8215d 115 CYContext context(options);
36bf49c4
JF
116 if (lower)
117 driver.program_->Replace(context);
11c1cc16
JF
118}
119
7e5391fd 120static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
967067aa 121 const char *json;
9d79cefc 122 uint32_t size;
7e5391fd 123
b166b11b 124 if (client == -1) {
4e39dc0b 125 mode_ = Running;
2aa77fd8 126#ifdef CY_EXECUTE
89d16b11 127 json = CYExecute(CYGetJSContext(), pool, code);
2aa77fd8
JF
128#else
129 json = NULL;
130#endif
4e39dc0b 131 mode_ = Working;
dd221c6b
JF
132 if (json == NULL)
133 size = 0;
134 else
6ec85c5b
JF
135 size = strlen(json);
136 } else {
4e39dc0b 137 mode_ = Sending;
0ced2e47 138 size = code.size;
a1f3555e
JF
139 _assert(CYSendAll(client, &size, sizeof(size)));
140 _assert(CYSendAll(client, code.data, code.size));
4e39dc0b 141 mode_ = Waiting;
a1f3555e 142 _assert(CYRecvAll(client, &size, sizeof(size)));
9d79cefc 143 if (size == _not(uint32_t))
967067aa
JF
144 json = NULL;
145 else {
146 char *temp(new(pool) char[size + 1]);
a1f3555e 147 _assert(CYRecvAll(client, temp, size));
967067aa
JF
148 temp[size] = '\0';
149 json = temp;
150 }
4e39dc0b 151 mode_ = Working;
4cf49641 152 }
b09da87b 153
7e5391fd
JF
154 return CYUTF8String(json, size);
155}
156
157static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
158 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
159}
160
2e2ed904 161static std::ostream *out_;
a3f4a8e1 162
82a02ede
JF
163static void Write(bool syntax, const char *data, size_t size, std::ostream &out) {
164 if (syntax)
165 CYLexerHighlight(data, size, out);
166 else
167 out.write(data, size);
168}
169
170static void Output(bool syntax, CYUTF8String json, std::ostream *out, bool expand = false) {
a3f4a8e1
JF
171 const char *data(json.data);
172 size_t size(json.size);
173
2e2ed904 174 if (data == NULL || out == NULL)
a3f4a8e1
JF
175 return;
176
0881deb5
JF
177 if (!expand ||
178 data[0] != '@' && data[0] != '"' && data[0] != '\'' ||
179 data[0] == '@' && data[1] != '"' && data[1] != '\''
180 )
82a02ede 181 Write(syntax, data, size, *out);
a3f4a8e1
JF
182 else for (size_t i(0); i != size; ++i)
183 if (data[i] != '\\')
2e2ed904 184 *out << data[i];
a3f4a8e1
JF
185 else switch(data[++i]) {
186 case '\0': goto done;
2e2ed904
JF
187 case '\\': *out << '\\'; break;
188 case '\'': *out << '\''; break;
189 case '"': *out << '"'; break;
190 case 'b': *out << '\b'; break;
191 case 'f': *out << '\f'; break;
192 case 'n': *out << '\n'; break;
193 case 'r': *out << '\r'; break;
194 case 't': *out << '\t'; break;
195 case 'v': *out << '\v'; break;
196 default: *out << '\\'; --i; break;
a3f4a8e1 197 }
6ec85c5b 198
a3f4a8e1 199 done:
2e2ed904 200 *out << std::endl;
a3f4a8e1
JF
201}
202
82a02ede 203static void Run(int client, bool syntax, const char *data, size_t size, std::ostream *out = NULL, bool expand = false) {
a3f4a8e1 204 CYPool pool;
82a02ede 205 Output(syntax, Run(pool, client, CYUTF8String(data, size)), out, expand);
b09da87b
JF
206}
207
82a02ede
JF
208static void Run(int client, bool syntax, std::string &code, std::ostream *out = NULL, bool expand = false) {
209 Run(client, syntax, code.c_str(), code.size(), out, expand);
fcc64bb5
JF
210}
211
da858962
JF
212int (*append_history$)(int, const char *);
213
7e5391fd
JF
214static std::string command_;
215
2eb8215d 216static CYExpression *ParseExpression(CYUTF8String code) {
d3b63265
JF
217 std::stringstream stream;
218 stream << '(' << code << ')';
219 CYDriver driver(stream);
7e5391fd
JF
220
221 cy::parser parser(driver);
222 Setup(driver, parser);
223
224 if (parser.parse() != 0 || !driver.errors_.empty())
df24434f 225 return NULL;
7e5391fd 226
e06e5ee1
JF
227 CYOptions options;
228 CYContext context(options);
229
fd5cdf97
JF
230 CYStatement *statement(driver.program_->statements_);
231 _assert(statement != NULL);
232 _assert(statement->next_ == NULL);
e06e5ee1 233
fd5cdf97
JF
234 CYExpress *express(dynamic_cast<CYExpress *>(driver.program_->statements_));
235 _assert(express != NULL);
236
237 return express->expression_;
7e5391fd
JF
238}
239
240static int client_;
241
242static char **Complete(const char *word, int start, int end) {
243 rl_attempted_completion_over = TRUE;
244
2eb8215d 245 CYLocalPool pool;
7e5391fd
JF
246
247 std::string line(rl_line_buffer, start);
d3b63265
JF
248 std::istringstream stream(command_ + line);
249 CYDriver driver(stream);
7e5391fd
JF
250
251 driver.auto_ = true;
252
d3b63265
JF
253 cy::parser parser(driver);
254 Setup(driver, parser);
255
7e5391fd
JF
256 if (parser.parse() != 0 || !driver.errors_.empty())
257 return NULL;
258
259 if (driver.mode_ == CYDriver::AutoNone)
260 return NULL;
261
262 CYExpression *expression;
263
264 CYOptions options;
2eb8215d 265 CYContext context(options);
7e5391fd
JF
266
267 std::ostringstream prefix;
268
269 switch (driver.mode_) {
270 case CYDriver::AutoPrimary:
271 expression = $ CYThis();
272 break;
273
274 case CYDriver::AutoDirect:
275 expression = driver.context_;
276 break;
277
278 case CYDriver::AutoIndirect:
279 expression = $ CYIndirect(driver.context_);
280 break;
281
282 case CYDriver::AutoMessage: {
283 CYDriver::Context &thing(driver.contexts_.back());
aa926c8b 284 expression = $M($C1($V("object_getClass"), thing.context_), $S("messages"));
7e5391fd
JF
285 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
286 prefix << (*part)->word_ << ':';
287 } break;
288
289 default:
290 _assert(false);
291 }
292
2a18313c 293 std::string begin(prefix.str());
7e5391fd 294
2eb8215d 295 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
2a18313c 296 " function(object, prefix, word) {\n"
7e5391fd 297 " var names = [];\n"
5a3f7a01
JF
298 " var before = prefix.length;\n"
299 " prefix += word;\n"
300 " var entire = prefix.length;\n"
3e6377db 301 " for (var name in object)\n"
5a3f7a01
JF
302 " if (name.substring(0, entire) == prefix)\n"
303 " names.push(name.substr(before));\n"
7e5391fd
JF
304 " return names;\n"
305 " }\n"
2a18313c 306 ), expression, $S(begin.c_str()), $S(word))));
7e5391fd
JF
307
308 driver.program_->Replace(context);
309
310 std::ostringstream str;
311 CYOutput out(str, options);
312 out << *driver.program_;
313
314 std::string code(str.str());
315 CYUTF8String json(Run(pool, client_, code));
1b2613d3 316 // XXX: if this fails we should not try to parse it
7e5391fd 317
2eb8215d 318 CYExpression *result(ParseExpression(json));
df24434f
JF
319 if (result == NULL)
320 return NULL;
321
fd5cdf97 322 CYArray *array(dynamic_cast<CYArray *>(result->Primitive(context)));
a3f4a8e1 323 if (array == NULL) {
2e2ed904 324 *out_ << '\n';
82a02ede 325 Output(false, json, out_);
a3f4a8e1
JF
326 rl_forced_update_display();
327 return NULL;
328 }
7e5391fd
JF
329
330 // XXX: use an std::set?
331 typedef std::vector<std::string> Completions;
332 Completions completions;
333
334 std::string common;
335 bool rest(false);
336
c2c9f509 337 CYForEach (element, array->elements_) {
7e5391fd
JF
338 CYString *string(dynamic_cast<CYString *>(element->value_));
339 _assert(string != NULL);
340
763aa499
JF
341 std::string completion;
342 if (string->size_ != 0)
343 completion.assign(string->value_, string->size_);
344 else if (driver.mode_ == CYDriver::AutoMessage)
345 completion = "]";
346 else
347 continue;
348
7e5391fd
JF
349 completions.push_back(completion);
350
351 if (!rest) {
352 common = completion;
353 rest = true;
354 } else {
355 size_t limit(completion.size()), size(common.size());
356 if (size > limit)
357 common = common.substr(0, limit);
358 else
359 limit = size;
360 for (limit = 0; limit != size; ++limit)
361 if (common[limit] != completion[limit])
362 break;
363 if (limit != size)
364 common = common.substr(0, limit);
365 }
366 }
367
368 size_t count(completions.size());
369 if (count == 0)
370 return NULL;
371
c41590b2
JF
372 size_t colon(common.find(':'));
373 if (colon != std::string::npos)
374 common = common.substr(0, colon + 1);
6dccefa9
JF
375 if (completions.size() == 1)
376 common += ' ';
c41590b2 377
7e5391fd
JF
378 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
379
380 results[0] = strdup(common.c_str());
381 size_t index(0);
382 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
383 results[++index] = strdup(i->c_str());
384 results[count + 1] = NULL;
385
386 return results;
387}
388
389// need char *, not const char *
390static char name_[] = "cycript";
108c5fc8 391static char break_[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
7e5391fd 392
da136f88
JF
393class History {
394 private:
395 std::string histfile_;
396 size_t histlines_;
397
398 public:
399 History(std::string histfile) :
400 histfile_(histfile),
401 histlines_(0)
402 {
403 read_history(histfile_.c_str());
404 }
405
406 ~History() {
407 if (append_history$ != NULL) {
408 _syscall(close(_syscall(open(histfile_.c_str(), O_CREAT | O_WRONLY, 0600))));
409 _assert((*append_history$)(histlines_, histfile_.c_str()) == 0);
410 } else {
411 _assert(write_history(histfile_.c_str()) == 0);
412 }
413 }
414
415 void operator +=(const std::string &command) {
416 add_history(command_.c_str());
417 ++histlines_;
418 }
419};
420
2eb8215d
JF
421static void Console(CYOptions &options) {
422 CYPool pool;
423
b1589845
JF
424 passwd *passwd;
425 if (const char *username = getenv("LOGNAME"))
426 passwd = getpwnam(username);
427 else
428 passwd = getpwuid(getuid());
429
da136f88
JF
430 std::string basedir(passwd->pw_dir);
431 basedir += "/.cycript";
432 mkdir(basedir.c_str(), 0700);
b1589845 433
7e5391fd
JF
434 rl_initialize();
435 rl_readline_name = name_;
436
da136f88 437 History history(basedir + "/history");
b1589845 438
1f8eae40
JF
439 bool bypass(false);
440 bool debug(false);
6ec85c5b 441 bool expand(false);
36bf49c4 442 bool lower(true);
cd98d280 443 bool syntax(true);
1f8eae40 444
2e2ed904 445 out_ = &std::cout;
057f943f 446
7e5391fd
JF
447 // rl_completer_word_break_characters is broken in libedit
448 rl_basic_word_break_characters = break_;
bc1e87aa
JF
449
450 rl_completer_word_break_characters = break_;
7e5391fd
JF
451 rl_attempted_completion_function = &Complete;
452 rl_bind_key('\t', rl_complete);
057f943f
JF
453
454 struct sigaction action;
455 sigemptyset(&action.sa_mask);
456 action.sa_handler = &sigint;
457 action.sa_flags = 0;
458 sigaction(SIGINT, &action, NULL);
459
460 restart: for (;;) {
7e5391fd 461 command_.clear();
057f943f
JF
462 std::vector<std::string> lines;
463
931b816a
JF
464 bool extra(false);
465 const char *prompt("cy# ");
466
057f943f 467 if (setjmp(ctrlc_) != 0) {
4e39dc0b 468 mode_ = Working;
2e2ed904 469 *out_ << std::endl;
057f943f
JF
470 goto restart;
471 }
472
057f943f 473 read:
cd98d280
JF
474
475#if RL_READLINE_VERSION >= 0x0600
8a81192b 476 if (syntax)
cd98d280 477 rl_redisplay_function = CYDisplayUpdate;
8a81192b 478 else
cd98d280 479 rl_redisplay_function = rl_redisplay;
cd98d280
JF
480#endif
481
4e39dc0b 482 mode_ = Parsing;
057f943f 483 char *line(readline(prompt));
4e39dc0b 484 mode_ = Working;
cd98d280 485
79357996
JF
486 if (line == NULL) {
487 *out_ << std::endl;
057f943f 488 break;
79357996 489 } else if (line[0] == '\0')
67f1fc6b 490 goto read;
931b816a
JF
491
492 if (!extra) {
493 extra = true;
6ec85c5b 494 if (line[0] == '?') {
1f8eae40
JF
495 std::string data(line + 1);
496 if (data == "bypass") {
497 bypass = !bypass;
2e2ed904 498 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
1f8eae40
JF
499 } else if (data == "debug") {
500 debug = !debug;
2e2ed904 501 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
8fab8594
JF
502 } else if (data == "destroy") {
503 CYDestroyContext();
51b6165e 504 } else if (data == "gc") {
e7ff0158 505 *out_ << "collecting... " << std::flush;
51b6165e 506 CYGarbageCollect(CYGetJSContext());
e7ff0158 507 *out_ << "done." << std::endl;
6a5fd0d9
JF
508 } else if (data == "exit") {
509 return;
6ec85c5b
JF
510 } else if (data == "expand") {
511 expand = !expand;
2e2ed904 512 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
36bf49c4
JF
513 } else if (data == "lower") {
514 lower = !lower;
515 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
82a02ede
JF
516 } else if (data == "syntax") {
517 syntax = !syntax;
518 *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl;
1f8eae40 519 }
be8c2078
JF
520 command_ = line;
521 history += command_;
931b816a
JF
522 goto restart;
523 }
524 }
525
7e5391fd 526 command_ += line;
e818f0e0
JF
527
528 char *begin(line), *end(line + strlen(line));
529 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
530 *nl = '\0';
531 lines.push_back(begin);
532 begin = nl + 1;
533 }
534
535 lines.push_back(begin);
536
057f943f
JF
537 free(line);
538
1f8eae40
JF
539 std::string code;
540
541 if (bypass)
7e5391fd 542 code = command_;
1f8eae40 543 else {
2eb8215d 544 CYLocalPool pool;
d3b63265
JF
545
546 std::istringstream stream(command_);
547 CYDriver driver(stream);
548
1f8eae40 549 cy::parser parser(driver);
b10bd496 550 Setup(driver, parser);
1f8eae40 551
1f8eae40 552 if (parser.parse() != 0 || !driver.errors_.empty()) {
f0360d51
JF
553 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
554 cy::position begin(error->location_.begin);
c247172c 555 if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) {
f0360d51 556 cy::position end(error->location_.end);
48e3be8a 557
f0360d51
JF
558 if (begin.line != lines.size()) {
559 std::cerr << " | ";
560 std::cerr << lines[begin.line - 1] << std::endl;
561 }
48e3be8a 562
c52a09b8 563 std::cerr << "....";
97c8a8fc 564 for (size_t i(0); i != begin.column; ++i)
f0360d51 565 std::cerr << '.';
48e3be8a 566 if (begin.line != end.line || begin.column == end.column)
f0360d51
JF
567 std::cerr << '^';
568 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
569 std::cerr << '^';
570 std::cerr << std::endl;
48e3be8a 571
f0360d51
JF
572 std::cerr << " | ";
573 std::cerr << error->message_ << std::endl;
48e3be8a 574
da136f88 575 history += command_;
1f8eae40
JF
576 goto restart;
577 }
578 }
057f943f 579
1f8eae40 580 driver.errors_.clear();
057f943f 581
7e5391fd 582 command_ += '\n';
1f8eae40
JF
583 prompt = "cy> ";
584 goto read;
057f943f
JF
585 }
586
b10bd496 587 if (driver.program_ == NULL)
1f8eae40 588 goto restart;
057f943f 589
0df6a201
JF
590 std::ostringstream str;
591 CYOutput out(str, options);
36bf49c4 592 Setup(out, driver, options, lower);
0df6a201
JF
593 out << *driver.program_;
594 code = str.str();
057f943f
JF
595 }
596
da136f88 597 history += command_;
057f943f 598
82a02ede 599 if (debug) {
f43fcb85 600 std::cout << "cy= ";
82a02ede
JF
601 Write(syntax, code.c_str(), code.size(), std::cout);
602 std::cout << std::endl;
603 }
057f943f 604
82a02ede 605 Run(client_, syntax, code, out_, expand);
b09da87b 606 }
b09da87b 607}
057f943f 608
b6961e53 609void InjectLibrary(pid_t pid);
06edab7d 610
b6961e53 611int Main(int argc, char const * const argv[], char const * const envp[]) {
0cbeddf8
JF
612 _aprcall(apr_initialize());
613
614 apr_pool_t *pool;
615 apr_pool_create(&pool, NULL);
616
48e3be8a 617 bool tty(isatty(STDIN_FILENO));
75b0a457 618 bool compile(false);
96746747 619 bool target(false);
de9fc71b 620 CYOptions options;
967067aa 621
e4676127 622 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
da858962 623
2aa77fd8
JF
624#ifdef CY_ATTACH
625 pid_t pid(_not(pid_t));
626#endif
627
666eedb9
JF
628 const char *host(NULL);
629 const char *port(NULL);
630
06edab7d
JF
631 apr_getopt_t *state;
632 _aprcall(apr_getopt_init(&state, pool, argc, argv));
633
634 for (;;) {
63e43c8b 635 int opt;
06edab7d
JF
636 const char *arg;
637
63e43c8b
JF
638 apr_status_t status(apr_getopt_long(state, (apr_getopt_option_t[]) {
639 {NULL, 'c', false, NULL},
640 {NULL, 'g', true, NULL},
641 {NULL, 'n', true, NULL},
2aa77fd8 642#ifdef CY_ATTACH
63e43c8b 643 {NULL, 'p', true, NULL},
2aa77fd8 644#endif
63e43c8b
JF
645 {NULL, 'r', true, NULL},
646 {NULL, 's', false, NULL},
647 {0, 0, 0, 0}}, &opt, &arg));
06edab7d
JF
648
649 switch (status) {
650 case APR_EOF:
651 goto getopt;
652 case APR_BADCH:
653 case APR_BADARG:
654 fprintf(stderr,
655 "usage: cycript [-c]"
2aa77fd8 656#ifdef CY_ATTACH
69caa5be 657 " [-p <pid|name>]"
2aa77fd8 658#endif
666eedb9 659 " [-r <host:port>]"
06edab7d
JF
660 " [<script> [<arg>...]]\n"
661 );
662 return 1;
663 default:
664 _aprcall(status);
665 }
967067aa 666
06edab7d 667 switch (opt) {
96746747
JF
668 target:
669 if (!target)
670 target = true;
671 else {
672 fprintf(stderr, "only one of -[c"
673#ifdef CY_ATTACH
674 "p"
675#endif
676 "r] may be used at a time\n");
677 return 1;
678 }
679 break;
680
06edab7d
JF
681 case 'c':
682 compile = true;
96746747 683 goto target;
75b0a457 684
06edab7d
JF
685 case 'g':
686 if (false);
de9fc71b
JF
687 else if (strcmp(arg, "rename") == 0)
688 options.verbose_ = true;
cac61857 689#if YYDEBUG
5ef46cc0 690 else if (strcmp(arg, "bison") == 0)
06edab7d 691 bison_ = true;
cac61857 692#endif
06edab7d
JF
693 else {
694 fprintf(stderr, "invalid name for -g\n");
695 return 1;
696 }
697 break;
cac61857 698
06edab7d
JF
699 case 'n':
700 if (false);
5ef46cc0 701 else if (strcmp(arg, "minify") == 0)
06edab7d
JF
702 pretty_ = true;
703 else {
704 fprintf(stderr, "invalid name for -n\n");
705 return 1;
706 }
707 break;
11c1cc16 708
2aa77fd8 709#ifdef CY_ATTACH
06edab7d 710 case 'p': {
5ef46cc0 711 size_t size(strlen(arg));
06edab7d 712 char *end;
69caa5be 713
5ef46cc0
JF
714 pid = strtoul(arg, &end, 0);
715 if (arg + size != end) {
69caa5be 716 // XXX: arg needs to be escaped in some horrendous way of doom
0cbeddf8 717 const char *command(apr_pstrcat(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^", arg, " /{s/^[^ ]* //;q;};};d'", NULL));
69caa5be
JF
718
719 if (FILE *pids = popen(command, "r")) {
720 char value[32];
721 size = 0;
722
723 for (;;) {
724 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
725 if (read == 0)
726 break;
727 else {
728 size += read;
04aa6240 729 if (size == sizeof(value))
b166b11b 730 goto fail;
69caa5be
JF
731 }
732 }
733
734 size:
735 if (size == 0)
b166b11b 736 goto fail;
69caa5be
JF
737 if (value[size - 1] == '\n') {
738 --size;
739 goto size;
740 }
741
742 value[size] = '\0';
743 size = strlen(value);
744 pid = strtoul(value, &end, 0);
b166b11b 745 if (value + size != end) fail:
69caa5be 746 pid = _not(pid_t);
69caa5be
JF
747 _syscall(pclose(pids));
748 }
749
750 if (pid == _not(pid_t)) {
04aa6240 751 fprintf(stderr, "unable to find process `%s' using ps\n", arg);
69caa5be
JF
752 return 1;
753 }
06edab7d 754 }
96746747 755 } goto target;
2aa77fd8 756#endif
b10bd496 757
666eedb9
JF
758 case 'r': {
759 //size_t size(strlen(arg));
760
761 char *colon(strrchr(arg, ':'));
762 if (colon == NULL) {
763 fprintf(stderr, "missing colon in hostspec\n");
764 return 1;
765 }
766
767 /*char *end;
768 port = strtoul(colon + 1, &end, 10);
769 if (end != arg + size) {
770 fprintf(stderr, "invalid port in hostspec\n");
771 return 1;
772 }*/
773
774 host = arg;
775 *colon = '\0';
776 port = colon + 1;
96746747 777 } goto target;
666eedb9 778
06edab7d
JF
779 case 's':
780 strict_ = true;
781 break;
782 }
967067aa
JF
783 } getopt:;
784
b09da87b 785 const char *script;
5ef46cc0 786 int ind(state->ind);
b09da87b 787
2aa77fd8 788#ifdef CY_ATTACH
5ef46cc0 789 if (pid != _not(pid_t) && ind < argc - 1) {
fcc64bb5
JF
790 fprintf(stderr, "-p cannot set argv\n");
791 return 1;
792 }
2aa77fd8 793#endif
75b0a457 794
5ef46cc0 795 if (ind == argc)
b09da87b
JF
796 script = NULL;
797 else {
9185d5ef 798#ifdef CY_EXECUTE
967067aa 799 // XXX: const_cast?! wtf gcc :(
5ef46cc0 800 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
9185d5ef 801#endif
5ef46cc0 802 script = argv[ind];
967067aa
JF
803 if (strcmp(script, "-") == 0)
804 script = NULL;
b09da87b
JF
805 }
806
2aa77fd8 807#ifdef CY_ATTACH
967067aa 808 if (pid == _not(pid_t))
7e5391fd 809 client_ = -1;
967067aa 810 else {
46d13f4c
JF
811 struct Socket {
812 int fd_;
b166b11b 813
46d13f4c
JF
814 Socket(int fd) :
815 fd_(fd)
816 {
817 }
96cc7967 818
46d13f4c
JF
819 ~Socket() {
820 close(fd_);
821 }
96cc7967 822
46d13f4c
JF
823 operator int() {
824 return fd_;
825 }
826 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
96cc7967 827
46d13f4c
JF
828 struct sockaddr_un address;
829 memset(&address, 0, sizeof(address));
830 address.sun_family = AF_UNIX;
b166b11b 831
46d13f4c
JF
832 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
833 unlink(address.sun_path);
b166b11b 834
46d13f4c
JF
835 struct File {
836 const char *path_;
837
838 File(const char *path) :
839 path_(path)
840 {
841 }
842
843 ~File() {
844 unlink(path_);
845 }
846 } file(address.sun_path);
847
848 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
849 _syscall(chmod(address.sun_path, 0777));
850
851 _syscall(listen(server, 1));
852 InjectLibrary(pid);
853 client_ = _syscall(accept(server, NULL, NULL));
967067aa 854 }
2aa77fd8 855#else
7e5391fd 856 client_ = -1;
2aa77fd8 857#endif
579ed526 858
666eedb9
JF
859 if (client_ == -1 && host != NULL && port != NULL) {
860 struct addrinfo hints;
861 memset(&hints, 0, sizeof(hints));
862 hints.ai_family = AF_UNSPEC;
863 hints.ai_socktype = SOCK_STREAM;
864 hints.ai_protocol = 0;
865 hints.ai_flags = 0;
866
867 struct addrinfo *infos;
868 _syscall(getaddrinfo(host, port, &hints, &infos));
869
870 _assert(infos != NULL); try {
871 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
872 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
873 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
874 client_ = client;
875 break;
876 } catch (...) {
877 _syscall(close(client));
878 throw;
879 }
880 }
881 } catch (...) {
882 freeaddrinfo(infos);
883 throw;
884 }
885 }
886
48e3be8a 887 if (script == NULL && tty)
2eb8215d 888 Console(options);
b09da87b 889 else {
2eb8215d 890 CYLocalPool pool;
b09da87b 891
0df6a201 892 std::istream *stream;
48e3be8a 893 if (script == NULL) {
0df6a201
JF
894 stream = &std::cin;
895 script = "<stdin>";
48e3be8a 896 } else {
0df6a201
JF
897 stream = new std::fstream(script, std::ios::in | std::ios::binary);
898 _assert(!stream->fail());
48e3be8a 899 }
62ca2b82 900
0df6a201 901 CYDriver driver(*stream, script);
d3b63265
JF
902 cy::parser parser(driver);
903 Setup(driver, parser);
904
b09da87b
JF
905 if (parser.parse() != 0 || !driver.errors_.empty()) {
906 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
907 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
0df6a201
JF
908 } else if (driver.program_ != NULL) {
909 std::ostringstream str;
910 CYOutput out(str, options);
36bf49c4 911 Setup(out, driver, options, true);
0df6a201
JF
912 out << *driver.program_;
913 std::string code(str.str());
914 if (compile)
915 std::cout << code;
916 else
82a02ede 917 Run(client_, false, code, &std::cout);
0df6a201 918 }
057f943f 919 }
62ca2b82 920
0cbeddf8
JF
921 apr_pool_destroy(pool);
922
057f943f 923 return 0;
62ca2b82 924}
b6961e53
JF
925
926int main(int argc, char const * const argv[], char const * const envp[]) {
927 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
da858962 928
b6961e53
JF
929 if (status != APR_SUCCESS) {
930 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
931 return 1;
932 } else try {
933 return Main(argc, argv, envp);
934 } catch (const CYException &error) {
935 CYPool pool;
936 fprintf(stderr, "%s\n", error.PoolCString(pool));
937 return 1;
938 }
939}