]> git.saurik.com Git - cycript.git/blob - Console.cpp
Failing to send/receive client fd should be fatal.
[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 <sstream>
30
31 #include <setjmp.h>
32
33 #ifdef HAVE_READLINE_H
34 #include <readline.h>
35 #else
36 #include <readline/readline.h>
37 #endif
38
39 #ifdef HAVE_HISTORY_H
40 #include <history.h>
41 #else
42 #include <readline/history.h>
43 #endif
44
45 #include <sys/mman.h>
46
47 #include <errno.h>
48 #include <unistd.h>
49
50 #include <sys/socket.h>
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <fcntl.h>
54 #include <netdb.h>
55
56 #include <sys/types.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <sys/un.h>
60 #include <pwd.h>
61
62 #include <apr_getopt.h>
63 #include <apr_pools.h>
64 #include <apr_strings.h>
65
66 #include <dlfcn.h>
67
68 #include "Display.hpp"
69 #include "Replace.hpp"
70
71 #include "Cycript.tab.hh"
72 #include "Driver.hpp"
73
74 static volatile enum {
75 Working,
76 Parsing,
77 Running,
78 Sending,
79 Waiting,
80 } mode_;
81
82 static jmp_buf ctrlc_;
83
84 static void sigint(int) {
85 switch (mode_) {
86 case Working:
87 return;
88 case Parsing:
89 longjmp(ctrlc_, 1);
90 case Running:
91 throw "*** Ctrl-C";
92 case Sending:
93 return;
94 case Waiting:
95 return;
96 }
97 }
98
99 #if YYDEBUG
100 static bool bison_;
101 #endif
102 static bool strict_;
103 static bool pretty_;
104
105 void Setup(CYDriver &driver, cy::parser &parser) {
106 #if YYDEBUG
107 if (bison_)
108 parser.set_debug_level(1);
109 #endif
110 if (strict_)
111 driver.strict_ = true;
112 }
113
114 void Setup(CYOutput &out, CYDriver &driver, CYOptions &options) {
115 out.pretty_ = pretty_;
116 CYContext context(options);
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(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 // XXX: this could be replaced with a CYStatement::Primitive()
231 if (CYExpress *express = dynamic_cast<CYExpress *>(driver.program_->statements_))
232 return express->expression_->Primitive(context);
233
234 return NULL;
235 }
236
237 static int client_;
238
239 static char **Complete(const char *word, int start, int end) {
240 rl_attempted_completion_over = TRUE;
241
242 CYLocalPool pool;
243
244 std::string line(rl_line_buffer, start);
245 std::istringstream stream(command_ + line);
246 CYDriver driver(stream);
247
248 driver.auto_ = true;
249
250 cy::parser parser(driver);
251 Setup(driver, parser);
252
253 if (parser.parse() != 0 || !driver.errors_.empty())
254 return NULL;
255
256 if (driver.mode_ == CYDriver::AutoNone)
257 return NULL;
258
259 CYExpression *expression;
260
261 CYOptions options;
262 CYContext context(options);
263
264 std::ostringstream prefix;
265
266 switch (driver.mode_) {
267 case CYDriver::AutoPrimary:
268 expression = $ CYThis();
269 break;
270
271 case CYDriver::AutoDirect:
272 expression = driver.context_;
273 break;
274
275 case CYDriver::AutoIndirect:
276 expression = $ CYIndirect(driver.context_);
277 break;
278
279 case CYDriver::AutoMessage: {
280 CYDriver::Context &thing(driver.contexts_.back());
281 expression = $M($C1($V("object_getClass"), thing.context_), $S("messages"));
282 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
283 prefix << (*part)->word_ << ':';
284 } break;
285
286 default:
287 _assert(false);
288 }
289
290 std::string begin(prefix.str());
291
292 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
293 " function(object, prefix, word) {\n"
294 " var names = [];\n"
295 " var before = prefix.length;\n"
296 " prefix += word;\n"
297 " var entire = prefix.length;\n"
298 " for (name in object)\n"
299 " if (name.substring(0, entire) == prefix)\n"
300 " names.push(name.substr(before));\n"
301 " return names;\n"
302 " }\n"
303 ), expression, $S(begin.c_str()), $S(word))));
304
305 driver.program_->Replace(context);
306
307 std::ostringstream str;
308 CYOutput out(str, options);
309 out << *driver.program_;
310
311 std::string code(str.str());
312 CYUTF8String json(Run(pool, client_, code));
313 // XXX: if this fails we should not try to parse it
314
315 CYExpression *result(ParseExpression(json));
316 if (result == NULL)
317 return NULL;
318
319 CYArray *array(dynamic_cast<CYArray *>(result));
320
321 if (array == NULL) {
322 *out_ << '\n';
323 Output(false, json, out_);
324 rl_forced_update_display();
325 return NULL;
326 }
327
328 // XXX: use an std::set?
329 typedef std::vector<std::string> Completions;
330 Completions completions;
331
332 std::string common;
333 bool rest(false);
334
335 CYForEach (element, array->elements_) {
336 CYString *string(dynamic_cast<CYString *>(element->value_));
337 _assert(string != NULL);
338
339 std::string completion;
340 if (string->size_ != 0)
341 completion.assign(string->value_, string->size_);
342 else if (driver.mode_ == CYDriver::AutoMessage)
343 completion = "]";
344 else
345 continue;
346
347 completions.push_back(completion);
348
349 if (!rest) {
350 common = completion;
351 rest = true;
352 } else {
353 size_t limit(completion.size()), size(common.size());
354 if (size > limit)
355 common = common.substr(0, limit);
356 else
357 limit = size;
358 for (limit = 0; limit != size; ++limit)
359 if (common[limit] != completion[limit])
360 break;
361 if (limit != size)
362 common = common.substr(0, limit);
363 }
364 }
365
366 size_t count(completions.size());
367 if (count == 0)
368 return NULL;
369
370 size_t colon(common.find(':'));
371 if (colon != std::string::npos)
372 common = common.substr(0, colon + 1);
373 if (completions.size() == 1)
374 common += ' ';
375
376 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
377
378 results[0] = strdup(common.c_str());
379 size_t index(0);
380 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
381 results[++index] = strdup(i->c_str());
382 results[count + 1] = NULL;
383
384 return results;
385 }
386
387 // need char *, not const char *
388 static char name_[] = "cycript";
389 static char break_[] = " \t\n\"\\'`@$><=;|&{(" ")}" ".:[]";
390
391 static void Console(CYOptions &options) {
392 CYPool pool;
393
394 passwd *passwd;
395 if (const char *username = getenv("LOGNAME"))
396 passwd = getpwnam(username);
397 else
398 passwd = getpwuid(getuid());
399
400 const char *basedir(pool.strcat(passwd->pw_dir, "/.cycript", NULL));
401 const char *histfile(pool.strcat(basedir, "/history", NULL));
402 size_t histlines(0);
403
404 rl_initialize();
405 rl_readline_name = name_;
406
407 mkdir(basedir, 0700);
408 read_history(histfile);
409
410 bool bypass(false);
411 bool debug(false);
412 bool expand(false);
413 bool syntax(true);
414
415 out_ = &std::cout;
416
417 // rl_completer_word_break_characters is broken in libedit
418 rl_basic_word_break_characters = break_;
419
420 rl_completer_word_break_characters = break_;
421 rl_attempted_completion_function = &Complete;
422 rl_bind_key('\t', rl_complete);
423
424 struct sigaction action;
425 sigemptyset(&action.sa_mask);
426 action.sa_handler = &sigint;
427 action.sa_flags = 0;
428 sigaction(SIGINT, &action, NULL);
429
430 restart: for (;;) {
431 command_.clear();
432 std::vector<std::string> lines;
433
434 bool extra(false);
435 const char *prompt("cy# ");
436
437 if (setjmp(ctrlc_) != 0) {
438 mode_ = Working;
439 *out_ << std::endl;
440 goto restart;
441 }
442
443 read:
444
445 #if RL_READLINE_VERSION >= 0x0600
446 if (syntax) {
447 rl_prep_term_function = CYDisplayStart;
448 rl_redisplay_function = CYDisplayUpdate;
449 rl_deprep_term_function = CYDisplayFinish;
450 } else {
451 rl_prep_term_function = rl_prep_terminal;
452 rl_redisplay_function = rl_redisplay;
453 rl_deprep_term_function = rl_deprep_terminal;
454 }
455 #endif
456
457 mode_ = Parsing;
458 char *line(readline(prompt));
459 mode_ = Working;
460
461 if (line == NULL)
462 break;
463 if (line[0] == '\0')
464 goto read;
465
466 if (!extra) {
467 extra = true;
468 if (line[0] == '?') {
469 std::string data(line + 1);
470 if (data == "bypass") {
471 bypass = !bypass;
472 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
473 } else if (data == "debug") {
474 debug = !debug;
475 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
476 } else if (data == "expand") {
477 expand = !expand;
478 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
479 } else if (data == "syntax") {
480 syntax = !syntax;
481 *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl;
482 }
483 add_history(line);
484 ++histlines;
485 goto restart;
486 }
487 }
488
489 command_ += line;
490
491 char *begin(line), *end(line + strlen(line));
492 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
493 *nl = '\0';
494 lines.push_back(begin);
495 begin = nl + 1;
496 }
497
498 lines.push_back(begin);
499
500 free(line);
501
502 std::string code;
503
504 if (bypass)
505 code = command_;
506 else {
507 CYLocalPool pool;
508
509 std::istringstream stream(command_);
510 CYDriver driver(stream);
511
512 cy::parser parser(driver);
513 Setup(driver, parser);
514
515 if (parser.parse() != 0 || !driver.errors_.empty()) {
516 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
517 cy::position begin(error->location_.begin);
518 if (begin.line != lines.size() || begin.column < lines.back().size() || error->warning_) {
519 cy::position end(error->location_.end);
520
521 if (begin.line != lines.size()) {
522 std::cerr << " | ";
523 std::cerr << lines[begin.line - 1] << std::endl;
524 }
525
526 std::cerr << "....";
527 for (size_t i(0); i != begin.column; ++i)
528 std::cerr << '.';
529 if (begin.line != end.line || begin.column == end.column)
530 std::cerr << '^';
531 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
532 std::cerr << '^';
533 std::cerr << std::endl;
534
535 std::cerr << " | ";
536 std::cerr << error->message_ << std::endl;
537
538 add_history(command_.c_str());
539 ++histlines;
540 goto restart;
541 }
542 }
543
544 driver.errors_.clear();
545
546 command_ += '\n';
547 prompt = "cy> ";
548 goto read;
549 }
550
551 if (driver.program_ == NULL)
552 goto restart;
553
554 if (client_ != -1)
555 code = command_;
556 else {
557 std::ostringstream str;
558 CYOutput out(str, options);
559 Setup(out, driver, options);
560 out << *driver.program_;
561 code = str.str();
562 }
563 }
564
565 add_history(command_.c_str());
566 ++histlines;
567
568 if (debug) {
569 Write(syntax, code.c_str(), code.size(), std::cout);
570 std::cout << std::endl;
571 }
572
573 Run(client_, syntax, code, out_, expand);
574 }
575
576 if (append_history$ != NULL) {
577 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
578 (*append_history$)(histlines, histfile);
579 } else {
580 write_history(histfile);
581 }
582
583 *out_ << std::endl;
584 }
585
586 static void *Map(const char *path, size_t *psize) {
587 int fd;
588 _syscall(fd = open(path, O_RDONLY));
589
590 struct stat stat;
591 _syscall(fstat(fd, &stat));
592 size_t size(stat.st_size);
593
594 *psize = size;
595
596 void *base;
597 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
598
599 _syscall(close(fd));
600 return base;
601 }
602
603 void InjectLibrary(pid_t pid);
604
605 int Main(int argc, char const * const argv[], char const * const envp[]) {
606 _aprcall(apr_initialize());
607
608 apr_pool_t *pool;
609 apr_pool_create(&pool, NULL);
610
611 bool tty(isatty(STDIN_FILENO));
612 bool compile(false);
613 CYOptions options;
614
615 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
616
617 #ifdef CY_ATTACH
618 pid_t pid(_not(pid_t));
619 #endif
620
621 const char *host(NULL);
622 const char *port(NULL);
623
624 apr_getopt_t *state;
625 _aprcall(apr_getopt_init(&state, pool, argc, argv));
626
627 for (;;) {
628 char opt;
629 const char *arg;
630
631 apr_status_t status(apr_getopt(state,
632 "cg:n:"
633 #ifdef CY_ATTACH
634 "p:"
635 #endif
636 "r:"
637 "s"
638 , &opt, &arg));
639
640 switch (status) {
641 case APR_EOF:
642 goto getopt;
643 case APR_BADCH:
644 case APR_BADARG:
645 fprintf(stderr,
646 "usage: cycript [-c]"
647 #ifdef CY_ATTACH
648 " [-p <pid|name>]"
649 #endif
650 " [-r <host:port>]"
651 " [<script> [<arg>...]]\n"
652 );
653 return 1;
654 default:
655 _aprcall(status);
656 }
657
658 switch (opt) {
659 case 'c':
660 compile = true;
661 break;
662
663 case 'g':
664 if (false);
665 else if (strcmp(arg, "rename") == 0)
666 options.verbose_ = true;
667 #if YYDEBUG
668 else if (strcmp(arg, "bison") == 0)
669 bison_ = true;
670 #endif
671 else {
672 fprintf(stderr, "invalid name for -g\n");
673 return 1;
674 }
675 break;
676
677 case 'n':
678 if (false);
679 else if (strcmp(arg, "minify") == 0)
680 pretty_ = true;
681 else {
682 fprintf(stderr, "invalid name for -n\n");
683 return 1;
684 }
685 break;
686
687 #ifdef CY_ATTACH
688 case 'p': {
689 size_t size(strlen(arg));
690 char *end;
691
692 pid = strtoul(arg, &end, 0);
693 if (arg + size != end) {
694 // XXX: arg needs to be escaped in some horrendous way of doom
695 const char *command(apr_pstrcat(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^", arg, " /{s/^[^ ]* //;q;};};d'", NULL));
696
697 if (FILE *pids = popen(command, "r")) {
698 char value[32];
699 size = 0;
700
701 for (;;) {
702 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
703 if (read == 0)
704 break;
705 else {
706 size += read;
707 if (size == sizeof(value)) {
708 pid = _not(pid_t);
709 goto fail;
710 }
711 }
712 }
713
714 size:
715 if (size == 0)
716 goto fail;
717 if (value[size - 1] == '\n') {
718 --size;
719 goto size;
720 }
721
722 value[size] = '\0';
723 size = strlen(value);
724 pid = strtoul(value, &end, 0);
725 if (value + size != end) fail:
726 pid = _not(pid_t);
727 _syscall(pclose(pids));
728 }
729
730 if (pid == _not(pid_t)) {
731 fprintf(stderr, "invalid pid for -p\n");
732 return 1;
733 }
734 }
735 } break;
736 #endif
737
738 case 'r': {
739 //size_t size(strlen(arg));
740
741 char *colon(strrchr(arg, ':'));
742 if (colon == NULL) {
743 fprintf(stderr, "missing colon in hostspec\n");
744 return 1;
745 }
746
747 /*char *end;
748 port = strtoul(colon + 1, &end, 10);
749 if (end != arg + size) {
750 fprintf(stderr, "invalid port in hostspec\n");
751 return 1;
752 }*/
753
754 host = arg;
755 *colon = '\0';
756 port = colon + 1;
757 } break;
758
759 case 's':
760 strict_ = true;
761 break;
762 }
763 } getopt:;
764
765 const char *script;
766 int ind(state->ind);
767
768 #ifdef CY_ATTACH
769 if (pid != _not(pid_t) && ind < argc - 1) {
770 fprintf(stderr, "-p cannot set argv\n");
771 return 1;
772 }
773
774 if (pid != _not(pid_t) && compile) {
775 fprintf(stderr, "-p conflicts with -c\n");
776 return 1;
777 }
778 #endif
779
780 if (ind == argc)
781 script = NULL;
782 else {
783 #ifdef CY_EXECUTE
784 // XXX: const_cast?! wtf gcc :(
785 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
786 #endif
787 script = argv[ind];
788 if (strcmp(script, "-") == 0)
789 script = NULL;
790 }
791
792 #ifdef CY_ATTACH
793 if (pid != _not(pid_t) && script == NULL && !tty) {
794 fprintf(stderr, "non-terminal attaching to remote console\n");
795 return 1;
796 }
797 #endif
798
799 #ifdef CY_ATTACH
800 if (pid == _not(pid_t))
801 client_ = -1;
802 else {
803 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
804 struct sockaddr_un address;
805 memset(&address, 0, sizeof(address));
806 address.sun_family = AF_UNIX;
807
808 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
809
810 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
811 _syscall(chmod(address.sun_path, 0777));
812
813 try {
814 _syscall(listen(server, 1));
815 InjectLibrary(pid);
816 client_ = _syscall(accept(server, NULL, NULL));
817 } catch (...) {
818 // XXX: exception?
819 unlink(address.sun_path);
820 throw;
821 }
822 } catch (...) {
823 _syscall(close(server));
824 throw;
825 }
826 }
827 #else
828 client_ = -1;
829 #endif
830
831 if (client_ == -1 && host != NULL && port != NULL) {
832 struct addrinfo hints;
833 memset(&hints, 0, sizeof(hints));
834 hints.ai_family = AF_UNSPEC;
835 hints.ai_socktype = SOCK_STREAM;
836 hints.ai_protocol = 0;
837 hints.ai_flags = 0;
838
839 struct addrinfo *infos;
840 _syscall(getaddrinfo(host, port, &hints, &infos));
841
842 _assert(infos != NULL); try {
843 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
844 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
845 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
846 client_ = client;
847 break;
848 } catch (...) {
849 _syscall(close(client));
850 throw;
851 }
852 }
853 } catch (...) {
854 freeaddrinfo(infos);
855 throw;
856 }
857 }
858
859 if (script == NULL && tty)
860 Console(options);
861 else {
862 CYLocalPool pool;
863
864 char *start, *end;
865 std::istream *indirect;
866
867 if (script == NULL) {
868 start = NULL;
869 end = NULL;
870 indirect = &std::cin;
871 } else {
872 size_t size;
873 start = reinterpret_cast<char *>(Map(script, &size));
874 end = start + size;
875
876 if (size >= 2 && start[0] == '#' && start[1] == '!') {
877 start += 2;
878
879 if (void *line = memchr(start, '\n', end - start))
880 start = reinterpret_cast<char *>(line);
881 else
882 start = end;
883 }
884
885 indirect = NULL;
886 }
887
888 CYStream direct(start, end);
889 std::istream &stream(indirect == NULL ? direct : *indirect);
890 CYDriver driver(stream, script ?: "<stdin>");
891
892 cy::parser parser(driver);
893 Setup(driver, parser);
894
895 if (parser.parse() != 0 || !driver.errors_.empty()) {
896 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
897 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
898 } else if (driver.program_ != NULL)
899 if (client_ != -1) {
900 // XXX: this code means that you can't pipe to another process
901 std::string code(start, end-start);
902 Run(client_, false, code, &std::cout);
903 } else {
904 std::ostringstream str;
905 CYOutput out(str, options);
906 Setup(out, driver, options);
907 out << *driver.program_;
908 std::string code(str.str());
909 if (compile)
910 std::cout << code;
911 else
912 Run(client_, false, code, &std::cout);
913 }
914 }
915
916 apr_pool_destroy(pool);
917
918 return 0;
919 }
920
921 int main(int argc, char const * const argv[], char const * const envp[]) {
922 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
923
924 if (status != APR_SUCCESS) {
925 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
926 return 1;
927 } else try {
928 return Main(argc, argv, envp);
929 } catch (const CYException &error) {
930 CYPool pool;
931 fprintf(stderr, "%s\n", error.PoolCString(pool));
932 return 1;
933 }
934 }