]> git.saurik.com Git - cycript.git/blob - Console.cpp
Close server socket after accepting remote client.
[cycript.git] / Console.cpp
1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
3 */
4
5 /* GNU General Public License, Version 3 {{{ */
6 /*
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.
11 *
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.
16 *
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/>.
19 **/
20 /* }}} */
21
22 #include "cycript.hpp"
23
24 #ifdef CY_EXECUTE
25 #include "JavaScript.hpp"
26 #endif
27
28 #include <cstdio>
29 #include <fstream>
30 #include <sstream>
31
32 #include <setjmp.h>
33
34 #ifdef HAVE_READLINE_H
35 #include <readline.h>
36 #else
37 #include <readline/readline.h>
38 #endif
39
40 #ifdef HAVE_HISTORY_H
41 #include <history.h>
42 #else
43 #include <readline/history.h>
44 #endif
45
46 #include <errno.h>
47 #include <unistd.h>
48
49 #include <sys/socket.h>
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 #include <fcntl.h>
53 #include <netdb.h>
54
55 #include <sys/types.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <sys/un.h>
59 #include <pwd.h>
60
61 #include <apr_getopt.h>
62 #include <apr_pools.h>
63 #include <apr_strings.h>
64
65 #include <dlfcn.h>
66
67 #include "Display.hpp"
68 #include "Replace.hpp"
69
70 #include "Cycript.tab.hh"
71 #include "Driver.hpp"
72
73 static volatile enum {
74 Working,
75 Parsing,
76 Running,
77 Sending,
78 Waiting,
79 } mode_;
80
81 static jmp_buf ctrlc_;
82
83 static void sigint(int) {
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 }
96 }
97
98 #if YYDEBUG
99 static bool bison_;
100 #endif
101 static bool strict_;
102 static bool pretty_;
103
104 void Setup(CYDriver &driver, cy::parser &parser) {
105 #if YYDEBUG
106 if (bison_)
107 parser.set_debug_level(1);
108 #endif
109 if (strict_)
110 driver.strict_ = true;
111 }
112
113 void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) {
114 out.pretty_ = pretty_;
115 CYContext context(options);
116 if (lower)
117 driver.program_->Replace(context);
118 }
119
120 static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
121 const char *json;
122 uint32_t size;
123
124 if (client == -1) {
125 mode_ = Running;
126 #ifdef CY_EXECUTE
127 json = CYExecute(CYGetJSContext(), pool, code);
128 #else
129 json = NULL;
130 #endif
131 mode_ = Working;
132 if (json == NULL)
133 size = 0;
134 else
135 size = strlen(json);
136 } else {
137 mode_ = Sending;
138 size = code.size;
139 _assert(CYSendAll(client, &size, sizeof(size)));
140 _assert(CYSendAll(client, code.data, code.size));
141 mode_ = Waiting;
142 _assert(CYRecvAll(client, &size, sizeof(size)));
143 if (size == _not(uint32_t))
144 json = NULL;
145 else {
146 char *temp(new(pool) char[size + 1]);
147 _assert(CYRecvAll(client, temp, size));
148 temp[size] = '\0';
149 json = temp;
150 }
151 mode_ = Working;
152 }
153
154 return CYUTF8String(json, size);
155 }
156
157 static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
158 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
159 }
160
161 static std::ostream *out_;
162
163 static 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
170 static void Output(bool syntax, CYUTF8String json, std::ostream *out, bool expand = false) {
171 const char *data(json.data);
172 size_t size(json.size);
173
174 if (data == NULL || out == NULL)
175 return;
176
177 if (!expand ||
178 data[0] != '@' && data[0] != '"' && data[0] != '\'' ||
179 data[0] == '@' && data[1] != '"' && data[1] != '\''
180 )
181 Write(syntax, data, size, *out);
182 else for (size_t i(0); i != size; ++i)
183 if (data[i] != '\\')
184 *out << data[i];
185 else switch(data[++i]) {
186 case '\0': goto done;
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;
197 }
198
199 done:
200 *out << std::endl;
201 }
202
203 static void Run(int client, bool syntax, const char *data, size_t size, std::ostream *out = NULL, bool expand = false) {
204 CYPool pool;
205 Output(syntax, Run(pool, client, CYUTF8String(data, size)), out, expand);
206 }
207
208 static 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);
210 }
211
212 int (*append_history$)(int, const char *);
213
214 static std::string command_;
215
216 static CYExpression *ParseExpression(CYUTF8String code) {
217 std::stringstream stream;
218 stream << '(' << code << ')';
219 CYDriver driver(stream);
220
221 cy::parser parser(driver);
222 Setup(driver, parser);
223
224 if (parser.parse() != 0 || !driver.errors_.empty())
225 return NULL;
226
227 CYOptions options;
228 CYContext context(options);
229
230 CYStatement *statement(driver.program_->statements_);
231 _assert(statement != NULL);
232 _assert(statement->next_ == NULL);
233
234 CYExpress *express(dynamic_cast<CYExpress *>(driver.program_->statements_));
235 _assert(express != NULL);
236
237 return express->expression_;
238 }
239
240 static int client_;
241
242 static char **Complete(const char *word, int start, int end) {
243 rl_attempted_completion_over = TRUE;
244
245 CYLocalPool pool;
246
247 std::string line(rl_line_buffer, start);
248 std::istringstream stream(command_ + line);
249 CYDriver driver(stream);
250
251 driver.auto_ = true;
252
253 cy::parser parser(driver);
254 Setup(driver, parser);
255
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;
265 CYContext context(options);
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());
284 expression = $M($C1($V("object_getClass"), thing.context_), $S("messages"));
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
293 std::string begin(prefix.str());
294
295 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
296 " function(object, prefix, word) {\n"
297 " var names = [];\n"
298 " var before = prefix.length;\n"
299 " prefix += word;\n"
300 " var entire = prefix.length;\n"
301 " for (var name in object)\n"
302 " if (name.substring(0, entire) == prefix)\n"
303 " names.push(name.substr(before));\n"
304 " return names;\n"
305 " }\n"
306 ), expression, $S(begin.c_str()), $S(word))));
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));
316 // XXX: if this fails we should not try to parse it
317
318 CYExpression *result(ParseExpression(json));
319 if (result == NULL)
320 return NULL;
321
322 CYArray *array(dynamic_cast<CYArray *>(result->Primitive(context)));
323 if (array == NULL) {
324 *out_ << '\n';
325 Output(false, json, out_);
326 rl_forced_update_display();
327 return NULL;
328 }
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
337 CYForEach (element, array->elements_) {
338 CYString *string(dynamic_cast<CYString *>(element->value_));
339 _assert(string != NULL);
340
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
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
372 size_t colon(common.find(':'));
373 if (colon != std::string::npos)
374 common = common.substr(0, colon + 1);
375 if (completions.size() == 1)
376 common += ' ';
377
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 *
390 static char name_[] = "cycript";
391 static char break_[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
392
393 class 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
421 static void Console(CYOptions &options) {
422 CYPool pool;
423
424 passwd *passwd;
425 if (const char *username = getenv("LOGNAME"))
426 passwd = getpwnam(username);
427 else
428 passwd = getpwuid(getuid());
429
430 std::string basedir(passwd->pw_dir);
431 basedir += "/.cycript";
432 mkdir(basedir.c_str(), 0700);
433
434 rl_initialize();
435 rl_readline_name = name_;
436
437 History history(basedir + "/history");
438
439 bool bypass(false);
440 bool debug(false);
441 bool expand(false);
442 bool lower(true);
443 bool syntax(true);
444
445 out_ = &std::cout;
446
447 // rl_completer_word_break_characters is broken in libedit
448 rl_basic_word_break_characters = break_;
449
450 rl_completer_word_break_characters = break_;
451 rl_attempted_completion_function = &Complete;
452 rl_bind_key('\t', rl_complete);
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 (;;) {
461 command_.clear();
462 std::vector<std::string> lines;
463
464 bool extra(false);
465 const char *prompt("cy# ");
466
467 if (setjmp(ctrlc_) != 0) {
468 mode_ = Working;
469 *out_ << std::endl;
470 goto restart;
471 }
472
473 read:
474
475 #if RL_READLINE_VERSION >= 0x0600
476 if (syntax)
477 rl_redisplay_function = CYDisplayUpdate;
478 else
479 rl_redisplay_function = rl_redisplay;
480 #endif
481
482 mode_ = Parsing;
483 char *line(readline(prompt));
484 mode_ = Working;
485
486 if (line == NULL) {
487 *out_ << std::endl;
488 break;
489 } else if (line[0] == '\0')
490 goto read;
491
492 if (!extra) {
493 extra = true;
494 if (line[0] == '?') {
495 std::string data(line + 1);
496 if (data == "bypass") {
497 bypass = !bypass;
498 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
499 } else if (data == "debug") {
500 debug = !debug;
501 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
502 } else if (data == "destroy") {
503 CYDestroyContext();
504 } else if (data == "gc") {
505 *out_ << "collecting... " << std::flush;
506 CYGarbageCollect(CYGetJSContext());
507 *out_ << "done." << std::endl;
508 } else if (data == "exit") {
509 return;
510 } else if (data == "expand") {
511 expand = !expand;
512 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
513 } else if (data == "lower") {
514 lower = !lower;
515 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
516 } else if (data == "syntax") {
517 syntax = !syntax;
518 *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl;
519 }
520 command_ = line;
521 history += command_;
522 goto restart;
523 }
524 }
525
526 command_ += line;
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
537 free(line);
538
539 std::string code;
540
541 if (bypass)
542 code = command_;
543 else {
544 CYLocalPool pool;
545
546 std::istringstream stream(command_);
547 CYDriver driver(stream);
548
549 cy::parser parser(driver);
550 Setup(driver, parser);
551
552 if (parser.parse() != 0 || !driver.errors_.empty()) {
553 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
554 cy::position begin(error->location_.begin);
555 if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) {
556 cy::position end(error->location_.end);
557
558 if (begin.line != lines.size()) {
559 std::cerr << " | ";
560 std::cerr << lines[begin.line - 1] << std::endl;
561 }
562
563 std::cerr << "....";
564 for (size_t i(0); i != begin.column; ++i)
565 std::cerr << '.';
566 if (begin.line != end.line || begin.column == end.column)
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;
571
572 std::cerr << " | ";
573 std::cerr << error->message_ << std::endl;
574
575 history += command_;
576 goto restart;
577 }
578 }
579
580 driver.errors_.clear();
581
582 command_ += '\n';
583 prompt = "cy> ";
584 goto read;
585 }
586
587 if (driver.program_ == NULL)
588 goto restart;
589
590 std::ostringstream str;
591 CYOutput out(str, options);
592 Setup(out, driver, options, lower);
593 out << *driver.program_;
594 code = str.str();
595 }
596
597 history += command_;
598
599 if (debug) {
600 std::cout << "cy= ";
601 Write(syntax, code.c_str(), code.size(), std::cout);
602 std::cout << std::endl;
603 }
604
605 Run(client_, syntax, code, out_, expand);
606 }
607 }
608
609 void InjectLibrary(pid_t pid);
610
611 int Main(int argc, char const * const argv[], char const * const envp[]) {
612 _aprcall(apr_initialize());
613
614 apr_pool_t *pool;
615 apr_pool_create(&pool, NULL);
616
617 bool tty(isatty(STDIN_FILENO));
618 bool compile(false);
619 bool target(false);
620 CYOptions options;
621
622 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
623
624 #ifdef CY_ATTACH
625 pid_t pid(_not(pid_t));
626 #endif
627
628 const char *host(NULL);
629 const char *port(NULL);
630
631 apr_getopt_t *state;
632 _aprcall(apr_getopt_init(&state, pool, argc, argv));
633
634 for (;;) {
635 int opt;
636 const char *arg;
637
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},
642 #ifdef CY_ATTACH
643 {NULL, 'p', true, NULL},
644 #endif
645 {NULL, 'r', true, NULL},
646 {NULL, 's', false, NULL},
647 {0, 0, 0, 0}}, &opt, &arg));
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]"
656 #ifdef CY_ATTACH
657 " [-p <pid|name>]"
658 #endif
659 " [-r <host:port>]"
660 " [<script> [<arg>...]]\n"
661 );
662 return 1;
663 default:
664 _aprcall(status);
665 }
666
667 switch (opt) {
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
681 case 'c':
682 compile = true;
683 goto target;
684
685 case 'g':
686 if (false);
687 else if (strcmp(arg, "rename") == 0)
688 options.verbose_ = true;
689 #if YYDEBUG
690 else if (strcmp(arg, "bison") == 0)
691 bison_ = true;
692 #endif
693 else {
694 fprintf(stderr, "invalid name for -g\n");
695 return 1;
696 }
697 break;
698
699 case 'n':
700 if (false);
701 else if (strcmp(arg, "minify") == 0)
702 pretty_ = true;
703 else {
704 fprintf(stderr, "invalid name for -n\n");
705 return 1;
706 }
707 break;
708
709 #ifdef CY_ATTACH
710 case 'p': {
711 size_t size(strlen(arg));
712 char *end;
713
714 pid = strtoul(arg, &end, 0);
715 if (arg + size != end) {
716 // XXX: arg needs to be escaped in some horrendous way of doom
717 const char *command(apr_pstrcat(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^", arg, " /{s/^[^ ]* //;q;};};d'", NULL));
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;
729 if (size == sizeof(value))
730 goto fail;
731 }
732 }
733
734 size:
735 if (size == 0)
736 goto fail;
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);
745 if (value + size != end) fail:
746 pid = _not(pid_t);
747 _syscall(pclose(pids));
748 }
749
750 if (pid == _not(pid_t)) {
751 fprintf(stderr, "unable to find process `%s' using ps\n", arg);
752 return 1;
753 }
754 }
755 } goto target;
756 #endif
757
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;
777 } goto target;
778
779 case 's':
780 strict_ = true;
781 break;
782 }
783 } getopt:;
784
785 const char *script;
786 int ind(state->ind);
787
788 #ifdef CY_ATTACH
789 if (pid != _not(pid_t) && ind < argc - 1) {
790 fprintf(stderr, "-p cannot set argv\n");
791 return 1;
792 }
793 #endif
794
795 if (ind == argc)
796 script = NULL;
797 else {
798 #ifdef CY_EXECUTE
799 // XXX: const_cast?! wtf gcc :(
800 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
801 #endif
802 script = argv[ind];
803 if (strcmp(script, "-") == 0)
804 script = NULL;
805 }
806
807 #ifdef CY_ATTACH
808 if (pid == _not(pid_t))
809 client_ = -1;
810 else {
811 struct Socket {
812 int fd_;
813
814 Socket(int fd) :
815 fd_(fd)
816 {
817 }
818
819 ~Socket() {
820 close(fd_);
821 }
822
823 operator int() {
824 return fd_;
825 }
826 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
827
828 struct sockaddr_un address;
829 memset(&address, 0, sizeof(address));
830 address.sun_family = AF_UNIX;
831
832 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
833 unlink(address.sun_path);
834
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));
854 }
855 #else
856 client_ = -1;
857 #endif
858
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
887 if (script == NULL && tty)
888 Console(options);
889 else {
890 CYLocalPool pool;
891
892 std::istream *stream;
893 if (script == NULL) {
894 stream = &std::cin;
895 script = "<stdin>";
896 } else {
897 stream = new std::fstream(script, std::ios::in | std::ios::binary);
898 _assert(!stream->fail());
899 }
900
901 CYDriver driver(*stream, script);
902 cy::parser parser(driver);
903 Setup(driver, parser);
904
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;
908 } else if (driver.program_ != NULL) {
909 std::ostringstream str;
910 CYOutput out(str, options);
911 Setup(out, driver, options, true);
912 out << *driver.program_;
913 std::string code(str.str());
914 if (compile)
915 std::cout << code;
916 else
917 Run(client_, false, code, &std::cout);
918 }
919 }
920
921 apr_pool_destroy(pool);
922
923 return 0;
924 }
925
926 int main(int argc, char const * const argv[], char const * const envp[]) {
927 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
928
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 }