Debian Codegraph @

src/main.c

raw
1 /*
2 * main.c - interpreter main program
3 *
4 * Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #include "gauche.h"
35 #include "gauche/priv/configP.h"
36
37 #include <signal.h>
38 #include <ctype.h>
39 #include <fcntl.h> /* for _O_BINMODE on windows. */
40
41 #ifdef HAVE_GETOPT_H
42 #include <getopt.h>
43 #endif
44
45 #ifdef HAVE_GPERFTOOLS_PROFILER_H
46 #include <gperftools/profiler.h>
47 #define GPERFTOOLS_PROFILER_BEGIN \
48 do { \
49 const char *gprof_out = Scm_GetEnv("CPUPROFILE"); \
50 if (gprof_out != NULL) ProfilerStart(gprof_out);
51 #define GPERFTOOLS_PROFILER_END \
52 if (gprof_out != NULL) ProfilerStop(); \
53 } while (0)
54 #else /*!HAVE_GPERFTOOLS_PROFILER_H*/
55 #define GPERFTOOLS_PROFILER_BEGIN /* empty */
56 #define GPERFTOOLS_PROFILER_END /* empty */
57 #endif
58
59 /* options */
60 int load_initfile = TRUE; /* if false, not to load init files */
61 int batch_mode = FALSE; /* force batch mode */
62 int interactive_mode = FALSE; /* force interactive mode */
63 int test_mode = FALSE; /* add . and ../lib implicitly */
64 int profiling_mode = FALSE; /* profile the script? */
65 int stats_mode = FALSE; /* collect stats (EXPERIMENTAL) */
66 int version_mode = FALSE; /* show version and exit (-V option) */
67
68 ScmObj pre_cmds = SCM_NIL; /* assoc list of commands that needs to be
69 processed before entering repl.
70 Each car has either #\I, #\A, #\u, #\l
71 or #\e, according to the given cmdargs. */
72
73 ScmObj main_module = SCM_FALSE; /* The name of the module where we
74 look for 'main'.
75 If #f (default), 'user' module is used.
76 NB: R7RS script is read into 'r7rs.user'
77 module, so its 'main' routine isn't called
78 automatically. It is as specified in
79 R7RS. However, if the basename of the
80 interpreter executale is "scheme-r7rs",
81 we honor SRFI-22 and calls r7rs.user#main
82 after loading the script.
83 */
84 ScmModule *default_toplevel_module = NULL;
85 /* The initial module for the script execution
86 and interactive REPL. If NULL, the user
87 module is assumed. In R7RS mode, it's
88 'r7rs.user' module.
89 Note that the .gaucherc script,
90 if there's one, is always evaluated in 'user'
91 module; see lib/gauche/interactive.scm */
92
93 void usage(int errorp)
94 {
95 fprintf(errorp? stderr:stdout,
96 "Usage: gosh [-biqV][-I<path>][-A<path>][-u<module>][-m<module>][-l<file>][-L<file>][-e<expr>][-E<expr>][-p<type>][-F<feature>][-r<standard>][-f<flag>][--] [file]\n"
97 "Options:\n"
98 " -V Prints version and exits.\n"
99 " -h Shows this message to stdout.\n"
100 " -b Batch mode. Doesn't print prompts. Supersedes -i.\n"
101 " -i Interactive mode. Forces to print prompts.\n"
102 " -q Doesn't read the default initialization file.\n"
103 " -I<path> Adds <path> to the head of the load path list.\n"
104 " -A<path> Adds <path> to the tail of the load path list.\n"
105 " -u<module> (use) loads and imports <module>\n"
106 " -l<file> Loads <file> before executing the script file or\n"
107 " entering repl.\n"
108 " -L<file> Like -l, but doesn't complain if <file> doesn't exist.\n"
109 " -e<expr> Evaluates Scheme expression <expr> before executing\n"
110 " the script file or entering repl.\n"
111 " -E<expr> Similar to -e, but reads <expr> as if it is surrounded\n"
112 " by parenthesis.\n"
113 " -m<module> When the script file is given, this option specifies the\n"
114 " name of the module in which the 'main' procedure is defined.\n"
115 " By default, the 'main' procedure in the user module is called\n"
116 " after loading the script (srfi-22). This option allows to call\n"
117 " a main procedure in the different module.\n"
118 " -p<type> Turns on the profiler. <Type> can be 'time' or 'load'.\n"
119 " -F<feature> Makes <feature> available in cond-expand forms\n"
120 " If <feature> begins with '-', it removes the feature (without\n"
121 " preceding minus) instead.\n"
122 " -v<version>\n"
123 " -v:<version>\n"
124 " If <version> is not the running Gauche's version, but\n"
125 " the specified version is installed in the system, execute\n"
126 " that version's gosh instead. This is useful when you want\n"
127 " to invoke a specific version of Gauche. <Version> must be\n"
128 " 0.9.6 or later. Without ':' before <version>, gosh aborts\n"
129 " if the given version is not found; with ':', the invoked\n"
130 " gosh runs (with warning) in that case.\n"
131 " -r<standard> Starts gosh with the default environment defined\n"
132 " in RnRS, where n is determined by <standard>. The following\n"
133 " values are supported as <standard>.\n"
134 " 7 R7RS (R7RS-small)\n"
135 " -f<flag> Sets various flags\n"
136 " case-fold uses case-insensitive reader (as in R5RS)\n"
137 " include-verbose reports while including files\n"
138 " load-verbose reports while loading files\n"
139 " no-inline doesn't inline procedures & constants (combined\n"
140 " no-inline-globals, no-inline-locals,\n"
141 " no-inline-constants and no-inline-setters.)\n"
142 " no-inline-constants\n"
143 " doesn't inline constants.\n"
144 " no-inline-globals\n"
145 " doesn't inline global procedures.\n"
146 " no-inline-locals\n"
147 " doesn't inline local procedures.\n"
148 " no-inline-setters\n"
149 " doesn't inline setter procedures (srfi-17).\n"
150 " no-lambda-lifting-pass\n"
151 " doesn't run lambda lifting pass.\n"
152 " no-post-inline-pass\n"
153 " doesn't run post-inline optimization pass.\n"
154 " no-source-info doesn't preserve source information for debugging\n"
155 " read-edit\n"
156 " enables input-editing mode, if terminal supports it.\n"
157 " no-read-edit\n"
158 " disables input-editing mode.\n"
159 " safe-string-cursors\n"
160 " performs extra validation for use of string cursors\n"
161 " test test mode, to run gosh inside the build tree\n"
162 " without installing.\n"
163 " warn-legacy-syntax\n"
164 " prints warning when legacy Gauche syntax is encountered\n"
165 " warn-srfi-feature-id\n"
166 " prints warning when srfi-N is used as a feature id.\n"
167 " no-warn-srfi-feature-id\n"
168 " doesn't print warning when srfi-N is used as a feature id.\n"
169 "Environment variables:\n"
170 " GAUCHE_AVAILABLE_PROCESSORS\n"
171 " Value must be an integer. If set, it overrides the number of\n"
172 " available processors on the system, returned from\n"
173 " `sys-available-processors'.\n"
174 " GAUCHE_ALLOW_UNDEFINED_TEST\n"
175 " Suppress a warning when #<undef> is used in the test expression\n"
176 " of branch instructions.\n"
177 " GAUCHE_DYNLOAD_PATH\n"
178 " Directories separated by colon (on Unix) or semilcolon (on Windows)\n"
179 " to search dynamically loadable files.\n"
180 " GAUCHE_EDITOR\n"
181 " Path of the editor invoked with `ed'.\n"
182 " GAUCHE_HISTORY_FILE\n"
183 " Specify alternative file to save history of what you typed in REPL\n"
184 " while you're using input editing. By default, it is saved in\n"
185 " `~/.gosh_history'.\n"
186 " GAUCHE_KEYWORD_IS_SYMBOL\n"
187 " If set, keywords become subclass of symbols, to be fully R7RS\n"
188 " conformant. This is the current default behavior. Legacy code may\n"
189 " break in this mode. See ``Keyword and symbol integration'' section\n"
190 " of the manual for the details.\n"
191 " GAUCHE_KEYWORD_DISJOINT\n"
192 " If set, keywords are of their own disjoint type, rather than symbols.\n"
193 " This is old default behavior, in 0.9.7 and before. See ``Keyword and\n"
194 " symbol integration'' section of the manual for the details.\n"
195 " GAUCHE_LEGACY_DEFINE\n"
196 " Keep the toplevel `define' behavior the same as 0.9.8 and before.\n"
197 " It allows certain legacy programs that aren't valid R7RS. See\n"
198 " ``Into the Scheme-Verse'' section of the manual for the details.\n"
199 " GAUCHE_LOAD_PATH\n"
200 " Directories separated by colon (on Unix) or semilcolon (on Windows)\n"
201 " to search scheme files to load.\n"
202 " GAUCHE_MUTABLE_LITERALS\n"
203 " Make quoted pairs and lists mutable. Only to be used to run legacy\n"
204 " code that accidentally mutates literal pairs (you shouldn't do it)\n"
205 " GAUCHE_NO_READ_EDIT\n"
206 " If set, disable input editing feature. See also -fno-read-edit\n"
207 " option above.\n"
208 " GAUCHE_QUASIRENAME_MODE\n"
209 " Customize quasirename compatibility mode. See 'Explicit-renaming\n"
210 " macro transformer' section of the manual for the details.\n"
211 " GAUCHE_REPL_NO_PPRINT\n"
212 " If set, suppress using pretty printer in REPL.\n"
213 " GAUCHE_WARN_SRFI_FEATURE_ID\n"
214 " If set, warn if srfi-N is used as a feature id in cond-expand.\n"
215 " GAUCHE_SUPPRESS_WARNING\n"
216 " Suppress warnings displayed by ``warn''. This should be a quick-fix\n"
217 " when you need to get rid of warnings but do not have time to fix the\n"
218 " root cause.\n"
219 " GAUCHE_TEST_RECORD\n"
220 " When set, it specifies a file name to accumulated test statistics.\n"
221 " See ``gauche.test'' manual entry for the details.\n"
222 " GAUCHE_TEST_REPORT_ERROR\n"
223 " When set, a stack trace is printed when an error is raised during\n"
224 " running the test code in ``gauche.test'' framework.\n"
225 " GAUCHE_VERSION_INFO_EXCLUSION\n"
226 " The value must be a comma-separated keys in version-alist.\n"
227 " The keys listed here are excluded from the output of gosh -V.\n"
228 #if defined(GAUCHE_WINDOWS)
229 " GAUCHE_WINDOWS_CONSOLE_RAW\n"
230 " (Windows only) On Windows (MinGW), gosh in interactive mode wraps\n"
231 " standard ports with character conversion ports that matches the\n"
232 " the console's codepage by default. Setting this variable suppresses it.\n"
233 #endif /*defined(GAUCHE_WINDOWS)*/
234 );
235 exit(errorp? 1:0);
236 }
237
238 #ifdef GAUCHE_USE_PTHREADS
239 #define THREAD_OPT ",pthreads"
240 #elif GAUCHE_USE_WTHREADS
241 #define THREAD_OPT ",wthreads"
242 #else
243 #define THREAD_OPT ""
244 #endif
245
246 #ifdef GAUCHE_SNAPSHOT_ID
247 #define SNAPSHOT_OPT ",snapshot=" GAUCHE_SNAPSHOT_ID
248 #else
249 #define SNAPSHOT_OPT ""
250 #endif
251
252 void version(void)
253 {
254 Scm_Printf(SCM_CUROUT, "Gauche scheme shell, version %s [%s%s%s], %s\n",
255 GAUCHE_VERSION, SCM_CHAR_ENCODING_NAME, THREAD_OPT, SNAPSHOT_OPT,
256 Scm_HostArchitecture());
257 static ScmObj version_alist_proc = SCM_UNDEFINED;
258 SCM_BIND_PROC(version_alist_proc, "version-alist", Scm_GaucheModule());
259 ScmObj alist = Scm_ApplyRec0(version_alist_proc), cp;
260
261 SCM_FOR_EACH(cp, alist) {
262 Scm_Printf(SCM_CUROUT, "%S\n", SCM_CAR(cp));
263 }
264 Scm_Exit(0);
265 }
266
267 void maybe_invoke_other_version(const char *version, int argc, char **argv)
268 {
269 int allow_fallback = FALSE;
270 if (*version == ':') {
271 allow_fallback = TRUE;
272 version++;
273 }
274 if (strcmp(version, GAUCHE_VERSION) == 0) return;
275
276 static ScmObj invoke_other_version = SCM_UNDEFINED;
277 SCM_BIND_PROC(invoke_other_version, "%invoke-other-version",
278 Scm_GaucheInternalModule());
279
280 ScmEvalPacket epkt;
281 int r = Scm_Apply(invoke_other_version,
282 SCM_LIST2(SCM_MAKE_STR_COPYING(version),
283 Scm_CStringArrayToList((const char**)argv, argc, 0)),
284 &epkt);
285 /* If %invoke-other-version returns normally, it couldn't find the
286 specified version.
287 */
288 if (r < 0) {
289 Scm_Panic("Failed to call %%invoke-other-version. "
290 "Installation problem?");
291 }
292 SCM_ASSERT(r == 1);
293 if (!allow_fallback) {
294 Scm_Printf(SCM_CURERR,
295 "No installed Gauche with version %s under %A.\n",
296 version, epkt.results[0]);
297 Scm_Exit(1);
298 } else {
299 Scm_Warn("No installed Gauche with version %s under %A. "
300 "Using the current version.",
301 version, epkt.results[0]);
302 }
303 }
304
305 void further_options(const char *optarg)
306 {
307 ScmVM *vm = Scm_VM();
308 if (strcmp(optarg, "no-inline-globals") == 0) {
309 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOINLINE_GLOBALS);
310 }
311 else if (strcmp(optarg, "no-inline-locals") == 0) {
312 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOINLINE_LOCALS);
313 }
314 else if (strcmp(optarg, "no-inline-constants") == 0) {
315 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOINLINE_CONSTS);
316 }
317 else if (strcmp(optarg, "no-inline-setters") == 0) {
318 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOINLINE_SETTERS);
319 }
320 else if (strcmp(optarg, "no-inline") == 0) {
321 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOINLINE_GLOBALS);
322 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOINLINE_LOCALS);
323 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOINLINE_CONSTS);
324 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOINLINE_SETTERS);
325 }
326 else if (strcmp(optarg, "no-post-inline-pass") == 0) {
327 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NO_POST_INLINE_OPT);
328 }
329 else if (strcmp(optarg, "no-lambda-lifting-pass") == 0) {
330 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NO_LIFTING);
331 }
332 else if (strcmp(optarg, "no-dissolve-apply") == 0) {
333 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NODISSOLVE_APPLY);
334 }
335 else if (strcmp(optarg, "no-source-info") == 0) {
336 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOSOURCE);
337 }
338 else if (strcmp(optarg, "load-verbose") == 0) {
339 SCM_VM_RUNTIME_FLAG_SET(vm, SCM_LOAD_VERBOSE);
340 }
341 else if (strcmp(optarg, "include-verbose") == 0) {
342 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_INCLUDE_VERBOSE);
343 }
344 else if (strcmp(optarg, "case-fold") == 0) {
345 SCM_VM_RUNTIME_FLAG_SET(vm, SCM_CASE_FOLD);
346 }
347 else if (strcmp(optarg, "warn-legacy-syntax") == 0) {
348 Scm_SetReaderLexicalMode(SCM_INTERN("warn-legacy"));
349 /* standard input port is already initialized, so we should switch it */
350 Scm_SetPortReaderLexicalMode(SCM_CURIN, SCM_INTERN("warn-legacy"));
351 }
352 else if (strcmp(optarg, "warn-srfi-feature-id") == 0) {
353 SCM_VM_COMPILER_FLAG_CLEAR(vm, SCM_COMPILE_SRFI_FEATURE_ID);
354 }
355 else if (strcmp(optarg, "no-warn-srfi-feature-id") == 0) {
356 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_SRFI_FEATURE_ID);
357 }
358 else if (strcmp(optarg, "test") == 0) {
359 test_mode = TRUE;
360 }
361 else if (strcmp(optarg, "safe-string-cursors") == 0) {
362 SCM_VM_RUNTIME_FLAG_SET(vm, SCM_SAFE_STRING_CURSORS);
363 }
364 else if (strcmp(optarg, "read-edit") == 0) {
365 Scm_Define(Scm_GaucheInternalModule(),
366 SCM_SYMBOL(SCM_INTERN("*read-edit*")),
367 SCM_TRUE);
368 }
369 else if (strcmp(optarg, "no-read-edit") == 0) {
370 Scm_Define(Scm_GaucheInternalModule(),
371 SCM_SYMBOL(SCM_INTERN("*read-edit*")),
372 SCM_FALSE);
373 }
374 /* For development; not for public use */
375 else if (strcmp(optarg, "collect-stats") == 0) {
376 stats_mode = TRUE;
377 SCM_VM_RUNTIME_FLAG_SET(vm, SCM_COLLECT_VM_STATS);
378 }
379 /* For development; not for public use */
380 else if (strcmp(optarg, "no-combine-instructions") == 0) {
381 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_NOCOMBINE);
382 }
383 /* For development; not for public use */
384 else if (strcmp(optarg, "debug-compiler") == 0) {
385 SCM_VM_COMPILER_FLAG_SET(vm, SCM_COMPILE_SHOWRESULT);
386 }
387 /* Experimental */
388 else if (strcmp(optarg, "limit-module-mutation") == 0) {
389 SCM_VM_RUNTIME_FLAG_SET(vm, SCM_LIMIT_MODULE_MUTATION);
390 }
391 else {
392 fprintf(stderr, "unknown -f option: %s\n", optarg);
393 fprintf(stderr, "supported options are: -fcase-fold, -fload-verbose, "
394 "-finclude-verbose, -fno-dissolve-apply -fno-inline, "
395 "-fno-inline-globals, -fno-inline-locals, "
396 "-fno-inline-constants, -fno-inline-setters, -fno-source-info, "
397 "-fno-post-inline-pass, -fno-lambda-lifting-pass, "
398 "-fread-edit, -fno-read-edit, "
399 "-fsafe-string-cursors, -fwarn-legacy-syntax, "
400 "-fwarn-srfi-feature-id, -fno-warn-srfi-feature-id, "
401 "or -ftest\n");
402 exit(1);
403 }
404 }
405
406 void profiler_options(const char *optarg)
407 {
408 ScmVM *vm = Scm_VM();
409
410 if (strcmp(optarg, "time") == 0) {
411 profiling_mode = TRUE;
412 }
413 else if (strcmp(optarg, "load") == 0) {
414 SCM_VM_RUNTIME_FLAG_SET(vm, SCM_COLLECT_LOAD_STATS);
415 }
416 else {
417 fprintf(stderr, "unknown -p option: %s\n", optarg);
418 fprintf(stderr, "supported profiling options are: -ptime or -pload\n");
419 }
420 }
421
422 void feature_options(const char *optarg)
423 {
424 if (optarg[0] == '-') {
425 Scm_DisableFeature(optarg+1);
426 } else {
427 Scm_AddFeature(optarg, NULL);
428 }
429 }
430
431 int parse_options(int argc, char *argv[])
432 {
433 int c;
434 while ((c = getopt(argc, argv, "+be:E:hip:ql:L:m:u:Vv:r:F:f:I:A:-")) >= 0) {
435 switch (c) {
436 case 'b': batch_mode = TRUE; break;
437 case 'i': interactive_mode = TRUE; break;
438 case 'q': load_initfile = FALSE; break;
439 case 'V': version_mode = TRUE; break;
440 case 'f': further_options(optarg); break;
441 case 'p': profiler_options(optarg); break;
442 case 'F': feature_options(optarg); break;
443 case 'm':
444 main_module = Scm_Intern(SCM_STRING(SCM_MAKE_STR_COPYING(optarg)));
445 break;
446 case 'r': /*FALLTHROUGH*/;
447 case 'u': /*FALLTHROUGH*/;
448 case 'l': /*FALLTHROUGH*/;
449 case 'L': /*FALLTHROUGH*/;
450 case 'I': /*FALLTHROUGH*/;
451 case 'A': /*FALLTHROUGH*/;
452 case 'e': /*FALLTHROUGH*/;
453 case 'E': /*FALLTHROUGH*/;
454 pre_cmds = Scm_Acons(SCM_MAKE_CHAR(c),
455 SCM_MAKE_STR_COPYING(optarg), pre_cmds);
456 break;
457 case 'v':
458 maybe_invoke_other_version(optarg, argc, argv);
459 break;
460 case '-': break;
461 case 'h': usage(FALSE); break;
462 case '?': usage(TRUE); break;
463 }
464 }
465 return optind;
466 }
467
468 /* signal handler setup. let's catch as many signals as possible. */
469 static void sig_setup(void)
470 {
471 sigset_t set;
472 Scm_SigFillSetMostly(&set);
473 Scm_SetMasterSigmask(&set);
474 }
475
476 /*
477 * On Linux, LD_LIBRARY_PATH takes precedence over -rpath (which is
478 * already set to $(top_srcdir)/src) and could make GNU ld.so load the
479 * wrong libgauche.so.
480 *
481 * To avoid this, if we detect $LD_LIBRARY_PATH, adjust it and exec()
482 * again.
483 *
484 * This is only called when -ftest option is given.
485 */
486 static void test_ld_path_setup(char **av, const char *src_path)
487 {
488 #if defined(__GNUC__) && defined(__linux__)
489 char *ld_library_path = getenv("LD_LIBRARY_PATH");
490 if (!ld_library_path) return;
491
492 if (getenv("GAUCHE_CHANGED_LD_PATH")) return; /* avoid recursive addition */
493 setenv("GAUCHE_CHANGED_LD_PATH", "1", 1);
494
495 ScmObj new_path = Scm_NormalizePathname(SCM_STRING(SCM_MAKE_STR(src_path)),
496 SCM_PATH_ABSOLUTE);
497 new_path = Scm_StringAppendC(SCM_STRING(new_path), ":", 1, 1);
498 new_path = Scm_StringAppendC(SCM_STRING(new_path), ld_library_path, -1, -1);
499 setenv("LD_LIBRARY_PATH", strdup(Scm_GetString(SCM_STRING(new_path))), 1);
500
501 execv("/proc/self/exe", av);
502 #else
503 (void)av;
504 (void)src_path;
505 #endif
506 }
507
508 /* Path setup. When we're ran with -ftest flag, add paths to refer
509 to the files in the source tree. This is called after option processing
510 and before loading init file. */
511 static void test_paths_setup(char **av)
512 {
513 /* We first try from the location of executable; if it's not
514 available, we assume we're in the source tree, either in
515 src/ or ext/$EXT/.
516
517 The order of directories is important. 'lib' should
518 be searched first (hence it should come latter), since some
519 extension modules are built from the file in src then linked
520 from lib, and we want to test the one in lib. */
521 ScmObj self = Scm_ExecutablePath();
522 if (SCM_STRINGP(self)) {
523 ScmString *base = SCM_STRING(Scm_DirName(SCM_STRING(self)));
524 ScmObj srcdir = Scm_StringAppendC(base, "/../src", -1, -1);
525 ScmObj libsrcdir = Scm_StringAppendC(base, "/../libsrc", -1, -1);
526 ScmObj libdir = Scm_StringAppendC(base, "/../lib", -1, -1);
527 test_ld_path_setup(av, Scm_GetStringConst(SCM_STRING(srcdir)));
528 Scm_AddLoadPath(Scm_GetStringConst(SCM_STRING(srcdir)), FALSE);
529 Scm_AddLoadPath(Scm_GetStringConst(SCM_STRING(libsrcdir)), FALSE);
530 Scm_AddLoadPath(Scm_GetStringConst(SCM_STRING(libdir)), FALSE);
531 } else if (access("../src/gauche/config.h", R_OK) == 0
532 && access("../libsrc/scheme/list.scm", R_OK) == 0
533 && access("../lib/r7rs-setup.scm", R_OK) == 0) {
534 test_ld_path_setup(av, "../src");
535 Scm_AddLoadPath("../src", FALSE);
536 Scm_AddLoadPath("../libsrc", FALSE);
537 Scm_AddLoadPath("../lib", FALSE);
538 } else if (access("../../src/gauche/config.h", R_OK) == 0
539 && access("../../libsrc/scheme/list.scm", R_OK) == 0
540 && access("../../lib/r7rs-setup.scm", R_OK) == 0) {
541 test_ld_path_setup(av, "../../src");
542 Scm_AddLoadPath("../../src", FALSE);
543 Scm_AddLoadPath("../../libsrc", FALSE);
544 Scm_AddLoadPath("../../lib", FALSE);
545 } else {
546 Scm_Warn("Unable to find source tree. The -ftest option is ignored.");
547 return;
548 }
549 /* Also set a feature identifier gauche.in-place, so that other modules
550 may initialize differently if needed. */
551 Scm_AddFeature("gauche.in-place", NULL);
552 }
553
554 /* Cleanup */
555 void cleanup_main(void *data SCM_UNUSED)
556 {
557 ScmVM *vm = Scm_VM();
558
559 if (profiling_mode) {
560 Scm_ProfilerStop();
561 Scm_EvalCString("(profiler-show)",
562 SCM_OBJ(Scm_GaucheModule()),
563 NULL); /* ignore errors */
564 }
565
566 /* EXPERIMENTAL */
567 if (stats_mode) {
568 fprintf(stderr, "\n;; Statistics (*: main thread only):\n");
569 fprintf(stderr,
570 ";; GC: %zubytes heap, %zubytes allocated\n",
571 GC_get_heap_size(), GC_get_total_bytes());
572 fprintf(stderr,
573 ";; stack overflow*: %ldtimes, %.2fms total/%.2fms avg\n",
574 vm->stat.sovCount,
575 vm->stat.sovTime/1000.0,
576 (vm->stat.sovCount > 0?
577 (double)(vm->stat.sovTime/vm->stat.sovCount)/1000.0 :
578 0.0));
579 }
580
581 /* EXPERIMENTAL */
582 if (SCM_VM_RUNTIME_FLAG_IS_SET(vm, SCM_COLLECT_LOAD_STATS)) {
583 Scm_Eval(SCM_LIST2(SCM_INTERN("profiler-show-load-stats"),
584 SCM_LIST2(SCM_INTERN("quote"),
585 vm->stat.loadStat)),
586 SCM_OBJ(Scm_GaucheModule()),
587 NULL); /* ignore errors */
588 }
589 }
590
591 /* Error handling */
592 void error_exit(ScmObj c)
593 {
594 ScmObj m = Scm_ConditionMessage(c);
595 if (SCM_FALSEP(m)) {
596 Scm_Printf(SCM_CURERR, "gosh: Thrown unknown condition: %S\n", c);
597 } else {
598 Scm_Printf(SCM_CURERR, "gosh: %S: %A\n", Scm_ConditionTypeName(c), m);
599 }
600
601 ScmObj print_additional_error_heading_proc = SCM_UNDEFINED;
602 SCM_BIND_PROC(print_additional_error_heading_proc,
603 "print-additional-error-heading", Scm_GaucheModule());
604 Scm_Apply(print_additional_error_heading_proc,
605 SCM_LIST2(c, SCM_OBJ(SCM_CURERR)),
606 NULL);
607 Scm_Exit(1);
608 }
609
610 /* Returns FALSE if the process doesn't have a console. */
611 #if defined(GAUCHE_WINDOWS)
612 static int init_console(void)
613 {
614 # if defined(GAUCHE_WINDOWS_NOCONSOLE)
615 char buf[100];
616 int in_fd, out_fd;
617 #define ERR(msg) do {sprintf(buf, msg, strerror(errno));goto fail;} while(0)
618 /* If we don't have console, we'll start off with stdio to be redirected
619 to NUL; but whenever Scheme program tries to do I/O from/to
620 standard Scheme ports, we open the console and reconnect the
621 ports. */
622 if ((in_fd = open("NUL", O_RDONLY)) < 0) ERR("couldn't open NUL: %s");
623 if ((out_fd = open("NUL", O_WRONLY)) < 0) ERR("couldn't open NUL: %s");
624 if (_dup2(in_fd, 0) < 0) ERR("dup2(0) failed (%s)");
625 if (_dup2(out_fd, 1) < 0) ERR("dup2(1) failed (%s)");
626 if (_dup2(out_fd, 2) < 0) ERR("dup2(2) failed (%s)");
627 close(in_fd);
628 close(out_fd);
629 return FALSE;
630 #undef ERR
631 fail:
632 MessageBoxA(NULL, buf, "gosh-noconsole", MB_OK|MB_ICONERROR);
633 Scm_Exit(1);
634 # else /*!defined(GAUCHE_WINDOWS_NOCONSOLE)*/
635 /* This saves so much trouble */
636 _setmode(_fileno(stdin), _O_BINARY);
637 _setmode(_fileno(stdout), _O_BINARY);
638 _setmode(_fileno(stderr), _O_BINARY);
639 return TRUE;
640 # endif /*!defined(GAUCHE_WINDOWS_NOCONSOLE)*/
641 }
642
643 /* called in main to set up trapper ports; defined in port.c */
644 extern void Scm__SetupPortsForWindows(int);
645 #endif /*defined(GAUCHE_WINDOWS)*/
646
647 /* Process command-line options that needs to run after Scheme runtime
648 is initialized. CMD_ARGS is an list of (OPTION-CHAR . OPTION-ARG) */
649 static void process_command_args(ScmObj cmd_args)
650 {
651 ScmEvalPacket epak;
652 ScmLoadPacket lpak;
653 int standard_given = FALSE;
654 ScmObj cp;
655
656 SCM_FOR_EACH(cp, cmd_args) {
657 ScmObj p = SCM_CAR(cp);
658 ScmObj v = SCM_CDR(p);
659
660 switch (SCM_CHAR_VALUE(SCM_CAR(p))) {
661 case 'I':
662 Scm_AddLoadPath(Scm_GetStringConst(SCM_STRING(v)), FALSE);
663 break;
664 case 'A':
665 Scm_AddLoadPath(Scm_GetStringConst(SCM_STRING(v)), TRUE);
666 break;
667 case 'l':
668 if (Scm_Load(Scm_GetStringConst(SCM_STRING(v)), 0, &lpak) < 0)
669 error_exit(lpak.exception);
670 break;
671 case 'L':
672 if (Scm_Load(Scm_GetStringConst(SCM_STRING(v)), SCM_LOAD_QUIET_NOFILE, &lpak) < 0)
673 error_exit(lpak.exception);
674 break;
675 case 'u':
676 if (Scm_Require(Scm_StringJoin(Scm_StringSplitByChar(SCM_STRING(v),
677 '.'),
678 SCM_STRING(SCM_MAKE_STR("/")),
679 SCM_STRING_JOIN_INFIX),
680 0, &lpak) < 0) {
681 error_exit(lpak.exception);
682 }
683 Scm_ImportModule(SCM_CURRENT_MODULE(), Scm_Intern(SCM_STRING(v)),
684 SCM_FALSE, 0);
685 break;
686 case 'e':
687 /* -e option may have multiple sexprs */
688 {
689 ScmObj p = Scm_MakeInputStringPort(SCM_STRING(v), TRUE);
690 epak.module = Scm_UserModule();
691 ScmObj form;
692 while ((form = Scm_Read(p)) != SCM_EOF) {
693 if (Scm_Eval(form, SCM_OBJ(epak.module), &epak) < 0) {
694 error_exit(epak.exception);
695 }
696 }
697 }
698 break;
699 case 'E':
700 v = Scm_StringAppend(SCM_LIST3(SCM_MAKE_STR("("),
701 v,
702 SCM_MAKE_STR(")")));
703
704 if (Scm_EvalCString(Scm_GetStringConst(SCM_STRING(v)),
705 SCM_OBJ(Scm_UserModule()),
706 &epak) < 0) {
707 error_exit(epak.exception);
708 }
709 break;
710 case 'r':
711 if (standard_given) {
712 Scm_Error("Multiple -r option is specified.");
713 } else {
714 /* R7RS mode. Preload r7rs module, set the default toplevel
715 to r7rs.user, and define *r7rs-mode* in user module
716 so that gauche.interactive can do proper setup. */
717 const char *std = Scm_GetStringConst(SCM_STRING(v));
718 if (strcmp(std, "7") == 0) {
719 if (Scm_Require(SCM_MAKE_STR("r7rs-setup"), 0, &lpak) < 0) {
720 error_exit(lpak.exception);
721 }
722 SCM_DEFINE(Scm_UserModule(), "*r7rs-mode*", SCM_TRUE);
723 default_toplevel_module = SCM_FIND_MODULE("r7rs.user", 0);
724 standard_given = TRUE;
725 } else {
726 Scm_Error("Unsupported standard for -r option: %s", std);
727 }
728 }
729 }
730 }
731 }
732
733 /* When scriptfile is provided, execute it. Returns exit code. */
734 int execute_script(const char *scriptfile, ScmObj args)
735 {
736 /* If script file is specified, load it. */
737 ScmLoadPacket lpak;
738 Scm_Load(scriptfile, SCM_LOAD_PROPAGATE_ERROR|SCM_LOAD_MAIN_SCRIPT, &lpak);
739 if (!lpak.loaded) return 1;
740
741 /* If symbol 'main is bound, call it (SRFI-22). */
742 ScmModule *mainmod = (SCM_SYMBOLP(main_module)
743 ? Scm_FindModule(SCM_SYMBOL(main_module), 0)
744 : Scm_UserModule());
745 if (mainmod) {
746 ScmObj mainproc = Scm_GlobalVariableRef(mainmod,
747 SCM_SYMBOL(SCM_INTERN("main")),
748 SCM_BINDING_STAY_IN_MODULE);
749 if (SCM_PROCEDUREP(mainproc)) {
750 static ScmObj run_main_proc = SCM_UNDEFINED;
751 SCM_BIND_PROC(run_main_proc, "run-main", Scm_GaucheInternalModule());
752 SCM_ASSERT(SCM_PROCEDUREP(run_main_proc));
753
754 ScmEvalPacket epak;
755 int r = Scm_Apply(run_main_proc, SCM_LIST2(mainproc, args), &epak);
756 SCM_ASSERT(r == 1 && SCM_INTP(epak.results[0]));
757 return SCM_INT_VALUE(epak.results[0]);
758 }
759 }
760 return 0;
761 }
762
763 static int has_terminal()
764 {
765 if (isatty(0)) return TRUE;
766 #if defined(GAUCHE_WINDOWS)
767 /* MinGW console (mintty) communicates with running processes via pipe,
768 so isatty(0) returns false even if we're running on mintty.
769 We use pipe name to determine whether we're talking to mintty.
770 %sys-mintty? is defined in libsys.scm. */
771 ScmEvalPacket pac;
772 int r = Scm_EvalCString("(%sys-mintty? 0)",
773 SCM_OBJ(Scm_GaucheInternalModule()),
774 &pac);
775 if (r == 1 && !SCM_FALSEP(pac.results[0])) return TRUE;
776 #endif /*GAUCHE_WINDOWS*/
777 return FALSE;
778 }
779
780 /* When no script is given, enter REPL. */
781 void enter_repl()
782 {
783 _Bool full_mode = FALSE;
784
785 /* Load gauche.interactive, for we're not executing a script. */
786 if (load_initfile) {
787 ScmLoadPacket lpak;
788 if (Scm_Require(SCM_MAKE_STR("gauche/interactive/init"), 0, &lpak) < 0) {
789 Scm_ReportError(lpak.exception, SCM_OBJ(SCM_CURERR));
790 Scm_Warn("Encountered an error during loading gauche.interactive. Falling back to basic REPL.");
791 } else {
792 Scm_ImportModule(SCM_CURRENT_MODULE(),
793 SCM_INTERN("gauche.interactive"), SCM_FALSE, 0);
794 full_mode = TRUE;
795 }
796 }
797
798 /* If -fcase-fold flag is given, switch the stdin port to the
799 case folding mode. */
800 if (SCM_VM_RUNTIME_FLAG_IS_SET(Scm_VM(), SCM_CASE_FOLD)) {
801 Scm_SetPortCaseFolding(SCM_PORT(Scm_Stdin()), TRUE);
802 }
803
804 if (batch_mode || (!has_terminal() && !interactive_mode)) {
805 Scm_LoadFromPort(SCM_PORT(Scm_Stdin()), SCM_LOAD_PROPAGATE_ERROR, NULL);
806 } else {
807 Scm_SetRuntimeReplState(full_mode);
808 /* Call read-eval-print-loop. If gauche.interactive is loaded,
809 this will invoke 'user-friendly' version of repl; otherwise,
810 this calls the 'bare' version in libeval.scm. */
811 Scm_EvalCString("(read-eval-print-loop)",
812 SCM_OBJ(Scm_CurrentModule()), NULL);
813 }
814 }
815
816 /* POSIX basename() may or may not modify arg, so we roll our own. */
817 static const char *safe_basename(const char *path)
818 {
819 ScmObj bn = Scm_BaseName(SCM_STRING(SCM_MAKE_STR(path)));
820 return Scm_GetStringConst(SCM_STRING(bn));
821 }
822
823 /*-----------------------------------------------------------------
824 * MAIN
825 */
826 int main(int ac, char **av)
827 {
828 const char *scriptfile = NULL;
829 ScmObj args = SCM_NIL;
830 int exit_code = 0;
831 /* NB: For Windows, we can't use passed argv array if the command-line
832 argument contains multibyte characters. We'll overwrite those later. */
833 int argc = ac;
834 char **argv = av;
835
836 #if defined(GAUCHE_WINDOWS)
837 /* Need this before core initialization */
838 int has_console = init_console();
839 #endif /*defined(GAUCHE_WINDOWS)*/
840
841 /* Experimental. This should be done before the first VM is created. */
842 {
843 const char *call_trace = getenv("GAUCHE_CALL_TRACE");
844 if (call_trace) {
845 Scm_SetCallTraceSize(strtoul(call_trace, NULL, 10));
846 }
847 }
848
849 GC_INIT();
850 Scm_Init(GAUCHE_SIGNATURE);
851 sig_setup();
852
853 #if defined(GAUCHE_WINDOWS)
854 Scm__SetupPortsForWindows(has_console);
855 # if defined(UNICODE)
856 /* Set up argument array correctly */
857 LPWSTR *argvW = CommandLineToArgvW(GetCommandLineW(), &argc);
858 argv = SCM_NEW_ARRAY(char*, argc);
859 /* Kludge! Need to discard 'const' qualifier, for getopt() expects
860 char * const*, not const char**. It's safe since Scm_WCS2MBS
861 always returns freshly allocated strings and we won't share them. */
862 for (int i=0; i<argc; i++) argv[i] = (char*)Scm_WCS2MBS(argvW[i]);
863 LocalFree(argvW);
864 # endif /* UNICODE */
865 #endif /*defined(GAUCHE_WINDOWS)*/
866
867 /* If interpreter has the name scheme-r7rs, we assume it's
868 SRFI-22 *and* R7RS script. */
869 if (strcmp(safe_basename(argv[0]), "scheme-r7rs") == 0) {
870 main_module = SCM_INTERN("r7rs.user");
871 }
872
873 /* Check command-line options */
874 int argind = parse_options(argc, argv);
875
876 /* If -ftest option is given and we seem to be in the source
877 tree, adds build directories to the library path _before_
878 loading init file. This is to help development of Gauche
879 itself; normal user should never need this. */
880 if (test_mode) test_paths_setup(av);
881
882 /* If -V is given, show version info and exit
883 (must come after test_mode setup) */
884 if (version_mode) version();
885
886 /* prepare *program-name* and *argv* */
887 if (argind < argc) {
888 /* We have a script file specified. */
889 ScmStat statbuf;
890
891 /* if the script name is given in relative pathname, see if
892 it exists from the current directory. if not, leave it
893 to load() to search in the load paths */
894 if (argv[argind][0] == '\0') Scm_Error("bad script name");
895 if (argv[argind][0] == '/') {
896 scriptfile = argv[argind];
897 #if defined(__CYGWIN__) || defined(GAUCHE_WINDOWS)
898 } else if (isalpha(argv[argind][0]) && argv[argind][1] == ':') {
899 /* support of wicked legacy DOS drive letter */
900 scriptfile = argv[argind];
901 #endif /* __CYGWIN__ || GAUCHE_WINDOWS */
902 } else {
903 if (stat(argv[argind], &statbuf) == 0) {
904 ScmDString ds;
905 Scm_DStringInit(&ds);
906 Scm_DStringPutz(&ds, "./", -1);
907 Scm_DStringPutz(&ds, argv[argind], -1);
908 scriptfile = Scm_DStringGetz(&ds);
909 } else {
910 scriptfile = argv[argind];
911 }
912 }
913
914 /* sets up arguments. */
915 Scm_InitCommandLine2(argc, (const char**)argv, SCM_COMMAND_LINE_OS);
916 args = Scm_InitCommandLine2(argc - argind, (const char**)argv + argind,
917 SCM_COMMAND_LINE_SCRIPT);
918 } else {
919 /* For REPL, we leave command-line to the default '(""). */
920 Scm_InitCommandLine2(argc, (const char**)argv, SCM_COMMAND_LINE_OS);
921 Scm_InitCommandLine2(1, (const char*[]){""}, SCM_COMMAND_LINE_SCRIPT);
922 }
923
924 process_command_args(Scm_Reverse(pre_cmds));
925
926 /* Set up instruments. */
927 ScmLoadPacket lpak;
928 if (profiling_mode) {
929 if (Scm_Require(SCM_MAKE_STR("gauche/vm/profiler"), 0, &lpak) < 0) {
930 error_exit(lpak.exception);
931 }
932 Scm_ProfilerStart();
933 }
934 Scm_AddCleanupHandler(cleanup_main, NULL);
935
936 #if defined(GAUCHE_WINDOWS)
937 /* auto wrap windows console standard ports */
938 if (!test_mode && Scm_GetEnv("GAUCHE_WINDOWS_CONSOLE_RAW") == NULL) {
939 if (!Scm_Require(SCM_MAKE_STR("os/windows/console/codepage"), 0, NULL)) {
940 Scm_EvalCString("(with-module os.windows.console.codepage (auto-wrap-windows-console-standard-ports))",
941 SCM_OBJ(Scm_UserModule()), NULL);
942 }
943 }
944 #endif /*defined(GAUCHE_WINDOWS)*/
945
946 if (default_toplevel_module != NULL) {
947 Scm_SelectModule(default_toplevel_module);
948 }
949
950 GPERFTOOLS_PROFILER_BEGIN;
951
952 /* Following is the main dish. */
953 if (scriptfile != NULL) exit_code = execute_script(scriptfile, args);
954 #if !defined(GAUCHE_WINDOWS_NOCONSOLE)
955 else enter_repl();
956 #endif /*!defined(GAUCHE_WINDOWS_NOCONSOLE)*/
957
958 /* All is done. */
959 GPERFTOOLS_PROFILER_END;
960 Scm_Exit(exit_code);
961 return 0; /*NOTREACHED*/
962 }