Ruby 4.1.0dev (2026-08-15 revision 3349f4107d268658fdf8cc6b979fbb1c923e597f)
ruby.c (3349f4107d268658fdf8cc6b979fbb1c923e597f)
1/**********************************************************************
2
3 ruby.c -
4
5 $Author$
6 created at: Tue Aug 10 12:47:31 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
11
12**********************************************************************/
13
14#include "ruby/internal/config.h"
15
16#include <ctype.h>
17#include <stdio.h>
18#include <sys/types.h>
19
20#ifdef __CYGWIN__
21# include <windows.h>
22# include <sys/cygwin.h>
23#endif
24
25#if defined(LOAD_RELATIVE) && defined(HAVE_DLADDR)
26# include <dlfcn.h>
27#endif
28
29#ifdef HAVE_UNISTD_H
30# include <unistd.h>
31#endif
32
33#if defined(HAVE_FCNTL_H)
34# include <fcntl.h>
35#elif defined(HAVE_SYS_FCNTL_H)
36# include <sys/fcntl.h>
37#endif
38
39#ifdef HAVE_SYS_PARAM_H
40# include <sys/param.h>
41#endif
42
43#include "dln.h"
44#include "eval_intern.h"
45#include "internal.h"
46#include "internal/cmdlineopt.h"
47#include "internal/cont.h"
48#include "internal/coverage.h"
49#include "internal/error.h"
50#include "internal/file.h"
51#include "internal/inits.h"
52#include "internal/io.h"
53#include "internal/load.h"
54#include "internal/loadpath.h"
55#include "internal/missing.h"
56#include "internal/object.h"
57#include "internal/thread.h"
58#include "internal/ruby_parser.h"
59#include "internal/variable.h"
60#include "ruby/encoding.h"
61#include "ruby/thread.h"
62#include "ruby/util.h"
63#include "ruby/version.h"
64#include "ruby/internal/error.h"
65
66#define singlebit_only_p(x) !((x) & ((x)-1))
67STATIC_ASSERT(Qnil_1bit_from_Qfalse, singlebit_only_p(Qnil^Qfalse));
68STATIC_ASSERT(Qundef_1bit_from_Qnil, singlebit_only_p(Qundef^Qnil));
69
70#ifndef MAXPATHLEN
71# define MAXPATHLEN 1024
72#endif
73#ifndef O_ACCMODE
74# define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
75#endif
76
77void Init_ruby_description(ruby_cmdline_options_t *opt);
78
79#ifndef HAVE_STDLIB_H
80char *getenv();
81#endif
82
83#ifndef DISABLE_RUBYGEMS
84# define DISABLE_RUBYGEMS 0
85#endif
86#if DISABLE_RUBYGEMS
87#define DEFAULT_RUBYGEMS_ENABLED "disabled"
88#else
89#define DEFAULT_RUBYGEMS_ENABLED "enabled"
90#endif
91
92void rb_warning_category_update(unsigned int mask, unsigned int bits);
93
94#define COMMA ,
95#define FEATURE_BIT(bit) (1U << feature_##bit)
96#define EACH_FEATURES(X, SEP) \
97 X(gems) \
98 SEP \
99 X(error_highlight) \
100 SEP \
101 X(did_you_mean) \
102 SEP \
103 X(syntax_suggest) \
104 SEP \
105 X(rubyopt) \
106 SEP \
107 X(frozen_string_literal) \
108 SEP \
109 X(yjit) \
110 SEP \
111 X(zjit) \
112 /* END OF FEATURES */
113#define EACH_DEBUG_FEATURES(X, SEP) \
114 X(frozen_string_literal) \
115 /* END OF DEBUG FEATURES */
116#define AMBIGUOUS_FEATURE_NAMES 0 /* no ambiguous feature names now */
117#define DEFINE_FEATURE(bit) feature_##bit
118#define DEFINE_DEBUG_FEATURE(bit) feature_debug_##bit
119enum feature_flag_bits {
120 EACH_FEATURES(DEFINE_FEATURE, COMMA),
121 DEFINE_FEATURE(frozen_string_literal_set),
122 feature_debug_flag_first,
123#if !USE_YJIT && USE_ZJIT
124 DEFINE_FEATURE(jit) = feature_zjit,
125#else
126 DEFINE_FEATURE(jit) = feature_yjit,
127#endif
128 feature_jit_mask = FEATURE_BIT(yjit) | FEATURE_BIT(zjit),
129
130 feature_debug_flag_begin = feature_debug_flag_first - 1,
131 EACH_DEBUG_FEATURES(DEFINE_DEBUG_FEATURE, COMMA),
132 feature_flag_count
133};
134
135#define MULTI_BITS_P(bits) ((bits) & ((bits) - 1))
136
137#define DEBUG_BIT(bit) (1U << feature_debug_##bit)
138
139#define DUMP_BIT(bit) (1U << dump_##bit)
140#define DEFINE_DUMP(bit) dump_##bit
141#define EACH_DUMPS(X, SEP) \
142 X(version) \
143 SEP \
144 X(copyright) \
145 SEP \
146 X(usage) \
147 SEP \
148 X(help) \
149 SEP \
150 X(yydebug) \
151 SEP \
152 X(syntax) \
153 SEP \
154 X(parsetree) \
155 SEP \
156 X(insns) \
157 /* END OF DUMPS */
158enum dump_flag_bits {
159 dump_version_v,
160 dump_opt_error_tolerant,
161 dump_opt_comment,
162 dump_opt_optimize,
163 EACH_DUMPS(DEFINE_DUMP, COMMA),
164 dump_exit_bits = (DUMP_BIT(yydebug) | DUMP_BIT(syntax) |
165 DUMP_BIT(parsetree) | DUMP_BIT(insns)),
166 dump_optional_bits = (DUMP_BIT(opt_error_tolerant) |
167 DUMP_BIT(opt_comment) |
168 DUMP_BIT(opt_optimize))
169};
170
171static inline void
172rb_feature_set_to(ruby_features_t *feat, unsigned int bit_mask, unsigned int bit_set)
173{
174 feat->mask |= bit_mask;
175 feat->set = (feat->set & ~bit_mask) | bit_set;
176}
177
178#define FEATURE_SET_TO(feat, bit_mask, bit_set) \
179 rb_feature_set_to(&(feat), bit_mask, bit_set)
180#define FEATURE_SET(feat, bits) FEATURE_SET_TO(feat, bits, bits)
181#define FEATURE_SET_RESTORE(feat, save) FEATURE_SET_TO(feat, (save).mask, (save).set & (save).mask)
182#define FEATURE_SET_P(feat, bits) ((feat).set & FEATURE_BIT(bits))
183#define FEATURE_USED_P(feat, bits) ((feat).mask & FEATURE_BIT(bits))
184#define FEATURE_SET_BITS(feat) ((feat).set & (feat).mask)
185
186static void init_ids(ruby_cmdline_options_t *);
187
188#define src_encoding_index GET_VM()->src_encoding_index
189
190enum {
191 COMPILATION_FEATURES = (
192 0
193 | FEATURE_BIT(frozen_string_literal)
194 | FEATURE_BIT(frozen_string_literal_set)
195 | FEATURE_BIT(debug_frozen_string_literal)
196 ),
197 DEFAULT_FEATURES = (
198 (FEATURE_BIT(debug_flag_first)-1)
199#if DISABLE_RUBYGEMS
200 & ~FEATURE_BIT(gems)
201#endif
202 & ~FEATURE_BIT(frozen_string_literal)
203 & ~FEATURE_BIT(frozen_string_literal_set)
204 & ~feature_jit_mask
205 )
206};
207
208#define BACKTRACE_LENGTH_LIMIT_VALID_P(n) ((n) >= -1)
209#define OPT_BACKTRACE_LENGTH_LIMIT_VALID_P(opt) \
210 BACKTRACE_LENGTH_LIMIT_VALID_P((opt)->backtrace_length_limit)
211
213cmdline_options_init(ruby_cmdline_options_t *opt)
214{
215 MEMZERO(opt, *opt, 1);
216 init_ids(opt);
217 opt->src.enc.index = src_encoding_index;
218 opt->ext.enc.index = -1;
219 opt->intern.enc.index = -1;
220 opt->features.set = DEFAULT_FEATURES;
221#if defined(YJIT_FORCE_ENABLE)
222 opt->features.set |= FEATURE_BIT(yjit);
223#endif
224 opt->dump |= DUMP_BIT(opt_optimize);
225 opt->backtrace_length_limit = LONG_MIN;
226
227 return opt;
228}
229
230static VALUE load_file(VALUE parser, VALUE fname, VALUE f, int script,
232static VALUE open_load_file(VALUE fname_v, int *xflag);
233static void forbid_setid(const char *, const ruby_cmdline_options_t *);
234#define forbid_setid(s) forbid_setid((s), opt)
235
236static struct {
237 int argc;
238 char **argv;
239} origarg;
240
241static const char esc_standout[] = "\n\033[1;7m";
242static const char esc_bold[] = "\033[1m";
243static const char esc_reset[] = "\033[0m";
244static const char esc_none[] = "";
245#define USAGE_INDENT " " /* macro for concatenation */
246
247static void
248show_usage_part(const char *str, const unsigned int namelen,
249 const char *str2, const unsigned int secondlen,
250 const char *desc,
251 int help, int highlight, unsigned int w, int columns)
252{
253 static const int indent_width = (int)rb_strlen_lit(USAGE_INDENT);
254 const char *sb = highlight ? esc_bold : esc_none;
255 const char *se = highlight ? esc_reset : esc_none;
256 unsigned int desclen = (unsigned int)strcspn(desc, "\n");
257 if (!help && desclen > 0 && strchr(".;:", desc[desclen-1])) --desclen;
258 if (help && (namelen + 1 > w) && /* a padding space */
259 (int)(namelen + secondlen + indent_width) >= columns) {
260 printf(USAGE_INDENT "%s" "%.*s" "%s\n", sb, namelen, str, se);
261 if (secondlen > 0) {
262 const int second_end = secondlen;
263 int n = 0;
264 if (str2[n] == ',') n++;
265 if (str2[n] == ' ') n++;
266 printf(USAGE_INDENT "%s" "%.*s" "%s\n", sb, second_end-n, str2+n, se);
267 }
268 printf("%-*s%.*s\n", w + indent_width, USAGE_INDENT, desclen, desc);
269 }
270 else {
271 const int wrap = help && namelen + secondlen >= w;
272 printf(USAGE_INDENT "%s%.*s%-*.*s%s%-*s%.*s\n", sb, namelen, str,
273 (wrap ? 0 : w - namelen),
274 (help ? secondlen : 0), str2, se,
275 (wrap ? (int)(w + rb_strlen_lit("\n" USAGE_INDENT)) : 0),
276 (wrap ? "\n" USAGE_INDENT : ""),
277 desclen, desc);
278 }
279 if (help) {
280 while (desc[desclen]) {
281 desc += desclen + rb_strlen_lit("\n");
282 desclen = (unsigned int)strcspn(desc, "\n");
283 printf("%-*s%.*s\n", w + indent_width, USAGE_INDENT, desclen, desc);
284 }
285 }
286}
287
288static void
289show_usage_line(const struct ruby_opt_message *m,
290 int help, int highlight, unsigned int w, int columns)
291{
292 const char *str = m->str;
293 const unsigned int namelen = m->namelen, secondlen = m->secondlen;
294 const char *desc = str + namelen + secondlen;
295 show_usage_part(str, namelen - 1, str + namelen, secondlen - 1, desc,
296 help, highlight, w, columns);
297}
298
299void
300ruby_show_usage_line(const char *name, const char *secondary, const char *description,
301 int help, int highlight, unsigned int width, int columns)
302{
303 unsigned int namelen = (unsigned int)strlen(name);
304 unsigned int secondlen = (secondary ? (unsigned int)strlen(secondary) : 0);
305 show_usage_part(name, namelen, secondary, secondlen,
306 description, help, highlight, width, columns);
307}
308
309RUBY_EXTERN const char ruby_api_version_name[];
310
311static void
312usage(const char *name, int help, int highlight, int columns)
313{
314#define M(shortopt, longopt, desc) RUBY_OPT_MESSAGE(shortopt, longopt, desc)
315
316#if USE_YJIT
317# define DEFAULT_JIT_OPTION "--yjit"
318#elif USE_ZJIT
319# define DEFAULT_JIT_OPTION "--zjit"
320#endif
321
322 /* This message really ought to be max 23 lines.
323 * Removed -h because the user already knows that option. Others? */
324 static const struct ruby_opt_message usage_msg[] = {
325 M("-0[octal]", "", "Set input record separator ($/):\n"
326 "-0 for \\0; -00 for paragraph mode; -0777 for slurp mode."),
327 M("-a", "", "Split each input line ($_) into fields ($F)."),
328 M("-c", "", "Check syntax (no execution)."),
329 M("-Cdirpath", "", "Execute program in specified directory."),
330 M("-d", ", --debug", "Set debugging flag ($DEBUG) and $VERBOSE to true."),
331 M("-e 'code'", "", "Execute given Ruby code; multiple -e allowed."),
332 M("-Eex[:in]", ", --encoding=ex[:in]", "Set default external and internal encodings."),
333 M("-Fpattern", "", "Set input field separator ($;); used with -a."),
334 M("-i[extension]", "", "Set ARGF in-place mode;\n"
335 "create backup files with given extension."),
336 M("-Idirpath", "", "Prepend specified directory to load paths ($LOAD_PATH);\n"
337 "relative paths are expanded; multiple -I are allowed."),
338 M("-l", "", "Set output record separator ($\\) to $/;\n"
339 "used for line-oriented output."),
340 M("-n", "", "Run program in gets loop."),
341 M("-p", "", "Like -n, with printing added."),
342 M("-rlibrary", "", "Require the given library."),
343 M("-s", "", "Define global variables using switches following program path."),
344 M("-S", "", "Search directories found in the PATH environment variable."),
345 M("-v", "", "Print version; set $VERBOSE to true."),
346 M("-w", "", "Synonym for -W1."),
347 M("-W[level=2|:category]", "", "Set warning flag ($-W):\n"
348 "0 for silent; 1 for moderate; 2 for verbose."),
349 M("-x[dirpath]", "", "Execute Ruby code starting from a #!ruby line."),
350#if USE_YJIT || USE_ZJIT
351 M("--jit", "", "Enable the default JIT for the build; same as " DEFAULT_JIT_OPTION "."),
352#endif
353#if USE_YJIT
354 M("--yjit", "", "Enable in-process JIT compiler."),
355#endif
356#if USE_ZJIT
357 M("--zjit", "", "Enable method-based JIT compiler."),
358#endif
359 M("-h", "", "Print this help message; use --help for longer message."),
360 };
361 STATIC_ASSERT(usage_msg_size, numberof(usage_msg) < 26);
362
363 static const struct ruby_opt_message help_msg[] = {
364 M("--backtrace-limit=num", "", "Set backtrace limit."),
365 M("--copyright", "", "Print Ruby copyright."),
366 M("--crash-report=template", "", "Set template for crash report file."),
367 M("--disable=features", "", "Disable features; see list below."),
368 M("--dump=items", "", "Dump items; see list below."),
369 M("--enable=features", "", "Enable features; see list below."),
370 M("--external-encoding=encoding", "", "Set default external encoding."),
371 M("--help", "", "Print long help message; use -h for short message."),
372 M("--internal-encoding=encoding", "", "Set default internal encoding."),
373 M("--parser=parser", "", "Set Ruby parser: parse.y or prism."),
374 M("--verbose", "", "Set $VERBOSE to true; ignore input from $stdin."),
375 M("--version", "", "Print Ruby version."),
376 M("-y", ", --yydebug", "Print parser log; backward compatibility not guaranteed."),
377 };
378 static const struct ruby_opt_message dumps[] = {
379 M("insns", "", "Instruction sequences."),
380 M("yydebug", "", "yydebug of yacc parser generator."),
381 M("parsetree", "", "Abstract syntax tree (AST)."),
382 M("-optimize", "", "Disable optimization (affects insns)."),
383 M("+error-tolerant", "", "Error-tolerant parsing (affects yydebug, parsetree)."),
384 M("+comment", "", "Add comments to AST (affects parsetree with --parser=parse.y)."),
385 };
386 static const struct ruby_opt_message features[] = {
387 M("gems", "", "Rubygems (only for debugging, default: "DEFAULT_RUBYGEMS_ENABLED")."),
388 M("error_highlight", "", "error_highlight (default: "DEFAULT_RUBYGEMS_ENABLED")."),
389 M("did_you_mean", "", "did_you_mean (default: "DEFAULT_RUBYGEMS_ENABLED")."),
390 M("syntax_suggest", "", "syntax_suggest (default: "DEFAULT_RUBYGEMS_ENABLED")."),
391 M("rubyopt", "", "RUBYOPT environment variable (default: enabled)."),
392 M("frozen-string-literal", "", "Freeze all string literals (default: disabled)."),
393#if USE_YJIT
394 M("yjit", "", "In-process JIT compiler (default: disabled)."),
395#endif
396#if USE_ZJIT
397 M("zjit", "", "Method-based JIT compiler (default: disabled)."),
398#endif
399 };
400 static const struct ruby_opt_message warn_categories[] = {
401 M("deprecated", "", "Deprecated features."),
402 M("experimental", "", "Experimental features."),
403 M("performance", "", "Performance issues."),
404 M("strict_unused_block", "", "Warning unused block strictly"),
405 };
406 int i;
407 const char *sb = highlight ? esc_standout+1 : esc_none;
408 const char *se = highlight ? esc_reset : esc_none;
409 const int num = numberof(usage_msg) - (help ? 1 : 0);
410 unsigned int w = (columns > 80 ? (columns - 79) / 2 : 0) + 16;
411#define SHOW(m) show_usage_line(&(m), help, highlight, w, columns)
412
413 printf("%sUsage:%s %s [options] [--] [filepath] [arguments]\n", sb, se, name);
414 for (i = 0; i < num; ++i)
415 SHOW(usage_msg[i]);
416
417 if (!help) return;
418
419 if (highlight) sb = esc_standout;
420
421 for (i = 0; i < numberof(help_msg); ++i)
422 SHOW(help_msg[i]);
423 printf("%s""Dump List:%s\n", sb, se);
424 for (i = 0; i < numberof(dumps); ++i)
425 SHOW(dumps[i]);
426 printf("%s""Features:%s\n", sb, se);
427 for (i = 0; i < numberof(features); ++i)
428 SHOW(features[i]);
429 printf("%s""Warning categories:%s\n", sb, se);
430 for (i = 0; i < numberof(warn_categories); ++i)
431 SHOW(warn_categories[i]);
432#if USE_YJIT
433 printf("%s""YJIT options:%s\n", sb, se);
434 rb_yjit_show_usage(help, highlight, w, columns);
435#endif
436#if USE_ZJIT
437 printf("%s""ZJIT options:%s\n", sb, se);
438 extern void rb_zjit_show_usage(int help, int highlight, unsigned int width, int columns);
439 rb_zjit_show_usage(help, highlight, w, columns);
440#endif
441}
442
443#define rubylib_path_new rb_str_new
444
445static void
446ruby_push_include(const char *path, VALUE (*filter)(VALUE))
447{
448 const char sep = PATH_SEP_CHAR;
449 const char *p, *s;
450 VALUE load_path = rb_root_box()->load_path;
451#ifdef __CYGWIN__
452 char rubylib[FILENAME_MAX];
453 VALUE buf = 0;
454# define is_path_sep(c) ((c) == sep || (c) == ';')
455#else
456# define is_path_sep(c) ((c) == sep)
457#endif
458
459 if (path == 0) return;
460 p = path;
461 while (*p) {
462 long len;
463 while (is_path_sep(*p))
464 p++;
465 if (!*p) break;
466 for (s = p; *s && !is_path_sep(*s); s = CharNext(s));
467 len = s - p;
468#undef is_path_sep
469
470#ifdef __CYGWIN__
471 if (*s) {
472 if (!buf) {
473 buf = rb_str_new(p, len);
474 p = RSTRING_PTR(buf);
475 }
476 else {
477 rb_str_resize(buf, len);
478 p = strncpy(RSTRING_PTR(buf), p, len);
479 }
480 }
481#ifdef HAVE_CYGWIN_CONV_PATH
482#define CONV_TO_POSIX_PATH(p, lib) \
483 cygwin_conv_path(CCP_WIN_A_TO_POSIX|CCP_RELATIVE, (p), (lib), sizeof(lib))
484#else
485# error no cygwin_conv_path
486#endif
487 if (CONV_TO_POSIX_PATH(p, rubylib) == 0) {
488 p = rubylib;
489 len = strlen(p);
490 }
491#endif
492 rb_ary_push(load_path, (*filter)(rubylib_path_new(p, len)));
493 p = s;
494 }
495}
496
497static VALUE
498identical_path(VALUE path)
499{
500 return path;
501}
502
503static VALUE
504locale_path(VALUE path)
505{
506 rb_enc_associate(path, rb_locale_encoding());
507 return path;
508}
509
510void
511ruby_incpush(const char *path)
512{
513 ruby_push_include(path, locale_path);
514}
515
516static VALUE
517expand_include_path(VALUE path)
518{
519 char *p = RSTRING_PTR(path);
520 if (!p)
521 return path;
522 if (*p == '.' && p[1] == '/')
523 return path;
524 return rb_file_expand_path(path, Qnil);
525}
526
527static void
528ruby_incpush_expand(const char *path)
529{
530 ruby_push_include(path, expand_include_path);
531}
532
533#undef UTF8_PATH
534#if defined _WIN32 || defined __CYGWIN__
535static HMODULE libruby;
536
537BOOL WINAPI
538DllMain(HINSTANCE dll, DWORD reason, LPVOID reserved)
539{
540 if (reason == DLL_PROCESS_ATTACH)
541 libruby = dll;
542 return TRUE;
543}
544
545HANDLE
546rb_libruby_handle(void)
547{
548 return libruby;
549}
550
551static inline void
552translit_char_bin(char *p, int from, int to)
553{
554 while (*p) {
555 if ((unsigned char)*p == from)
556 *p = to;
557 p++;
558 }
559}
560#endif
561
562#ifdef _WIN32
563# undef chdir
564# define chdir rb_w32_uchdir
565# define UTF8_PATH 1
566#endif
567
568#ifndef UTF8_PATH
569# define UTF8_PATH 0
570#endif
571#if UTF8_PATH
572# define IF_UTF8_PATH(t, f) t
573#else
574# define IF_UTF8_PATH(t, f) f
575#endif
576
577#if UTF8_PATH
578static VALUE
579str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
580{
581 return rb_str_conv_enc_opts(str, from, to,
583 Qnil);
584}
585#else
586# define str_conv_enc(str, from, to) (str)
587#endif
588
589void ruby_init_loadpath(void);
590
591#if defined(LOAD_RELATIVE)
592static VALUE
593runtime_libruby_path(void)
594{
595#if defined _WIN32 || defined __CYGWIN__
596 DWORD ret;
597 DWORD len = 32;
598 VALUE path;
599 VALUE wsopath = rb_str_new(0, len*sizeof(WCHAR));
600 WCHAR *wlibpath;
601 char *libpath;
602
603 while (wlibpath = (WCHAR *)RSTRING_PTR(wsopath),
604 ret = GetModuleFileNameW(libruby, wlibpath, len),
605 (ret == len))
606 {
607 rb_str_modify_expand(wsopath, len*sizeof(WCHAR));
608 rb_str_set_len(wsopath, (len += len)*sizeof(WCHAR));
609 }
610 if (!ret || ret > len) rb_fatal("failed to get module file name");
611#if defined __CYGWIN__
612 {
613 const int win_to_posix = CCP_WIN_W_TO_POSIX | CCP_RELATIVE;
614 size_t newsize = cygwin_conv_path(win_to_posix, wlibpath, 0, 0);
615 if (!newsize) rb_fatal("failed to convert module path to cygwin");
616 path = rb_str_new(0, newsize);
617 libpath = RSTRING_PTR(path);
618 if (cygwin_conv_path(win_to_posix, wlibpath, libpath, newsize)) {
619 rb_str_resize(path, 0);
620 }
621 }
622#else
623 {
624 DWORD i;
625 for (len = ret, i = 0; i < len; ++i) {
626 if (wlibpath[i] == L'\\') {
627 wlibpath[i] = L'/';
628 ret = i+1; /* chop after the last separator */
629 }
630 }
631 }
632 len = WideCharToMultiByte(CP_UTF8, 0, wlibpath, ret, NULL, 0, NULL, NULL);
633 path = rb_utf8_str_new(0, len);
634 libpath = RSTRING_PTR(path);
635 WideCharToMultiByte(CP_UTF8, 0, wlibpath, ret, libpath, len, NULL, NULL);
636#endif
637 rb_str_resize(wsopath, 0);
638 return path;
639#elif defined(HAVE_DLADDR)
640 Dl_info dli;
641 VALUE fname, path;
642 const void* addr = (void *)(VALUE)expand_include_path;
643
644 if (!dladdr((void *)addr, &dli)) {
645 return rb_str_new(0, 0);
646 }
647#ifdef __linux__
648 else if (origarg.argc > 0 && origarg.argv && dli.dli_fname == origarg.argv[0]) {
649 fname = rb_str_new_cstr("/proc/self/exe");
650 path = rb_readlink(fname, NULL);
651 }
652#endif
653 else {
654 fname = rb_str_new_cstr(dli.dli_fname);
655 path = rb_realpath_internal(Qnil, fname, 1);
656 }
657 rb_str_resize(fname, 0);
658 return path;
659#else
660# error relative load path is not supported on this platform.
661#endif
662}
663#endif
664
665#define INITIAL_LOAD_PATH_MARK rb_intern_const("@gem_prelude_index")
666
667VALUE ruby_archlibdir_path, ruby_prefix_path;
668
669void
671{
672 VALUE load_path, archlibdir = 0;
673 ID id_initial_load_path_mark;
674 const char *paths = ruby_initial_load_paths;
675
676#if defined LOAD_RELATIVE
677#if !defined ENABLE_MULTIARCH
678# define RUBY_ARCH_PATH ""
679#elif defined RUBY_ARCH
680# define RUBY_ARCH_PATH "/"RUBY_ARCH
681#else
682# define RUBY_ARCH_PATH "/"RUBY_PLATFORM
683#endif
684 char *libpath;
685 VALUE sopath;
686 size_t baselen;
687 const char *p;
688
689 sopath = runtime_libruby_path();
690 libpath = RSTRING_PTR(sopath);
691
692 p = strrchr(libpath, '/');
693 if (p) {
694 static const char libdir[] = "/"
695#ifdef LIBDIR_BASENAME
696 LIBDIR_BASENAME
697#else
698 "lib"
699#endif
700 RUBY_ARCH_PATH;
701 const ptrdiff_t libdir_len = (ptrdiff_t)sizeof(libdir)
702 - rb_strlen_lit(RUBY_ARCH_PATH) - 1;
703 static const char bindir[] = "/bin";
704 const ptrdiff_t bindir_len = (ptrdiff_t)sizeof(bindir) - 1;
705
706 const char *p2 = NULL;
707
708#ifdef ENABLE_MULTIARCH
709 multiarch:
710#endif
711 if (p - libpath >= bindir_len && !STRNCASECMP(p - bindir_len, bindir, bindir_len)) {
712 p -= bindir_len;
713 archlibdir = rb_str_subseq(sopath, 0, p - libpath);
714 rb_str_cat_cstr(archlibdir, libdir);
715 OBJ_FREEZE(archlibdir);
716 }
717 else if (p - libpath >= libdir_len && !strncmp(p - libdir_len, libdir, libdir_len)) {
718 archlibdir = rb_str_subseq(sopath, 0, (p2 ? p2 : p) - libpath);
719 OBJ_FREEZE(archlibdir);
720 p -= libdir_len;
721 }
722#ifdef ENABLE_MULTIARCH
723 else if (p2) {
724 p = p2;
725 }
726 else {
727 p2 = p;
728 p = rb_enc_path_last_separator(libpath, p, rb_ascii8bit_encoding());
729 if (p) goto multiarch;
730 p = p2;
731 }
732#endif
733 baselen = p - libpath;
734 }
735 else {
736 baselen = 0;
737 }
738 rb_str_resize(sopath, baselen);
739 libpath = RSTRING_PTR(sopath);
740#define PREFIX_PATH() sopath
741#define BASEPATH() rb_str_buf_cat(rb_str_buf_new(baselen+len), libpath, baselen)
742#define RUBY_RELATIVE(path, len) rb_str_buf_cat(BASEPATH(), (path), (len))
743#else
744 const size_t exec_prefix_len = strlen(ruby_exec_prefix);
745#define RUBY_RELATIVE(path, len) rubylib_path_new((path), (len))
746#define PREFIX_PATH() RUBY_RELATIVE(ruby_exec_prefix, exec_prefix_len)
747#endif
748 rb_gc_register_address(&ruby_prefix_path);
749 ruby_prefix_path = PREFIX_PATH();
750 OBJ_FREEZE(ruby_prefix_path);
751 if (!archlibdir) archlibdir = ruby_prefix_path;
752 rb_gc_register_address(&ruby_archlibdir_path);
753 ruby_archlibdir_path = archlibdir;
754
755 load_path = rb_root_box()->load_path;
756
757 ruby_push_include(getenv("RUBYLIB"), identical_path);
758
759 id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK;
760 while (*paths) {
761 size_t len = strlen(paths);
762 VALUE path = RUBY_RELATIVE(paths, len);
763 rb_ivar_set(path, id_initial_load_path_mark, path);
764 rb_ary_push(load_path, path);
765 paths += len + 1;
766 }
767}
768
769
770static void
771add_modules(VALUE *req_list, const char *mod)
772{
773 VALUE list = *req_list;
774 VALUE feature;
775
776 if (!list) {
777 *req_list = list = rb_ary_hidden_new(0);
778 }
779 feature = rb_str_cat_cstr(rb_str_tmp_new(0), mod);
780 rb_ary_push(list, feature);
781}
782
783static void
784require_libraries(VALUE *req_list)
785{
786 VALUE list = *req_list;
787 VALUE self = rb_vm_top_self();
788 ID require;
789 rb_encoding *extenc = rb_default_external_encoding();
790
791 CONST_ID(require, "require");
792 while (list && RARRAY_LEN(list) > 0) {
793 VALUE feature = rb_ary_shift(list);
794 rb_enc_associate(feature, extenc);
795 RBASIC_SET_CLASS_RAW(feature, rb_cString);
796 OBJ_FREEZE(feature);
797 rb_funcallv(self, require, 1, &feature);
798 }
799 *req_list = 0;
800}
801
802static void
803require_libraries_in_main_box(VALUE *req_list)
804{
805 const rb_box_t *main_box = rb_main_box();
806 VALUE list = *req_list;
807 ID require;
808 rb_encoding *extenc = rb_default_external_encoding();
809
810 CONST_ID(require, "require");
811 while (list && RARRAY_LEN(list) > 0) {
812 VALUE feature = rb_ary_shift(list);
813 rb_enc_associate(feature, extenc);
814 RBASIC_SET_CLASS_RAW(feature, rb_cString);
815 OBJ_FREEZE(feature);
816 rb_funcallv(main_box->box_object, require, 1, &feature);
817 }
818 *req_list = 0;
819}
820
821static const struct rb_block*
822toplevel_context(rb_binding_t *bind)
823{
824 return &bind->block;
825}
826
827static int
828process_sflag(int sflag)
829{
830 if (sflag > 0) {
831 long n;
832 const VALUE *args;
833 VALUE argv = rb_argv;
834
835 n = RARRAY_LEN(argv);
836 args = RARRAY_CONST_PTR(argv);
837 while (n > 0) {
838 VALUE v = *args++;
839 char *s = StringValuePtr(v);
840 char *p;
841 int hyphen = FALSE;
842
843 if (s[0] != '-')
844 break;
845 n--;
846 if (s[1] == '-' && s[2] == '\0')
847 break;
848
849 v = Qtrue;
850 /* check if valid name before replacing - with _ */
851 for (p = s + 1; *p; p++) {
852 if (*p == '=') {
853 *p++ = '\0';
854 v = rb_str_new2(p);
855 break;
856 }
857 if (*p == '-') {
858 hyphen = TRUE;
859 }
860 else if (*p != '_' && !ISALNUM(*p)) {
861 VALUE name_error[2];
862 name_error[0] =
863 rb_str_new2("invalid name for global variable - ");
864 if (!(p = strchr(p, '='))) {
865 rb_str_cat2(name_error[0], s);
866 }
867 else {
868 rb_str_cat(name_error[0], s, p - s);
869 }
870 name_error[1] = args[-1];
872 }
873 }
874 s[0] = '$';
875 if (hyphen) {
876 for (p = s + 1; *p; ++p) {
877 if (*p == '-')
878 *p = '_';
879 }
880 }
881 rb_gv_set(s, v);
882 }
883 n = RARRAY_LEN(argv) - n;
884 while (n--) {
885 rb_ary_shift(argv);
886 }
887 return -1;
888 }
889 return sflag;
890}
891
892static long proc_options(long argc, char **argv, ruby_cmdline_options_t *opt, int envopt);
893
894static void
895moreswitches(const char *s, ruby_cmdline_options_t *opt, int envopt)
896{
897 long argc, i, len;
898 char **argv, *p;
899 const char *ap = 0;
900 VALUE argstr, argary;
901 void *ptr;
902
903 VALUE src_enc_name = opt->src.enc.name;
904 VALUE ext_enc_name = opt->ext.enc.name;
905 VALUE int_enc_name = opt->intern.enc.name;
906 ruby_features_t feat = opt->features;
907 ruby_features_t warn = opt->warn;
908 long backtrace_length_limit = opt->backtrace_length_limit;
909 const char *crash_report = opt->crash_report;
910
911 while (ISSPACE(*s)) s++;
912 if (!*s) return;
913
914 opt->src.enc.name = opt->ext.enc.name = opt->intern.enc.name = 0;
915
916 const int hyphen = *s != '-';
917 argstr = rb_str_tmp_new((len = strlen(s)) + hyphen);
918 argary = rb_str_tmp_new(0);
919
920 p = RSTRING_PTR(argstr);
921 if (hyphen) *p = '-';
922 memcpy(p + hyphen, s, len + 1);
923 ap = 0;
924 rb_str_cat(argary, (char *)&ap, sizeof(ap));
925 while (*p) {
926 ap = p;
927 rb_str_cat(argary, (char *)&ap, sizeof(ap));
928 while (*p && !ISSPACE(*p)) ++p;
929 if (!*p) break;
930 *p++ = '\0';
931 while (ISSPACE(*p)) ++p;
932 }
933 argc = RSTRING_LEN(argary) / sizeof(ap);
934 ap = 0;
935 rb_str_cat(argary, (char *)&ap, sizeof(ap));
936
937 VALUE ptr_obj;
938 argv = ptr = RB_ALLOCV_N(char *, ptr_obj, argc);
939 MEMMOVE(argv, RSTRING_PTR(argary), char *, argc);
940
941 while ((i = proc_options(argc, argv, opt, envopt)) > 1 && envopt && (argc -= i) > 0) {
942 argv += i;
943 if (**argv != '-') {
944 *--*argv = '-';
945 }
946 if ((*argv)[1]) {
947 ++argc;
948 --argv;
949 }
950 }
951
952 if (src_enc_name) {
953 opt->src.enc.name = src_enc_name;
954 }
955 if (ext_enc_name) {
956 opt->ext.enc.name = ext_enc_name;
957 }
958 if (int_enc_name) {
959 opt->intern.enc.name = int_enc_name;
960 }
961 FEATURE_SET_RESTORE(opt->features, feat);
962 FEATURE_SET_RESTORE(opt->warn, warn);
963 if (BACKTRACE_LENGTH_LIMIT_VALID_P(backtrace_length_limit)) {
964 opt->backtrace_length_limit = backtrace_length_limit;
965 }
966 if (crash_report) {
967 opt->crash_report = crash_report;
968 }
969
970 RB_ALLOCV_END(ptr_obj);
971
972 /* get rid of GC */
973 rb_str_resize(argary, 0);
974 rb_str_resize(argstr, 0);
975}
976
977static int
978name_match_p(const char *name, const char *str, size_t len)
979{
980 if (len == 0) return 0;
981 while (1) {
982 while (TOLOWER(*str) == *name) {
983 if (!--len) return 1;
984 ++name;
985 ++str;
986 }
987 if (*str != '-' && *str != '_') return 0;
988 while (ISALNUM(*name)) name++;
989 if (*name != '-' && *name != '_') return 0;
990 if (!*++name) return 1;
991 ++str;
992 if (--len == 0) return 1;
993 }
994}
995
996#define NAME_MATCH_P(name, str, len) \
997 ((len) < (int)sizeof(name) && name_match_p((name), (str), (len)))
998
999#define UNSET_WHEN(name, bit, str, len) \
1000 if (NAME_MATCH_P((name), (str), (len))) { \
1001 *(unsigned int *)arg &= ~(bit); \
1002 return; \
1003 }
1004
1005#define SET_WHEN(name, bit, str, len) \
1006 if (NAME_MATCH_P((name), (str), (len))) { \
1007 *(unsigned int *)arg |= (bit); \
1008 return; \
1009 }
1010
1011#define LITERAL_NAME_ELEMENT(name) #name
1012
1013static void
1014feature_option(const char *str, int len, void *arg, const unsigned int enable)
1015{
1016 static const char list[] = EACH_FEATURES(LITERAL_NAME_ELEMENT, ", ");
1017 ruby_features_t *argp = arg;
1018 unsigned int mask = ~0U;
1019 unsigned int set = 0U;
1020#if AMBIGUOUS_FEATURE_NAMES
1021 int matched = 0;
1022# define FEATURE_FOUND ++matched
1023#else
1024# define FEATURE_FOUND goto found
1025#endif
1026#define SET_FEATURE(bit) \
1027 if (NAME_MATCH_P(#bit, str, len)) {set |= mask = FEATURE_BIT(bit); FEATURE_FOUND;}
1028 EACH_FEATURES(SET_FEATURE, ;);
1029 if (NAME_MATCH_P("jit", str, len)) { // This allows you to cancel --jit
1030 set |= mask = FEATURE_BIT(jit);
1031 goto found;
1032 }
1033 if (NAME_MATCH_P("all", str, len)) {
1034 // We enable only one JIT for --enable=all.
1035 mask &= ~feature_jit_mask | FEATURE_BIT(jit);
1036 goto found;
1037 }
1038#if AMBIGUOUS_FEATURE_NAMES
1039 if (matched == 1) goto found;
1040 if (matched > 1) {
1041 VALUE mesg = rb_sprintf("ambiguous feature: '%.*s' (", len, str);
1042#define ADD_FEATURE_NAME(bit) \
1043 if (FEATURE_BIT(bit) & set) { \
1044 rb_str_cat_cstr(mesg, #bit); \
1045 if (--matched) rb_str_cat_cstr(mesg, ", "); \
1046 }
1047 EACH_FEATURES(ADD_FEATURE_NAME, ;);
1048 rb_str_cat_cstr(mesg, ")");
1050#undef ADD_FEATURE_NAME
1051 }
1052#else
1053 (void)set;
1054#endif
1055 rb_warn("unknown argument for --%s: '%.*s'",
1056 enable ? "enable" : "disable", len, str);
1057 rb_warn("features are [%.*s].", (int)strlen(list), list);
1058 return;
1059
1060 found:
1061 FEATURE_SET_TO(*argp, mask, (mask & enable));
1062 if (NAME_MATCH_P("frozen_string_literal", str, len)) {
1063 FEATURE_SET_TO(*argp, FEATURE_BIT(frozen_string_literal_set), FEATURE_BIT(frozen_string_literal_set));
1064 }
1065 return;
1066}
1067
1068static void
1069enable_option(const char *str, int len, void *arg)
1070{
1071 feature_option(str, len, arg, ~0U);
1072}
1073
1074static void
1075disable_option(const char *str, int len, void *arg)
1076{
1077 feature_option(str, len, arg, 0U);
1078}
1079
1081int ruby_env_debug_option(const char *str, int len, void *arg);
1082
1083static void
1084debug_option(const char *str, int len, void *arg)
1085{
1086 static const char list[] = EACH_DEBUG_FEATURES(LITERAL_NAME_ELEMENT, ", ");
1087 ruby_features_t *argp = arg;
1088#define SET_WHEN_DEBUG(bit) \
1089 if (NAME_MATCH_P(#bit, str, len)) { \
1090 FEATURE_SET(*argp, DEBUG_BIT(bit)); \
1091 return; \
1092 }
1093 EACH_DEBUG_FEATURES(SET_WHEN_DEBUG, ;);
1094#ifdef RUBY_DEVEL
1095 if (ruby_patchlevel < 0 && ruby_env_debug_option(str, len, 0)) return;
1096#endif
1097 rb_warn("unknown argument for --debug: '%.*s'", len, str);
1098 rb_warn("debug features are [%.*s].", (int)strlen(list), list);
1099}
1100
1101static int
1102memtermspn(const char *str, char term, int len)
1103{
1104 RUBY_ASSERT(len >= 0);
1105 if (len <= 0) return 0;
1106 const char *next = memchr(str, term, len);
1107 return next ? (int)(next - str) : len;
1108}
1109
1110static const char additional_opt_sep = '+';
1111
1112static unsigned int
1113dump_additional_option_flag(const char *str, int len, unsigned int bits, bool set)
1114{
1115#define SET_DUMP_OPT(bit) if (NAME_MATCH_P(#bit, str, len)) { \
1116 return set ? (bits | DUMP_BIT(opt_ ## bit)) : (bits & ~DUMP_BIT(opt_ ## bit)); \
1117 }
1118 SET_DUMP_OPT(error_tolerant);
1119 SET_DUMP_OPT(comment);
1120 SET_DUMP_OPT(optimize);
1121#undef SET_DUMP_OPT
1122 rb_warn("don't know how to dump with%s '%.*s'", set ? "" : "out", len, str);
1123 return bits;
1124}
1125
1126static unsigned int
1127dump_additional_option(const char *str, int len, unsigned int bits)
1128{
1129 int w;
1130 for (; len-- > 0 && *str++ == additional_opt_sep; len -= w, str += w) {
1131 w = memtermspn(str, additional_opt_sep, len);
1132 bool set = true;
1133 if (*str == '-' || *str == '+') {
1134 set = *str++ == '+';
1135 --w;
1136 }
1137 else {
1138 int n = memtermspn(str, '-', w);
1139 if (str[n] == '-') {
1140 if (NAME_MATCH_P("with", str, n)) {
1141 str += n;
1142 w -= n;
1143 }
1144 else if (NAME_MATCH_P("without", str, n)) {
1145 set = false;
1146 str += n;
1147 w -= n;
1148 }
1149 }
1150 }
1151 bits = dump_additional_option_flag(str, w, bits, set);
1152 }
1153 return bits;
1154}
1155
1156static void
1157dump_option(const char *str, int len, void *arg)
1158{
1159 static const char list[] = EACH_DUMPS(LITERAL_NAME_ELEMENT, ", ");
1160 unsigned int *bits_ptr = (unsigned int *)arg;
1161 if (*str == '+' || *str == '-') {
1162 bool set = *str++ == '+';
1163 *bits_ptr = dump_additional_option_flag(str, --len, *bits_ptr, set);
1164 return;
1165 }
1166 int w = memtermspn(str, additional_opt_sep, len);
1167
1168#define SET_WHEN_DUMP(bit) \
1169 if (NAME_MATCH_P(#bit "-", (str), (w))) { \
1170 *bits_ptr = dump_additional_option(str + w, len - w, *bits_ptr | DUMP_BIT(bit)); \
1171 return; \
1172 }
1173 EACH_DUMPS(SET_WHEN_DUMP, ;);
1174 rb_warn("don't know how to dump '%.*s',", len, str);
1175 rb_warn("but only [%.*s].", (int)strlen(list), list);
1176}
1177
1178static void
1179set_option_encoding_once(const char *type, VALUE *name, const char *e, long elen)
1180{
1181 VALUE ename;
1182
1183 if (!elen) elen = strlen(e);
1184 ename = rb_str_new(e, elen);
1185
1186 if (*name &&
1187 rb_funcall(ename, rb_intern("casecmp"), 1, *name) != INT2FIX(0)) {
1188 rb_raise(rb_eRuntimeError,
1189 "%s already set to %"PRIsVALUE, type, *name);
1190 }
1191 *name = ename;
1192}
1193
1194#define set_internal_encoding_once(opt, e, elen) \
1195 set_option_encoding_once("default_internal", &(opt)->intern.enc.name, (e), (elen))
1196#define set_external_encoding_once(opt, e, elen) \
1197 set_option_encoding_once("default_external", &(opt)->ext.enc.name, (e), (elen))
1198#define set_source_encoding_once(opt, e, elen) \
1199 set_option_encoding_once("source", &(opt)->src.enc.name, (e), (elen))
1200
1201#define yjit_opt_match_noarg(s, l, name) \
1202 opt_match(s, l, name) && (*(s) ? (rb_warn("argument to --yjit-" name " is ignored"), 1) : 1)
1203#define yjit_opt_match_arg(s, l, name) \
1204 opt_match(s, l, name) && (*(s) && *(s+1) ? 1 : (rb_raise(rb_eRuntimeError, "--yjit-" name " needs an argument"), 0))
1205
1206#if USE_YJIT
1207static bool
1208setup_yjit_options(const char *s)
1209{
1210 // The option parsing is done in yjit/src/options.rs
1211 bool rb_yjit_parse_option(const char* s);
1212 bool success = rb_yjit_parse_option(s);
1213
1214 if (success) {
1215 return true;
1216 }
1217
1218 rb_raise(
1220 "invalid YJIT option '%s' (--help will show valid yjit options)",
1221 s
1222 );
1223}
1224#endif
1225
1226#if USE_ZJIT
1227static void
1228setup_zjit_options(const char *s)
1229{
1230 // The option parsing is done in zjit/src/options.rs
1231 extern bool rb_zjit_parse_option(const char *s);
1232
1233 if (!rb_zjit_parse_option(s)) {
1234 rb_raise(rb_eRuntimeError, "invalid ZJIT option '%s' (--help will show valid zjit options)", s);
1235 }
1236}
1237#endif
1238
1239/*
1240 * Following proc_*_option functions are tree kinds:
1241 *
1242 * - with a required argument, takes also `argc` and `argv`, and
1243 * returns the number of consumed argv including the option itself.
1244 *
1245 * - with a mandatory argument just after the option.
1246 *
1247 * - no required argument, this returns the address of
1248 * the next character after the last consumed character.
1249 */
1250
1251/* optional */
1252static const char *
1253proc_W_option(ruby_cmdline_options_t *opt, const char *s, int *warning)
1254{
1255 if (s[1] == ':') {
1256 unsigned int bits = 0;
1257 static const char no_prefix[] = "no-";
1258 int enable = strncmp(s += 2, no_prefix, sizeof(no_prefix)-1) != 0;
1259 if (!enable) s += sizeof(no_prefix)-1;
1260 size_t len = strlen(s);
1261 if (NAME_MATCH_P("deprecated", s, len)) {
1262 bits = 1U << RB_WARN_CATEGORY_DEPRECATED;
1263 }
1264 else if (NAME_MATCH_P("experimental", s, len)) {
1265 bits = 1U << RB_WARN_CATEGORY_EXPERIMENTAL;
1266 }
1267 else if (NAME_MATCH_P("performance", s, len)) {
1268 bits = 1U << RB_WARN_CATEGORY_PERFORMANCE;
1269 }
1270 else if (NAME_MATCH_P("strict_unused_block", s, len)) {
1272 }
1273 else {
1274 rb_warn("unknown warning category: '%s'", s);
1275 }
1276 if (bits) FEATURE_SET_TO(opt->warn, bits, enable ? bits : 0);
1277 return 0;
1278 }
1279 else {
1280 size_t numlen;
1281 int v = 2; /* -W as -W2 */
1282
1283 if (*++s) {
1284 v = scan_oct(s, 1, &numlen);
1285 if (numlen == 0)
1286 v = 2;
1287 s += numlen;
1288 }
1289 if (!opt->warning) {
1290 switch (v) {
1291 case 0:
1293 break;
1294 case 1:
1296 break;
1297 default:
1299 break;
1300 }
1301 }
1302 *warning = 1;
1303 switch (v) {
1304 case 0:
1305 FEATURE_SET_TO(opt->warn, RB_WARN_CATEGORY_DEFAULT_BITS, 0);
1306 break;
1307 case 1:
1308 FEATURE_SET_TO(opt->warn, 1U << RB_WARN_CATEGORY_DEPRECATED, 0);
1309 break;
1310 default:
1311 FEATURE_SET(opt->warn, RB_WARN_CATEGORY_DEFAULT_BITS);
1312 break;
1313 }
1314 return s;
1315 }
1316}
1317
1318/* required */
1319static long
1320proc_e_option(ruby_cmdline_options_t *opt, const char *s, long argc, char **argv)
1321{
1322 long n = 1;
1323 forbid_setid("-e");
1324 if (!*++s) {
1325 if (!--argc)
1326 rb_raise(rb_eRuntimeError, "no code specified for -e");
1327 s = *++argv;
1328 n++;
1329 }
1330 if (!opt->e_script) {
1331 opt->e_script = rb_str_new(0, 0);
1332 if (opt->script == 0)
1333 opt->script = "-e";
1334 }
1335 rb_str_cat2(opt->e_script, s);
1336 rb_str_cat2(opt->e_script, "\n");
1337 return n;
1338}
1339
1340/* optional */
1341static const char *
1342proc_K_option(ruby_cmdline_options_t *opt, const char *s)
1343{
1344 if (*++s) {
1345 const char *enc_name = 0;
1346 switch (*s) {
1347 case 'E': case 'e':
1348 enc_name = "EUC-JP";
1349 break;
1350 case 'S': case 's':
1351 enc_name = "Windows-31J";
1352 break;
1353 case 'U': case 'u':
1354 enc_name = "UTF-8";
1355 break;
1356 case 'N': case 'n': case 'A': case 'a':
1357 enc_name = "ASCII-8BIT";
1358 break;
1359 }
1360 if (enc_name) {
1361 opt->src.enc.name = rb_str_new2(enc_name);
1362 if (!opt->ext.enc.name)
1363 opt->ext.enc.name = opt->src.enc.name;
1364 }
1365 s++;
1366 }
1367 return s;
1368}
1369
1370/* optional */
1371static const char *
1372proc_0_option(ruby_cmdline_options_t *opt, const char *s)
1373{
1374 size_t numlen;
1375 int v;
1376 char c;
1377
1378 v = scan_oct(s, 4, &numlen);
1379 s += numlen;
1380 if (v > 0377)
1381 rb_rs = Qnil;
1382 else if (v == 0 && numlen >= 2) {
1383 rb_rs = rb_fstring_lit("");
1384 }
1385 else {
1386 c = v & 0xff;
1387 rb_rs = rb_str_freeze(rb_str_new(&c, 1));
1388 }
1389 return s;
1390}
1391
1392/* mandatory */
1393static void
1394proc_encoding_option(ruby_cmdline_options_t *opt, const char *s, const char *opt_name)
1395{
1396 const char *p;
1397# define set_encoding_part(type) \
1398 if (!(p = strchr(s, ':'))) { \
1399 set_##type##_encoding_once(opt, s, 0); \
1400 return; \
1401 } \
1402 else if (p > s) { \
1403 set_##type##_encoding_once(opt, s, p-s); \
1404 }
1405 set_encoding_part(external);
1406 if (!*(s = ++p)) return;
1407 set_encoding_part(internal);
1408 if (!*(s = ++p)) return;
1409#if defined ALLOW_DEFAULT_SOURCE_ENCODING && ALLOW_DEFAULT_SOURCE_ENCODING
1410 set_encoding_part(source);
1411 if (!*(s = ++p)) return;
1412#endif
1413 rb_raise(rb_eRuntimeError, "extra argument for %s: %s", opt_name, s);
1414# undef set_encoding_part
1416}
1417
1418static long
1419proc_long_options(ruby_cmdline_options_t *opt, const char *s, long argc, char **argv, int envopt)
1420{
1421 size_t n;
1422 long argc0 = argc;
1423# define is_option_end(c, allow_hyphen) \
1424 (!(c) || ((allow_hyphen) && (c) == '-') || (c) == '=')
1425# define check_envopt(name, allow_envopt) \
1426 (((allow_envopt) || !envopt) ? (void)0 : \
1427 rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --" name))
1428# define need_argument(name, s, needs_arg, next_arg) \
1429 ((*(s) ? !*++(s) : (next_arg) && (argc <= 1 || !((s) = argv[1]) || (--argc, ++argv, 0))) && (needs_arg) ? \
1430 rb_raise(rb_eRuntimeError, "missing argument for --" name) \
1431 : (void)0)
1432# define is_option_with_arg(name, allow_hyphen, allow_envopt) \
1433 is_option_with_optarg(name, allow_hyphen, allow_envopt, Qtrue, Qtrue)
1434# define is_option_with_optarg(name, allow_hyphen, allow_envopt, needs_arg, next_arg) \
1435 (strncmp((name), s, n = sizeof(name) - 1) == 0 && is_option_end(s[n], (allow_hyphen)) && \
1436 (s[n] != '-' || (s[n] && s[n+1])) ? \
1437 (check_envopt(name, (allow_envopt)), s += n, \
1438 need_argument(name, s, needs_arg, next_arg), 1) : 0)
1439
1440 if (strcmp("copyright", s) == 0) {
1441 if (envopt) goto noenvopt_long;
1442 opt->dump |= DUMP_BIT(copyright);
1443 }
1444 else if (is_option_with_optarg("debug", Qtrue, Qtrue, Qfalse, Qfalse)) {
1445 if (s && *s) {
1446 ruby_each_words(s, debug_option, &opt->features);
1447 }
1448 else {
1449 ruby_debug = Qtrue;
1451 }
1452 }
1453 else if (is_option_with_arg("enable", Qtrue, Qtrue)) {
1454 ruby_each_words(s, enable_option, &opt->features);
1455 }
1456 else if (is_option_with_arg("disable", Qtrue, Qtrue)) {
1457 ruby_each_words(s, disable_option, &opt->features);
1458 }
1459 else if (is_option_with_arg("encoding", Qfalse, Qtrue)) {
1460 proc_encoding_option(opt, s, "--encoding");
1461 }
1462 else if (is_option_with_arg("internal-encoding", Qfalse, Qtrue)) {
1463 set_internal_encoding_once(opt, s, 0);
1464 }
1465 else if (is_option_with_arg("external-encoding", Qfalse, Qtrue)) {
1466 set_external_encoding_once(opt, s, 0);
1467 }
1468 else if (is_option_with_arg("parser", Qfalse, Qtrue)) {
1469 if (strcmp("prism", s) == 0) {
1470 rb_ruby_default_parser_set(RB_DEFAULT_PARSER_PRISM);
1471 }
1472 else if (strcmp("parse.y", s) == 0) {
1473 rb_ruby_default_parser_set(RB_DEFAULT_PARSER_PARSE_Y);
1474 }
1475 else {
1476 rb_raise(rb_eRuntimeError, "unknown parser %s", s);
1477 }
1478 }
1479#if defined ALLOW_DEFAULT_SOURCE_ENCODING && ALLOW_DEFAULT_SOURCE_ENCODING
1480 else if (is_option_with_arg("source-encoding", Qfalse, Qtrue)) {
1481 set_source_encoding_once(opt, s, 0);
1482 }
1483#endif
1484 else if (strcmp("version", s) == 0) {
1485 if (envopt) goto noenvopt_long;
1486 opt->dump |= DUMP_BIT(version);
1487 }
1488 else if (strcmp("verbose", s) == 0) {
1489 opt->verbose = 1;
1491 }
1492 else if (strcmp("jit", s) == 0) {
1493#if USE_YJIT || USE_ZJIT
1494 FEATURE_SET(opt->features, FEATURE_BIT(jit));
1495#else
1496 rb_warn("Ruby was built without JIT support");
1497#endif
1498 }
1499 else if (is_option_with_optarg("yjit", '-', true, false, false)) {
1500#if USE_YJIT
1501 FEATURE_SET(opt->features, FEATURE_BIT(yjit));
1502 setup_yjit_options(s);
1503#else
1504 rb_warn("Ruby was built without YJIT support."
1505 " You may need to install rustc to build Ruby with YJIT.");
1506#endif
1507 }
1508 else if (is_option_with_optarg("zjit", '-', true, false, false)) {
1509#if USE_ZJIT
1510 FEATURE_SET(opt->features, FEATURE_BIT(zjit));
1511 setup_zjit_options(s);
1512#else
1513 rb_warn("Ruby was built without ZJIT support."
1514 " You may need to install rustc to build Ruby with ZJIT.");
1515#endif
1516 }
1517 else if (strcmp("yydebug", s) == 0) {
1518 if (envopt) goto noenvopt_long;
1519 opt->dump |= DUMP_BIT(yydebug);
1520 }
1521 else if (is_option_with_arg("dump", Qfalse, Qfalse)) {
1522 ruby_each_words(s, dump_option, &opt->dump);
1523 }
1524 else if (strcmp("help", s) == 0) {
1525 if (envopt) goto noenvopt_long;
1526 opt->dump |= DUMP_BIT(help);
1527 return 0;
1528 }
1529 else if (is_option_with_arg("backtrace-limit", Qfalse, Qtrue)) {
1530 char *e;
1531 long n = strtol(s, &e, 10);
1532 if (errno == ERANGE || !BACKTRACE_LENGTH_LIMIT_VALID_P(n) || *e) {
1533 rb_raise(rb_eRuntimeError, "wrong limit for backtrace length");
1534 }
1535 else {
1536 opt->backtrace_length_limit = n;
1537 }
1538 }
1539 else if (is_option_with_arg("crash-report", true, true)) {
1540 opt->crash_report = s;
1541 }
1542 else {
1543 rb_raise(rb_eRuntimeError,
1544 "invalid option --%s (-h will show valid options)", s);
1545 }
1546 return argc0 - argc + 1;
1547
1548 noenvopt_long:
1549 rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --%s", s);
1550# undef is_option_end
1551# undef check_envopt
1552# undef need_argument
1553# undef is_option_with_arg
1554# undef is_option_with_optarg
1556}
1557
1558static long
1559proc_options(long argc, char **argv, ruby_cmdline_options_t *opt, int envopt)
1560{
1561 long n, argc0 = argc;
1562 const char *s;
1563 int warning = opt->warning;
1564
1565 if (argc <= 0 || !argv)
1566 return 0;
1567
1568 for (argc--, argv++; argc > 0; argc--, argv++) {
1569 const char *const arg = argv[0];
1570 if (!arg || arg[0] != '-' || !arg[1])
1571 break;
1572
1573 s = arg + 1;
1574 reswitch:
1575 switch (*s) {
1576 case 'a':
1577 if (envopt) goto noenvopt;
1578 opt->do_split = TRUE;
1579 s++;
1580 goto reswitch;
1581
1582 case 'p':
1583 if (envopt) goto noenvopt;
1584 opt->do_print = TRUE;
1585 /* through */
1586 case 'n':
1587 if (envopt) goto noenvopt;
1588 opt->do_loop = TRUE;
1589 s++;
1590 goto reswitch;
1591
1592 case 'd':
1593 ruby_debug = Qtrue;
1595 s++;
1596 goto reswitch;
1597
1598 case 'y':
1599 if (envopt) goto noenvopt;
1600 opt->dump |= DUMP_BIT(yydebug);
1601 s++;
1602 goto reswitch;
1603
1604 case 'v':
1605 if (opt->verbose) {
1606 s++;
1607 goto reswitch;
1608 }
1609 opt->dump |= DUMP_BIT(version_v);
1610 opt->verbose = 1;
1611 case 'w':
1612 if (!opt->warning) {
1613 warning = 1;
1615 }
1616 FEATURE_SET(opt->warn, RB_WARN_CATEGORY_DEFAULT_BITS);
1617 s++;
1618 goto reswitch;
1619
1620 case 'W':
1621 if (!(s = proc_W_option(opt, s, &warning))) break;
1622 goto reswitch;
1623
1624 case 'c':
1625 if (envopt) goto noenvopt;
1626 opt->dump |= DUMP_BIT(syntax);
1627 s++;
1628 goto reswitch;
1629
1630 case 's':
1631 if (envopt) goto noenvopt;
1632 forbid_setid("-s");
1633 if (!opt->sflag) opt->sflag = 1;
1634 s++;
1635 goto reswitch;
1636
1637 case 'h':
1638 if (envopt) goto noenvopt;
1639 opt->dump |= DUMP_BIT(usage);
1640 goto switch_end;
1641
1642 case 'l':
1643 if (envopt) goto noenvopt;
1644 opt->do_line = TRUE;
1645 rb_output_rs = rb_rs;
1646 s++;
1647 goto reswitch;
1648
1649 case 'S':
1650 if (envopt) goto noenvopt;
1651 forbid_setid("-S");
1652 opt->do_search = TRUE;
1653 s++;
1654 goto reswitch;
1655
1656 case 'e':
1657 if (envopt) goto noenvopt;
1658 if (!(n = proc_e_option(opt, s, argc, argv))) break;
1659 --n;
1660 argc -= n;
1661 argv += n;
1662 break;
1663
1664 case 'r':
1665 forbid_setid("-r");
1666 if (*++s) {
1667 add_modules(&opt->req_list, s);
1668 }
1669 else if (argc > 1) {
1670 add_modules(&opt->req_list, argv[1]);
1671 argc--, argv++;
1672 }
1673 break;
1674
1675 case 'i':
1676 if (envopt) goto noenvopt;
1677 forbid_setid("-i");
1678 ruby_set_inplace_mode(s + 1);
1679 break;
1680
1681 case 'x':
1682 if (envopt) goto noenvopt;
1683 forbid_setid("-x");
1684 opt->xflag = TRUE;
1685 s++;
1686 if (*s && chdir(s) < 0) {
1687 rb_fatal("Can't chdir to %s", s);
1688 }
1689 break;
1690
1691 case 'C':
1692 case 'X':
1693 if (envopt) goto noenvopt;
1694 if (!*++s && (!--argc || !(s = *++argv) || !*s)) {
1695 rb_fatal("Can't chdir");
1696 }
1697 if (chdir(s) < 0) {
1698 rb_fatal("Can't chdir to %s", s);
1699 }
1700 break;
1701
1702 case 'F':
1703 if (envopt) goto noenvopt;
1704 if (*++s) {
1705 rb_fs = rb_reg_new(s, strlen(s), 0);
1706 }
1707 break;
1708
1709 case 'E':
1710 if (!*++s && (!--argc || !(s = *++argv))) {
1711 rb_raise(rb_eRuntimeError, "missing argument for -E");
1712 }
1713 proc_encoding_option(opt, s, "-E");
1714 break;
1715
1716 case 'U':
1717 set_internal_encoding_once(opt, "UTF-8", 0);
1718 ++s;
1719 goto reswitch;
1720
1721 case 'K':
1722 if (!(s = proc_K_option(opt, s))) break;
1723 goto reswitch;
1724
1725 case 'I':
1726 forbid_setid("-I");
1727 if (*++s)
1728 ruby_incpush_expand(s);
1729 else if (argc > 1) {
1730 ruby_incpush_expand(argv[1]);
1731 argc--, argv++;
1732 }
1733 break;
1734
1735 case '0':
1736 if (envopt) goto noenvopt;
1737 if (!(s = proc_0_option(opt, s))) break;
1738 goto reswitch;
1739
1740 case '-':
1741 if (!s[1] || (s[1] == '\r' && !s[2])) {
1742 argc--, argv++;
1743 goto switch_end;
1744 }
1745 s++;
1746
1747 if (!(n = proc_long_options(opt, s, argc, argv, envopt))) goto switch_end;
1748 --n;
1749 argc -= n;
1750 argv += n;
1751 break;
1752
1753 case '\r':
1754 if (!s[1])
1755 break;
1756
1757 default: {
1758 rb_encoding *enc = IF_UTF8_PATH(rb_utf8_encoding(), rb_locale_encoding());
1759 const char *e = s + strlen(s);
1760 int r = rb_enc_precise_mbclen(s, e, enc);
1761 unsigned int c = (unsigned char)*s;
1762 if (r > 0) {
1763 c = rb_enc_mbc_to_codepoint(s, e, enc);
1764 if (ONIGENC_IS_CODE_GRAPH(enc, c) ||
1765 ((s = ruby_escaped_char(c)) != 0 &&
1766 (r = (int)strlen(s), /* 3 at most */ 1))) {
1768 "invalid option -%.*s (-h will show valid options)",
1769 r, s);
1770 }
1771 }
1772 rb_raise(rb_eRuntimeError,
1773 "invalid option -\\x%.2x (-h will show valid options)",
1774 c);
1775
1776 goto switch_end;
1777 }
1778
1779 noenvopt:
1780 /* "EIdvwWrKU" only */
1781 rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: -%c", *s);
1782 break;
1783
1784 case 0:
1785 break;
1786 }
1787 }
1788
1789 switch_end:
1790 if (warning) opt->warning = warning;
1791 return argc0 - argc;
1792}
1793
1794VALUE rb_define_gem_modules(VALUE, VALUE);
1795void Init_builtin_features(void);
1796
1797static void
1798ruby_init_prelude(void)
1799{
1800 Init_builtin_features();
1801}
1802
1803void rb_call_builtin_inits(void);
1804
1805// Initialize extra optional exts linked statically.
1806// This empty definition will be replaced with the actual strong symbol by linker.
1807#if RBIMPL_HAS_ATTRIBUTE(weak)
1808__attribute__((weak))
1809#endif
1810void
1811Init_extra_exts(void)
1812{
1813}
1814
1815static void
1816ruby_opt_init(ruby_cmdline_options_t *opt)
1817{
1818 rb_warning_category_update(opt->warn.mask, opt->warn.set);
1819
1820 if (opt->dump & dump_exit_bits) return;
1821
1822 Init_ext(); /* load statically linked extensions before rubygems */
1823 Init_extra_exts();
1824
1825 GET_VM()->running = 0;
1826 rb_call_builtin_inits();
1827 GET_VM()->running = 1;
1828 memset(ruby_vm_redefined_flag, 0, sizeof(ruby_vm_redefined_flag));
1829
1830 // Register JIT-optimized builtin CMEs before the prelude, which may
1831 // redefine core methods (e.g. Kernel.prepend via bundler/setup).
1832#if USE_YJIT
1833 rb_yjit_init_builtin_cmes();
1834#endif
1835#if USE_ZJIT
1836 extern void rb_zjit_init_builtin_cmes(void);
1837 rb_zjit_init_builtin_cmes();
1838#endif
1839
1844 if (rb_box_available()) {
1845 rb_initialize_mandatory_boxes();
1846 }
1847
1848 rb_box_init_done();
1849
1850 if (FEATURE_SET_P(opt->features, gems)) {
1851 rb_box_gem_flags_t gem_flags = {
1852 .gem = FEATURE_SET_P(opt->features, gems),
1853 .error_highlight = opt->features.set & FEATURE_BIT(error_highlight),
1854 .did_you_mean = opt->features.set & FEATURE_BIT(did_you_mean),
1855 .syntax_suggest = opt->features.set & FEATURE_BIT(syntax_suggest)
1856 };
1857
1858 if (rb_box_available()) {
1859 rb_vm_call_cfunc_in_box(Qnil, rb_define_gem_modules, (VALUE)&gem_flags, Qnil,
1860 rb_str_new_cstr("before_prelude.root.dummy"), rb_root_box());
1861 rb_vm_call_cfunc_in_box(Qnil, rb_define_gem_modules, (VALUE)&gem_flags, Qnil,
1862 rb_str_new_cstr("before_prelude.main.dummy"), rb_main_box());
1863
1864 rb_box_set_gem_flags(&gem_flags);
1865 }
1866 else {
1867 rb_define_gem_modules((VALUE)&gem_flags, Qnil);
1868 }
1869 }
1870
1871 // The root/main boxes load gem_prelude here.
1872 // User boxes will load it in those #initialize instead.
1873 ruby_init_prelude();
1874
1875 // Enable JITs after ruby_init_prelude() to avoid JITing prelude code.
1876#if USE_YJIT
1877 rb_yjit_init(opt->yjit);
1878#endif
1879#if USE_ZJIT
1880 extern void rb_zjit_init(bool);
1881 rb_zjit_init(opt->zjit);
1882#endif
1883
1884 ruby_set_script_name(opt->script_name);
1885 if (rb_box_available()) {
1886 require_libraries_in_main_box(&opt->req_list);
1887 }
1888 else {
1889 require_libraries(&opt->req_list);
1890 }
1891}
1892
1893static int
1894opt_enc_index(VALUE enc_name)
1895{
1896 const char *s = RSTRING_PTR(enc_name);
1897 int i = rb_enc_find_index(s);
1898
1899 if (i < 0) {
1900 rb_raise(rb_eRuntimeError, "unknown encoding name - %s", s);
1901 }
1902 else if (rb_enc_dummy_p(rb_enc_from_index(i))) {
1903 rb_raise(rb_eRuntimeError, "dummy encoding is not acceptable - %s ", s);
1904 }
1905 return i;
1906}
1907
1908#define rb_progname (GET_VM()->progname)
1909#define rb_orig_progname (GET_VM()->orig_progname)
1911VALUE rb_e_script;
1912
1913static VALUE
1914false_value(ID _x, VALUE *_y)
1915{
1916 return Qfalse;
1917}
1918
1919static VALUE
1920true_value(ID _x, VALUE *_y)
1921{
1922 return Qtrue;
1923}
1924
1925#define rb_define_readonly_boolean(name, val) \
1926 rb_define_virtual_variable((name), (val) ? true_value : false_value, 0)
1927
1928static VALUE
1929uscore_get(void)
1930{
1931 VALUE line;
1932
1933 line = rb_lastline_get();
1934 if (!RB_TYPE_P(line, T_STRING)) {
1935 rb_raise(rb_eTypeError, "$_ value need to be String (%s given)",
1936 NIL_P(line) ? "nil" : rb_obj_classname(line));
1937 }
1938 return line;
1939}
1940
1941/*
1942 * call-seq:
1943 * sub(pattern, replacement) -> $_
1944 * sub(pattern) {|...| block } -> $_
1945 *
1946 * Equivalent to <code>$_.sub(<i>args</i>)</code>, except that
1947 * <code>$_</code> will be updated if substitution occurs.
1948 * Available only when -p/-n command line option specified.
1949 */
1950
1951static VALUE
1952rb_f_sub(int argc, VALUE *argv, VALUE _)
1953{
1954 VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("sub"), argc, argv);
1955 rb_lastline_set(str);
1956 return str;
1957}
1958
1959/*
1960 * call-seq:
1961 * gsub(pattern, replacement) -> $_
1962 * gsub(pattern) {|...| block } -> $_
1963 *
1964 * Equivalent to <code>$_.gsub...</code>, except that <code>$_</code>
1965 * will be updated if substitution occurs.
1966 * Available only when -p/-n command line option specified.
1967 *
1968 */
1969
1970static VALUE
1971rb_f_gsub(int argc, VALUE *argv, VALUE _)
1972{
1973 VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("gsub"), argc, argv);
1974 rb_lastline_set(str);
1975 return str;
1976}
1977
1978/*
1979 * call-seq:
1980 * chop -> $_
1981 *
1982 * Equivalent to <code>($_.dup).chop!</code>, except <code>nil</code>
1983 * is never returned. See String#chop!.
1984 * Available only when -p/-n command line option specified.
1985 *
1986 */
1987
1988static VALUE
1989rb_f_chop(VALUE _)
1990{
1991 VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("chop"), 0, 0);
1992 rb_lastline_set(str);
1993 return str;
1994}
1995
1996
1997/*
1998 * call-seq:
1999 * chomp -> $_
2000 * chomp(string) -> $_
2001 *
2002 * Equivalent to <code>$_ = $_.chomp(<em>string</em>)</code>. See
2003 * String#chomp.
2004 * Available only when -p/-n command line option specified.
2005 *
2006 */
2007
2008static VALUE
2009rb_f_chomp(int argc, VALUE *argv, VALUE _)
2010{
2011 VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("chomp"), argc, argv);
2012 rb_lastline_set(str);
2013 return str;
2014}
2015
2016static void
2017setup_pager_env(void)
2018{
2019 if (!getenv("LESS")) {
2020 // Output "raw" control characters, and move per sections.
2021 ruby_setenv("LESS", "-R +/^[A-Z].*");
2022 }
2023}
2024
2025#ifdef _WIN32
2026static int
2027tty_enabled(void)
2028{
2029 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2030 DWORD m;
2031 if (!GetConsoleMode(h, &m)) return 0;
2032# ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2033# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2034# endif
2035 if (!(m & ENABLE_VIRTUAL_TERMINAL_PROCESSING)) return 0;
2036 return 1;
2037}
2038#elif !defined(HAVE_WORKING_FORK)
2039# define tty_enabled() 0
2040#endif
2041
2042static VALUE
2043copy_str(VALUE str, rb_encoding *enc, bool intern)
2044{
2045 if (!intern) {
2046 if (rb_enc_str_coderange_scan(str, enc) == ENC_CODERANGE_BROKEN)
2047 return 0;
2048 return rb_enc_associate(rb_str_dup(str), enc);
2049 }
2050 return rb_enc_interned_str(RSTRING_PTR(str), RSTRING_LEN(str), enc);
2051}
2052
2053#if USE_YJIT || USE_ZJIT
2054// Check that an environment variable is set to a truthy value
2055static bool
2056env_var_truthy(const char *name)
2057{
2058 const char *value = getenv(name);
2059
2060 if (!value)
2061 return false;
2062 if (strcmp(value, "1") == 0)
2063 return true;
2064 if (strcmp(value, "true") == 0)
2065 return true;
2066 if (strcmp(value, "yes") == 0)
2067 return true;
2068
2069 return false;
2070}
2071#endif
2072
2073rb_pid_t rb_fork_ruby(int *status);
2074
2075static void
2076show_help(const char *progname, int help)
2077{
2078 int tty = isatty(1);
2079 int columns = 0;
2080 if (help && tty) {
2081 const char *pager_env = getenv("RUBY_PAGER");
2082 if (!pager_env) pager_env = getenv("PAGER");
2083 if (pager_env && *pager_env && isatty(0)) {
2084 const char *columns_env = getenv("COLUMNS");
2085 if (columns_env) columns = atoi(columns_env);
2086 VALUE pager = rb_str_new_cstr(pager_env);
2087#ifdef HAVE_WORKING_FORK
2088 int fds[2];
2089 if (rb_pipe(fds) == 0) {
2090 rb_pid_t pid = rb_fork_ruby(NULL);
2091 if (pid > 0) {
2092 /* exec PAGER with reading from child */
2093 dup2(fds[0], 0);
2094 }
2095 else if (pid == 0) {
2096 /* send the help message to the parent PAGER */
2097 dup2(fds[1], 1);
2098 dup2(fds[1], 2);
2099 }
2100 close(fds[0]);
2101 close(fds[1]);
2102 if (pid > 0) {
2103 setup_pager_env();
2104 rb_f_exec(1, &pager);
2105 kill(SIGTERM, pid);
2106 rb_waitpid(pid, 0, 0);
2107 }
2108 }
2109#else
2110 setup_pager_env();
2111 VALUE port = rb_io_popen(pager, rb_str_new_lit("w"), Qnil, Qnil);
2112 if (!NIL_P(port)) {
2113 int oldout = dup(1);
2114 int olderr = dup(2);
2115 int fd = RFILE(port)->fptr->fd;
2116 tty = tty_enabled();
2117 dup2(fd, 1);
2118 dup2(fd, 2);
2119 usage(progname, 1, tty, columns);
2120 fflush(stdout);
2121 dup2(oldout, 1);
2122 dup2(olderr, 2);
2123 rb_io_close(port);
2124 return;
2125 }
2126#endif
2127 }
2128 }
2129 usage(progname, help, tty, columns);
2130}
2131
2132static VALUE
2133process_script(ruby_cmdline_options_t *opt)
2134{
2135 rb_ast_t *ast;
2136 VALUE ast_value;
2137 VALUE parser = rb_parser_new();
2138 const unsigned int dump = opt->dump;
2139
2140 if (dump & DUMP_BIT(yydebug)) {
2141 rb_parser_set_yydebug(parser, Qtrue);
2142 }
2143
2144 if ((dump & dump_exit_bits) && (dump & DUMP_BIT(opt_error_tolerant))) {
2145 rb_parser_error_tolerant(parser);
2146 }
2147
2148 if (opt->e_script) {
2149 VALUE progname = rb_progname;
2150 rb_parser_set_context(parser, 0, TRUE);
2151
2152 ruby_opt_init(opt);
2153 ruby_set_script_name(progname);
2154 rb_parser_set_options(parser, opt->do_print, opt->do_loop,
2155 opt->do_line, opt->do_split);
2156 ast_value = rb_parser_compile_string(parser, opt->script, opt->e_script, 1);
2157 }
2158 else {
2159 VALUE f;
2160 int xflag = opt->xflag;
2161 f = open_load_file(opt->script_name, &xflag);
2162 opt->xflag = xflag != 0;
2163 rb_parser_set_context(parser, 0, f == rb_stdin);
2164 ast_value = load_file(parser, opt->script_name, f, 1, opt);
2165 }
2166 ast = rb_ruby_ast_data_get(ast_value);
2167 if (!ast->body.root) {
2168 rb_ast_dispose(ast);
2169 return Qnil;
2170 }
2171 return ast_value;
2172}
2173
2174static uint8_t
2175prism_script_command_line(ruby_cmdline_options_t *opt)
2176{
2177 uint8_t command_line = 0;
2178 if (opt->do_split) command_line |= PM_OPTIONS_COMMAND_LINE_A;
2179 if (opt->do_line) command_line |= PM_OPTIONS_COMMAND_LINE_L;
2180 if (opt->do_loop) command_line |= PM_OPTIONS_COMMAND_LINE_N;
2181 if (opt->do_print) command_line |= PM_OPTIONS_COMMAND_LINE_P;
2182 if (opt->xflag) command_line |= PM_OPTIONS_COMMAND_LINE_X;
2183 return command_line;
2184}
2185
2186static void
2187prism_script_shebang_callback(pm_options_t *options, const uint8_t *source, size_t length, void *data)
2188{
2190 opt->warning = 0;
2191
2192 char *switches = malloc(length + 1);
2193 memcpy(switches, source, length);
2194 switches[length] = '\0';
2195
2196 int no_src_enc = !opt->src.enc.name;
2197 int no_ext_enc = !opt->ext.enc.name;
2198 int no_int_enc = !opt->intern.enc.name;
2199
2200 moreswitches(switches, opt, 0);
2201 free(switches);
2202
2203 pm_options_command_line_set(options, prism_script_command_line(opt));
2204
2205 if (no_src_enc && opt->src.enc.name) {
2206 opt->src.enc.index = opt_enc_index(opt->src.enc.name);
2207 pm_options_encoding_set(options, StringValueCStr(opt->ext.enc.name));
2208 }
2209 if (no_ext_enc && opt->ext.enc.name) {
2210 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2211 }
2212 if (no_int_enc && opt->intern.enc.name) {
2213 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
2214 }
2215}
2216
2221static void
2222prism_script(ruby_cmdline_options_t *opt, pm_parse_result_t *result)
2223{
2224 pm_parse_result_init(result);
2225 pm_options_t *options = result->options;
2226 pm_options_main_script_set(options, true);
2227
2228 const bool read_stdin = (strcmp(opt->script, "-") == 0);
2229
2230 if (read_stdin) {
2231 pm_options_encoding_set(options, rb_enc_name(IF_UTF8_PATH(rb_utf8_encoding(), rb_locale_encoding())));
2232 }
2233 if (opt->src.enc.name != 0) {
2234 pm_options_encoding_set(options, StringValueCStr(opt->src.enc.name));
2235 }
2236
2237 uint8_t command_line = prism_script_command_line(opt);
2238 VALUE error;
2239
2240 if (read_stdin) {
2241 pm_options_command_line_set(options, command_line);
2242 pm_options_filepath_set(options, "-");
2243 pm_options_shebang_callback_set(options, prism_script_shebang_callback, (void *) opt);
2244
2245 ruby_opt_init(opt);
2246 error = pm_parse_stdin(result);
2247
2248 // If we found an __END__ marker, then we're going to define a global
2249 // DATA constant that is a file object that can be read to read the
2250 // contents after the marker.
2251 if (NIL_P(error) && pm_parser_data_loc(result->parser)->length != 0) {
2253 }
2254 }
2255 else if (opt->e_script) {
2256 command_line = (uint8_t) ((command_line | PM_OPTIONS_COMMAND_LINE_E) & ~PM_OPTIONS_COMMAND_LINE_X);
2257 pm_options_command_line_set(options, command_line);
2258
2259 ruby_opt_init(opt);
2260 result->node.coverage_enabled = 0;
2261 error = pm_parse_string(result, opt->e_script, rb_str_new2("-e"), NULL);
2262 }
2263 else {
2264 VALUE script_name = rb_str_encode_ospath(opt->script_name);
2265
2266 pm_options_command_line_set(options, command_line);
2267 pm_options_shebang_callback_set(options, prism_script_shebang_callback, (void *) opt);
2268
2269 error = pm_load_file(result, script_name, true);
2270
2271 // If reading the file did not error, at that point we load the command
2272 // line options. We do it in this order so that if the main script fails
2273 // to load, it doesn't require files required by -r.
2274 if (NIL_P(error)) {
2275 ruby_opt_init(opt);
2276 error = pm_parse_file(result, opt->script_name, NULL);
2277 }
2278
2279 // Check if (after requiring all of the files through -r flags) we have
2280 // coverage enabled and need to enable coverage on the main script.
2281 if (RTEST(rb_get_coverages())) {
2282 result->node.coverage_enabled = 1;
2283 }
2284
2285 // If we found an __END__ marker, then we're going to define a global
2286 // DATA constant that is a file object that can be read to read the
2287 // contents after the marker.
2288 if (NIL_P(error) && pm_parser_data_loc(result->parser)->length != 0) {
2289 int xflag = opt->xflag;
2290 VALUE file = open_load_file(script_name, &xflag);
2291
2292 const pm_parser_t *parser = result->parser;
2293 const pm_location_t *data_loc = pm_parser_data_loc(parser);
2294 const uint8_t *start = pm_parser_start(parser);
2295 const uint8_t *end = pm_parser_end(parser);
2296 uint32_t offset = data_loc->start + 7;
2297
2298 if ((start + offset < end) && start[offset] == '\r') offset++;
2299 if ((start + offset < end) && start[offset] == '\n') offset++;
2300
2301 rb_funcall(file, rb_intern_const("seek"), 2, UINT2NUM(offset), INT2FIX(SEEK_SET));
2302 rb_define_global_const("DATA", file);
2303 }
2304 }
2305
2306 if (!NIL_P(error)) {
2307 pm_parse_result_free(result);
2308 rb_exc_raise(error);
2309 }
2310}
2311
2312static VALUE
2313prism_dump_tree(pm_parse_result_t *result)
2314{
2315 pm_buffer_t *output_buffer = pm_buffer_new();
2316
2317 pm_prettyprint(output_buffer, result->parser, result->node.ast_node);
2318 VALUE tree = rb_str_new(pm_buffer_value(output_buffer), pm_buffer_length(output_buffer));
2319 pm_buffer_free(output_buffer);
2320 return tree;
2321}
2322
2323static void
2324process_options_global_setup(const ruby_cmdline_options_t *opt, const rb_iseq_t *iseq)
2325{
2326 if (OPT_BACKTRACE_LENGTH_LIMIT_VALID_P(opt)) {
2327 rb_backtrace_length_limit = opt->backtrace_length_limit;
2328 }
2329
2330 if (opt->do_loop) {
2331 rb_define_global_function("sub", rb_f_sub, -1);
2332 rb_define_global_function("gsub", rb_f_gsub, -1);
2333 rb_define_global_function("chop", rb_f_chop, 0);
2334 rb_define_global_function("chomp", rb_f_chomp, -1);
2335 }
2336
2337 rb_define_readonly_boolean("$-p", opt->do_print);
2338 rb_define_readonly_boolean("$-l", opt->do_line);
2339 rb_define_readonly_boolean("$-a", opt->do_split);
2340
2341 rb_gvar_ractor_local("$-p");
2342 rb_gvar_ractor_local("$-l");
2343 rb_gvar_ractor_local("$-a");
2344
2345 if ((rb_e_script = opt->e_script) != 0) {
2346 rb_str_freeze(rb_e_script);
2347 rb_vm_register_global_object(opt->e_script);
2348 }
2349
2350 rb_execution_context_t *ec = GET_EC();
2351 VALUE script = (opt->e_script ? opt->e_script : Qnil);
2352 rb_exec_event_hook_script_compiled(ec, iseq, script);
2353}
2354
2355static bool
2356has_dir_sep(const char *path)
2357{
2358 if (strchr(path, '/')) return true;
2359#ifdef _WIN32
2360 if (strchr(path, '\\')) return true;
2361#endif
2362 return false;
2363}
2364
2365static VALUE
2366process_options(int argc, char **argv, ruby_cmdline_options_t *opt)
2367{
2368 VALUE ast_value = Qnil;
2369 struct {
2370 rb_ast_t *ast;
2371 pm_parse_result_t prism;
2372 } result = {0};
2373#define dispose_result() \
2374 (result.ast ? rb_ast_dispose(result.ast) : pm_parse_result_free(&result.prism))
2375
2376 const rb_iseq_t *iseq;
2377 rb_encoding *enc, *lenc;
2378#if UTF8_PATH
2379 rb_encoding *ienc = 0;
2380 rb_encoding *const uenc = rb_utf8_encoding();
2381#endif
2382 const char *s;
2383 char fbuf[MAXPATHLEN];
2384 int i = (int)proc_options(argc, argv, opt, 0);
2385 unsigned int dump = opt->dump & dump_exit_bits;
2386 const rb_box_t *box = rb_root_box();
2387 const long loaded_before_enc = RARRAY_LEN(box->loaded_features);
2388
2389 if (opt->dump & (DUMP_BIT(usage)|DUMP_BIT(help))) {
2390 const char *const progname =
2391 (argc > 0 && argv && argv[0] ? argv[0] :
2392 origarg.argc > 0 && origarg.argv && origarg.argv[0] ? origarg.argv[0] :
2393 ruby_engine);
2394 show_help(progname, (opt->dump & DUMP_BIT(help)));
2395 return Qtrue;
2396 }
2397
2398 argc -= i;
2399 argv += i;
2400
2401 if (FEATURE_SET_P(opt->features, rubyopt) && (s = getenv("RUBYOPT"))) {
2402 moreswitches(s, opt, 1);
2403 }
2404
2405 if (opt->src.enc.name)
2406 /* cannot set deprecated category, as enabling deprecation warnings based on flags
2407 * has not happened yet.
2408 */
2409 rb_warning("-K is specified; it is for 1.8 compatibility and may cause odd behavior");
2410
2411 if (!(FEATURE_SET_BITS(opt->features) & feature_jit_mask)) {
2412#if USE_YJIT
2413 if (!FEATURE_USED_P(opt->features, yjit) && env_var_truthy("RUBY_YJIT_ENABLE")) {
2414 FEATURE_SET(opt->features, FEATURE_BIT(yjit));
2415 }
2416#endif
2417#if USE_ZJIT
2418 if (!FEATURE_USED_P(opt->features, zjit) && env_var_truthy("RUBY_ZJIT_ENABLE")) {
2419 FEATURE_SET(opt->features, FEATURE_BIT(zjit));
2420
2421 // When the --zjit flag is specified, we would have call setup_zjit_options(""),
2422 // which would have called rb_zjit_prepare_options() internally. This ensures we
2423 // go through the same set up but with less overhead than setup_zjit_options("").
2424 extern void rb_zjit_prepare_options();
2425 rb_zjit_prepare_options();
2426 }
2427#endif
2428 }
2429 if (MULTI_BITS_P(FEATURE_SET_BITS(opt->features) & feature_jit_mask)) {
2430 rb_warn("Only one JIT can be enabled at the same time. Exiting");
2431 return Qfalse;
2432 }
2433
2434#if USE_YJIT
2435 if (FEATURE_SET_P(opt->features, yjit)) {
2436 bool rb_yjit_option_disable(void);
2437 opt->yjit = !rb_yjit_option_disable(); // set opt->yjit for Init_ruby_description() and calling rb_yjit_init()
2438 }
2439#endif
2440#if USE_ZJIT
2441 if (FEATURE_SET_P(opt->features, zjit)) {
2442 bool rb_zjit_option_enable(void);
2443 opt->zjit = rb_zjit_option_enable(); // set opt->zjit for Init_ruby_description() and calling rb_zjit_init()
2444 }
2445#endif
2446
2447 ruby_mn_threads_params();
2448 Init_ruby_description(opt);
2449
2450 if (opt->dump & (DUMP_BIT(version) | DUMP_BIT(version_v))) {
2452 if (opt->dump & DUMP_BIT(version)) return Qtrue;
2453 }
2454 if (opt->dump & DUMP_BIT(copyright)) {
2456 return Qtrue;
2457 }
2458
2459 if (!opt->e_script) {
2460 if (argc <= 0) { /* no more args */
2461 if (opt->verbose)
2462 return Qtrue;
2463 opt->script = "-";
2464 }
2465 else {
2466 opt->script = argv[0];
2467 if (!opt->script || opt->script[0] == '\0') {
2468 opt->script = "-";
2469 }
2470 else if (opt->do_search && !has_dir_sep(opt->script)) {
2471 const char *path = getenv("RUBYPATH");
2472
2473 opt->script = 0;
2474 if (path) {
2475 opt->script = dln_find_file_r(argv[0], path, fbuf, sizeof(fbuf));
2476 }
2477 if (!opt->script) {
2478 opt->script = dln_find_file_r(argv[0], getenv(PATH_ENV), fbuf, sizeof(fbuf));
2479 }
2480 if (!opt->script)
2481 opt->script = argv[0];
2482 }
2483 argc--;
2484 argv++;
2485 }
2486 if (opt->script[0] == '-' && !opt->script[1]) {
2487 forbid_setid("program input from stdin");
2488 }
2489 }
2490
2491 opt->script_name = rb_str_new_cstr(opt->script);
2492 opt->script = RSTRING_PTR(opt->script_name);
2493
2494#ifdef _WIN32
2495 translit_char_bin(RSTRING_PTR(opt->script_name), '\\', '/');
2496#endif
2497
2498 ruby_gc_set_params();
2500
2501 Init_enc();
2502 lenc = rb_locale_encoding();
2503 rb_enc_associate(rb_progname, lenc);
2504 rb_obj_freeze(rb_progname);
2505 if (opt->ext.enc.name != 0) {
2506 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2507 }
2508 if (opt->intern.enc.name != 0) {
2509 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
2510 }
2511 if (opt->src.enc.name != 0) {
2512 opt->src.enc.index = opt_enc_index(opt->src.enc.name);
2513 src_encoding_index = opt->src.enc.index;
2514 }
2515 if (opt->ext.enc.index >= 0) {
2516 enc = rb_enc_from_index(opt->ext.enc.index);
2517 }
2518 else {
2519 enc = IF_UTF8_PATH(uenc, lenc);
2520 }
2521 rb_enc_set_default_external(rb_enc_from_encoding(enc));
2522 if (opt->intern.enc.index >= 0) {
2523 enc = rb_enc_from_index(opt->intern.enc.index);
2524 rb_enc_set_default_internal(rb_enc_from_encoding(enc));
2525 opt->intern.enc.index = -1;
2526#if UTF8_PATH
2527 ienc = enc;
2528#endif
2529 }
2530 rb_enc_associate(opt->script_name, IF_UTF8_PATH(uenc, lenc));
2531#if UTF8_PATH
2532 if (uenc != lenc) {
2533 opt->script_name = str_conv_enc(opt->script_name, uenc, lenc);
2534 opt->script = RSTRING_PTR(opt->script_name);
2535 }
2536#endif
2537 rb_obj_freeze(opt->script_name);
2538 if (IF_UTF8_PATH(uenc != lenc, 1)) {
2539 long i;
2540 VALUE load_path = box->load_path;
2541 const ID id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK;
2542 int modifiable = FALSE;
2543
2544 rb_get_expanded_load_path(NULL);
2545 for (i = 0; i < RARRAY_LEN(load_path); ++i) {
2546 VALUE path = RARRAY_AREF(load_path, i);
2547 int mark = rb_attr_get(path, id_initial_load_path_mark) == path;
2548#if UTF8_PATH
2549 VALUE newpath = rb_str_conv_enc(path, uenc, lenc);
2550 if (newpath == path) continue;
2551 path = newpath;
2552#else
2553 if (!(path = copy_str(path, lenc, !mark))) continue;
2554#endif
2555 if (mark) rb_ivar_set(path, id_initial_load_path_mark, path);
2556 if (!modifiable) {
2557 rb_ary_modify(load_path);
2558 modifiable = TRUE;
2559 }
2560 RARRAY_ASET(load_path, i, path);
2561 }
2562 if (modifiable) {
2563 rb_ary_replace(box->load_path_snapshot, load_path);
2564 }
2565 }
2566 {
2567 VALUE loaded_features = box->loaded_features;
2568 bool modified = false;
2569 for (long i = loaded_before_enc; i < RARRAY_LEN(loaded_features); ++i) {
2570 VALUE path = RARRAY_AREF(loaded_features, i);
2571 if (!(path = copy_str(path, IF_UTF8_PATH(uenc, lenc), true))) continue;
2572 if (!modified) {
2573 rb_ary_modify(loaded_features);
2574 modified = true;
2575 }
2576 RARRAY_ASET(loaded_features, i, path);
2577 }
2578 if (modified) {
2579 rb_ary_replace(box->loaded_features_snapshot, loaded_features);
2580 }
2581 }
2582
2583 if (opt->features.mask & COMPILATION_FEATURES) {
2584 VALUE option = rb_hash_new();
2585#define SET_COMPILE_OPTION(h, o, name) \
2586 rb_hash_aset((h), ID2SYM(rb_intern_const(#name)), \
2587 RBOOL(FEATURE_SET_P(o->features, name)))
2588
2589 if (FEATURE_SET_P(opt->features, frozen_string_literal_set)) {
2590 SET_COMPILE_OPTION(option, opt, frozen_string_literal);
2591 }
2592 SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal);
2593 rb_funcallv(rb_cISeq, rb_intern_const("compile_option="), 1, &option);
2594#undef SET_COMPILE_OPTION
2595 }
2596 ruby_set_argv(argc, argv);
2597 opt->sflag = process_sflag(opt->sflag);
2598
2599 if (opt->e_script) {
2600 rb_encoding *eenc;
2601 if (opt->src.enc.index >= 0) {
2602 eenc = rb_enc_from_index(opt->src.enc.index);
2603 }
2604 else {
2605 eenc = lenc;
2606#if UTF8_PATH
2607 if (ienc) eenc = ienc;
2608#endif
2609 }
2610#if UTF8_PATH
2611 if (eenc != uenc) {
2612 opt->e_script = str_conv_enc(opt->e_script, uenc, eenc);
2613 }
2614#endif
2615 rb_enc_associate(opt->e_script, eenc);
2616 }
2617
2618 if (!rb_ruby_prism_p()) {
2619 ast_value = process_script(opt);
2620 if (!(result.ast = rb_ruby_ast_data_get(ast_value))) return Qfalse;
2621 }
2622 else {
2623 prism_script(opt, &result.prism);
2624 }
2625 ruby_set_script_name(opt->script_name);
2626 if ((dump & DUMP_BIT(yydebug)) && !(dump &= ~DUMP_BIT(yydebug))) {
2627 dispose_result();
2628 return Qtrue;
2629 }
2630
2631 if (opt->ext.enc.index >= 0) {
2632 enc = rb_enc_from_index(opt->ext.enc.index);
2633 }
2634 else {
2635 enc = IF_UTF8_PATH(uenc, lenc);
2636 }
2637 rb_enc_set_default_external(rb_enc_from_encoding(enc));
2638 if (opt->intern.enc.index >= 0) {
2639 /* Set in the shebang line */
2640 enc = rb_enc_from_index(opt->intern.enc.index);
2641 rb_enc_set_default_internal(rb_enc_from_encoding(enc));
2642 }
2643 else if (!rb_default_internal_encoding())
2644 /* Freeze default_internal */
2645 rb_enc_set_default_internal(Qnil);
2646 rb_stdio_set_default_encoding();
2647
2648 opt->sflag = process_sflag(opt->sflag);
2649 opt->xflag = 0;
2650
2651 if (dump & DUMP_BIT(syntax)) {
2652 printf("Syntax OK\n");
2653 dump &= ~DUMP_BIT(syntax);
2654 if (!dump) {
2655 dispose_result();
2656 return Qtrue;
2657 }
2658 }
2659
2660 if (dump & DUMP_BIT(parsetree)) {
2661 VALUE tree;
2662 if (result.ast) {
2663 int comment = opt->dump & DUMP_BIT(opt_comment);
2664 tree = rb_parser_dump_tree(result.ast->body.root, comment);
2665 }
2666 else {
2667 tree = prism_dump_tree(&result.prism);
2668 }
2669 rb_io_write(rb_stdout, tree);
2670 rb_io_flush(rb_stdout);
2671 dump &= ~DUMP_BIT(parsetree);
2672 if (!dump) {
2673 dispose_result();
2674 return Qtrue;
2675 }
2676 }
2677
2678 {
2679 VALUE path = Qnil;
2680 if (!opt->e_script && strcmp(opt->script, "-")) {
2681 path = rb_realpath_internal(Qnil, opt->script_name, 1);
2682#if UTF8_PATH
2683 if (uenc != lenc) {
2684 path = str_conv_enc(path, uenc, lenc);
2685 }
2686#endif
2687 if (!ENCODING_GET(path)) { /* ASCII-8BIT */
2688 rb_enc_copy(path, opt->script_name);
2689 }
2690 }
2691
2692 rb_binding_t *toplevel_binding;
2693 GetBindingPtr(rb_const_get(rb_cObject, rb_intern("TOPLEVEL_BINDING")), toplevel_binding);
2694 const struct rb_block *base_block = toplevel_context(toplevel_binding);
2695 const rb_iseq_t *parent = vm_block_iseq(base_block);
2696 bool optimize = (opt->dump & DUMP_BIT(opt_optimize)) != 0;
2697
2698 if (!result.ast) {
2699 pm_parse_result_t *pm = &result.prism;
2700 int error_state;
2701 iseq = pm_iseq_new_main(&pm->node, opt->script_name, path, parent, optimize, &error_state);
2702
2703 pm_parse_result_free(pm);
2704
2705 if (error_state) {
2706 RUBY_ASSERT(iseq == NULL);
2707 rb_jump_tag(error_state);
2708 }
2709 }
2710 else {
2711 rb_ast_t *ast = result.ast;
2712 iseq = rb_iseq_new_main(ast_value, opt->script_name, path, parent, optimize);
2713 rb_ast_dispose(ast);
2714 }
2715 }
2716
2717 if (dump & DUMP_BIT(insns)) {
2718 rb_io_write(rb_stdout, rb_iseq_disasm((const rb_iseq_t *)iseq));
2719 rb_io_flush(rb_stdout);
2720 dump &= ~DUMP_BIT(insns);
2721 if (!dump) return Qtrue;
2722 }
2723 if (opt->dump & dump_exit_bits) return Qtrue;
2724
2725 process_options_global_setup(opt, iseq);
2726 return (VALUE)iseq;
2727}
2728
2729#ifndef DOSISH
2730static void
2731warn_cr_in_shebang(const char *str, long len)
2732{
2733 if (len > 1 && str[len-1] == '\n' && str[len-2] == '\r') {
2734 rb_warn("shebang line ending with \\r may cause problems");
2735 }
2736}
2737#else
2738#define warn_cr_in_shebang(str, len) (void)0
2739#endif
2740
2741void rb_reset_argf_lineno(long n);
2742
2744 VALUE parser;
2745 VALUE fname;
2746 int script;
2748 VALUE f;
2749};
2750
2751void rb_set_script_lines_for(VALUE vparser, VALUE path);
2752
2753static VALUE
2754load_file_internal(VALUE argp_v)
2755{
2756 struct load_file_arg *argp = (struct load_file_arg *)argp_v;
2757 VALUE parser = argp->parser;
2758 VALUE orig_fname = argp->fname;
2759 int script = argp->script;
2760 ruby_cmdline_options_t *opt = argp->opt;
2761 VALUE f = argp->f;
2762 int line_start = 1;
2763 VALUE ast_value = Qnil;
2764 rb_encoding *enc;
2765 ID set_encoding;
2766
2767 CONST_ID(set_encoding, "set_encoding");
2768 if (script) {
2769 VALUE c = 1; /* something not nil */
2770 VALUE line;
2771 char *p, *str;
2772 long len;
2773 int no_src_enc = !opt->src.enc.name;
2774 int no_ext_enc = !opt->ext.enc.name;
2775 int no_int_enc = !opt->intern.enc.name;
2776
2777 enc = rb_ascii8bit_encoding();
2778 rb_funcall(f, set_encoding, 1, rb_enc_from_encoding(enc));
2779
2780 if (opt->xflag) {
2781 line_start--;
2782 search_shebang:
2783 while (!NIL_P(line = rb_io_gets(f))) {
2784 line_start++;
2785 RSTRING_GETMEM(line, str, len);
2786 if (len > 2 && str[0] == '#' && str[1] == '!') {
2787 if (line_start == 1) warn_cr_in_shebang(str, len);
2788 if ((p = strstr(str+2, ruby_engine)) != 0) {
2789 goto start_read;
2790 }
2791 }
2792 }
2793 rb_loaderror("no Ruby script found in input");
2794 }
2795
2796 c = rb_io_getbyte(f);
2797 if (c == INT2FIX('#')) {
2798 c = rb_io_getbyte(f);
2799 if (c == INT2FIX('!') && !NIL_P(line = rb_io_gets(f))) {
2800 RSTRING_GETMEM(line, str, len);
2801 warn_cr_in_shebang(str, len);
2802 if ((p = strstr(str, ruby_engine)) == 0) {
2803 /* not ruby script, assume -x flag */
2804 goto search_shebang;
2805 }
2806
2807 start_read:
2808 str += len - 1;
2809 if (*str == '\n') *str-- = '\0';
2810 if (*str == '\r') *str-- = '\0';
2811 /* ruby_engine should not contain a space */
2812 if ((p = strstr(p, " -")) != 0) {
2813 opt->warning = 0;
2814 moreswitches(p + 1, opt, 0);
2815 }
2816
2817 /* push back shebang for pragma may exist in next line */
2818 rb_io_ungetbyte(f, rb_str_new2("!\n"));
2819 }
2820 else if (!NIL_P(c)) {
2821 rb_io_ungetbyte(f, c);
2822 }
2823 rb_io_ungetbyte(f, INT2FIX('#'));
2824 if (no_src_enc && opt->src.enc.name) {
2825 opt->src.enc.index = opt_enc_index(opt->src.enc.name);
2826 src_encoding_index = opt->src.enc.index;
2827 }
2828 if (no_ext_enc && opt->ext.enc.name) {
2829 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2830 }
2831 if (no_int_enc && opt->intern.enc.name) {
2832 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
2833 }
2834 }
2835 else if (!NIL_P(c)) {
2836 rb_io_ungetbyte(f, c);
2837 }
2838 if (NIL_P(c)) {
2839 argp->f = f = Qnil;
2840 }
2841 rb_reset_argf_lineno(0);
2842 ruby_opt_init(opt);
2843 }
2844 if (opt->src.enc.index >= 0) {
2845 enc = rb_enc_from_index(opt->src.enc.index);
2846 }
2847 else if (f == rb_stdin) {
2848 enc = IF_UTF8_PATH(rb_utf8_encoding(), rb_locale_encoding());
2849 }
2850 else {
2851 enc = rb_utf8_encoding();
2852 }
2853 rb_parser_set_options(parser, opt->do_print, opt->do_loop,
2854 opt->do_line, opt->do_split);
2855
2856 rb_set_script_lines_for(parser, orig_fname);
2857
2858 if (NIL_P(f)) {
2859 f = rb_str_new(0, 0);
2860 rb_enc_associate(f, enc);
2861 return rb_parser_compile_string_path(parser, orig_fname, f, line_start);
2862 }
2863 rb_funcall(f, set_encoding, 2, rb_enc_from_encoding(enc), rb_str_new_cstr("-"));
2864 ast_value = rb_parser_compile_file_path(parser, orig_fname, f, line_start);
2865 rb_funcall(f, set_encoding, 1, rb_parser_encoding(parser));
2866 if (script && rb_parser_end_seen_p(parser)) {
2867 /*
2868 * DATA is a File that contains the data section of the executed file.
2869 * To create a data section use <tt>__END__</tt>:
2870 *
2871 * $ cat t.rb
2872 * puts DATA.gets
2873 * __END__
2874 * hello world!
2875 *
2876 * $ ruby t.rb
2877 * hello world!
2878 */
2879 rb_define_global_const("DATA", f);
2880 argp->f = Qnil;
2881 }
2882 return ast_value;
2883}
2884
2885/* disabling O_NONBLOCK, and returns 0 on success, otherwise errno */
2886static inline int
2887disable_nonblock(int fd)
2888{
2889#if defined(HAVE_FCNTL) && defined(F_SETFL)
2890 if (fcntl(fd, F_SETFL, 0) < 0) {
2891 const int e = errno;
2892 ASSUME(e != 0);
2893# if defined ENOTSUP
2894 if (e == ENOTSUP) return 0;
2895# endif
2896# if defined B_UNSUPPORTED
2897 if (e == B_UNSUPPORTED) return 0;
2898# endif
2899 return e;
2900 }
2901#endif
2902 return 0;
2903}
2904
2905static VALUE
2906open_load_file(VALUE fname_v, int *xflag)
2907{
2908 const char *fname = (fname_v = rb_str_encode_ospath(fname_v),
2909 StringValueCStr(fname_v));
2910 long flen = RSTRING_LEN(fname_v);
2911 VALUE f;
2912 int e;
2913
2914 if (flen == 1 && fname[0] == '-') {
2915 f = rb_stdin;
2916 }
2917 else {
2918 int fd;
2919 /* open(2) may block if fname is point to FIFO and it's empty. Let's
2920 use O_NONBLOCK. */
2921 const int MODE_TO_LOAD = O_RDONLY | (
2922#if defined O_NONBLOCK && HAVE_FCNTL
2923 /* TODO: fix conflicting O_NONBLOCK in ruby/win32.h */
2924 !(O_NONBLOCK & O_ACCMODE) ? O_NONBLOCK :
2925#endif
2926#if defined O_NDELAY && HAVE_FCNTL
2927 !(O_NDELAY & O_ACCMODE) ? O_NDELAY :
2928#endif
2929 0);
2930 int mode = MODE_TO_LOAD;
2931#if defined DOSISH || defined __CYGWIN__
2932# define isdirsep(x) ((x) == '/' || (x) == '\\')
2933 {
2934 static const char exeext[] = ".exe";
2935 enum {extlen = sizeof(exeext)-1};
2936 if (flen > extlen && !isdirsep(fname[flen-extlen-1]) &&
2937 STRNCASECMP(fname+flen-extlen, exeext, extlen) == 0) {
2938 mode |= O_BINARY;
2939 *xflag = 1;
2940 }
2941 }
2942#endif
2943
2944 if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) {
2945 e = errno;
2946 if (!rb_gc_for_fd(e)) {
2947 rb_load_fail(fname_v, strerror(e));
2948 }
2949 if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) {
2950 rb_load_fail(fname_v, strerror(errno));
2951 }
2952 }
2953 rb_update_max_fd(fd);
2954
2955 if (MODE_TO_LOAD != O_RDONLY && (e = disable_nonblock(fd)) != 0) {
2956 (void)close(fd);
2957 rb_load_fail(fname_v, strerror(e));
2958 }
2959
2960 e = ruby_is_fd_loadable(fd);
2961 if (!e) {
2962 e = errno;
2963 (void)close(fd);
2964 rb_load_fail(fname_v, strerror(e));
2965 }
2966
2967 f = rb_io_fdopen(fd, mode, fname);
2968 if (e < 0) {
2969 /*
2970 We need to wait if FIFO is empty. It's FIFO's semantics.
2971 rb_thread_wait_fd() release GVL. So, it's safe.
2972 */
2974 }
2975 }
2976 return f;
2977}
2978
2979static VALUE
2980restore_load_file(VALUE arg)
2981{
2982 struct load_file_arg *argp = (struct load_file_arg *)arg;
2983 VALUE f = argp->f;
2984
2985 if (!NIL_P(f) && f != rb_stdin) {
2986 rb_io_close(f);
2987 }
2988 return Qnil;
2989}
2990
2991static VALUE
2992load_file(VALUE parser, VALUE fname, VALUE f, int script, ruby_cmdline_options_t *opt)
2993{
2994 struct load_file_arg arg;
2995 arg.parser = parser;
2996 arg.fname = fname;
2997 arg.script = script;
2998 arg.opt = opt;
2999 arg.f = f;
3000 return rb_ensure(load_file_internal, (VALUE)&arg,
3001 restore_load_file, (VALUE)&arg);
3002}
3003
3004void *
3005rb_load_file(const char *fname)
3006{
3007 VALUE fname_v = rb_str_new_cstr(fname);
3008 return rb_load_file_str(fname_v);
3009}
3010
3011void *
3013{
3014 VALUE ast_value;
3015 ast_value = rb_parser_load_file(rb_parser_new(), fname_v);
3016 return (void *)rb_ruby_ast_data_get(ast_value);
3017}
3018
3019VALUE
3020rb_parser_load_file(VALUE parser, VALUE fname_v)
3021{
3023 int xflag = 0;
3024 VALUE f = open_load_file(fname_v, &xflag);
3025 cmdline_options_init(&opt)->xflag = xflag != 0;
3026 return load_file(parser, fname_v, f, 0, &opt);
3027}
3028
3029/*
3030 * call-seq:
3031 * Process.argv0 -> frozen_string
3032 *
3033 * Returns the name of the script being executed. The value is not
3034 * affected by assigning a new value to $0.
3035 *
3036 * This method first appeared in Ruby 2.1 to serve as a global
3037 * variable free means to get the script name.
3038 */
3039
3040static VALUE
3041proc_argv0(VALUE process)
3042{
3043 return rb_orig_progname;
3044}
3045
3046static VALUE ruby_setproctitle(VALUE title);
3047
3048/*
3049 * call-seq:
3050 * Process.setproctitle(string) -> string
3051 *
3052 * Sets the process title that appears on the ps(1) command. Not
3053 * necessarily effective on all platforms. No exception will be
3054 * raised regardless of the result, nor will NotImplementedError be
3055 * raised even if the platform does not support the feature.
3056 *
3057 * Calling this method does not affect the value of $0.
3058 *
3059 * Process.setproctitle('myapp: worker #%d' % worker_id)
3060 *
3061 * This method first appeared in Ruby 2.1 to serve as a global
3062 * variable free means to change the process title.
3063 */
3064
3065static VALUE
3066proc_setproctitle(VALUE process, VALUE title)
3067{
3068 return ruby_setproctitle(title);
3069}
3070
3071static VALUE
3072ruby_setproctitle(VALUE title)
3073{
3074 const char *ptr = StringValueCStr(title);
3075 setproctitle("%.*s", RSTRING_LENINT(title), ptr);
3076 return title;
3077}
3078
3079static void
3080set_arg0(VALUE val, ID id, VALUE *_)
3081{
3082 if (origarg.argv == 0)
3083 rb_raise(rb_eRuntimeError, "$0 not initialized");
3084
3085 rb_progname = rb_str_new_frozen(ruby_setproctitle(val));
3086}
3087
3088static inline VALUE
3089external_str_new_cstr(const char *p)
3090{
3091#if UTF8_PATH
3092 VALUE str = rb_utf8_str_new_cstr(p);
3093 str = str_conv_enc(str, NULL, rb_default_external_encoding());
3094 return str;
3095#else
3096 return rb_external_str_new_cstr(p);
3097#endif
3098}
3099
3100static void
3101set_progname(VALUE name)
3102{
3103 rb_orig_progname = rb_progname = name;
3104 rb_vm_set_progname(rb_progname);
3105}
3106
3107void
3108ruby_script(const char *name)
3109{
3110 if (name) {
3111 set_progname(rb_str_freeze(external_str_new_cstr(name)));
3112 }
3113}
3114
3119void
3121{
3122 set_progname(rb_str_new_frozen(name));
3123}
3124
3125static void
3126init_ids(ruby_cmdline_options_t *opt)
3127{
3128 rb_uid_t uid = getuid();
3129 rb_uid_t euid = geteuid();
3130 rb_gid_t gid = getgid();
3131 rb_gid_t egid = getegid();
3132
3133 if (uid != euid) opt->setids |= 1;
3134 if (egid != gid) opt->setids |= 2;
3135}
3136
3137#undef forbid_setid
3138static void
3139forbid_setid(const char *s, const ruby_cmdline_options_t *opt)
3140{
3141 if (opt->setids & 1)
3142 rb_raise(rb_eSecurityError, "no %s allowed while running setuid", s);
3143 if (opt->setids & 2)
3144 rb_raise(rb_eSecurityError, "no %s allowed while running setgid", s);
3145}
3146
3147static VALUE
3148verbose_getter(ID id, VALUE *ptr)
3149{
3150 return *rb_ruby_verbose_ptr();
3151}
3152
3153static void
3154verbose_setter(VALUE val, ID id, VALUE *variable)
3155{
3156 *rb_ruby_verbose_ptr() = RTEST(val) ? Qtrue : val;
3157}
3158
3159static VALUE
3160opt_W_getter(ID id, VALUE *dmy)
3161{
3162 VALUE v = *rb_ruby_verbose_ptr();
3163
3164 switch (v) {
3165 case Qnil:
3166 return INT2FIX(0);
3167 case Qfalse:
3168 return INT2FIX(1);
3169 case Qtrue:
3170 return INT2FIX(2);
3171 default:
3172 return Qnil;
3173 }
3174}
3175
3176static VALUE
3177debug_getter(ID id, VALUE *dmy)
3178{
3179 return *rb_ruby_debug_ptr();
3180}
3181
3182static void
3183debug_setter(VALUE val, ID id, VALUE *dmy)
3184{
3185 *rb_ruby_debug_ptr() = val;
3186}
3187
3188void
3190{
3191 rb_define_virtual_variable("$VERBOSE", verbose_getter, verbose_setter);
3192 rb_define_virtual_variable("$-v", verbose_getter, verbose_setter);
3193 rb_define_virtual_variable("$-w", verbose_getter, verbose_setter);
3195 rb_define_virtual_variable("$DEBUG", debug_getter, debug_setter);
3196 rb_define_virtual_variable("$-d", debug_getter, debug_setter);
3197
3198 rb_gvar_ractor_local("$VERBOSE");
3199 rb_gvar_ractor_local("$-v");
3200 rb_gvar_ractor_local("$-w");
3201 rb_gvar_ractor_local("$-W");
3202 rb_gvar_ractor_local("$DEBUG");
3203 rb_gvar_ractor_local("$-d");
3204
3205 rb_define_hooked_variable("$0", &rb_progname, 0, set_arg0);
3206 rb_define_hooked_variable("$PROGRAM_NAME", &rb_progname, 0, set_arg0);
3207
3208 rb_define_module_function(rb_mProcess, "argv0", proc_argv0, 0);
3209 rb_define_module_function(rb_mProcess, "setproctitle", proc_setproctitle, 1);
3210
3211 /*
3212 * ARGV contains the command line arguments used to run ruby.
3213 *
3214 * A library like OptionParser can be used to process command-line
3215 * arguments.
3216 */
3218}
3219
3220void
3221ruby_set_argv(int argc, char **argv)
3222{
3223 int i;
3224 VALUE av = rb_argv;
3225
3226 rb_ary_clear(av);
3227 for (i = 0; i < argc; i++) {
3228 VALUE arg = external_str_new_cstr(argv[i]);
3229
3230 OBJ_FREEZE(arg);
3231 rb_ary_push(av, arg);
3232 }
3233}
3234
3235void *
3236ruby_process_options(int argc, char **argv)
3237{
3239 VALUE iseq;
3240 const char *script_name = (argc > 0 && argv[0]) ? argv[0] : ruby_engine;
3241
3242 if (!origarg.argv || origarg.argc <= 0) {
3243 origarg.argc = argc;
3244 origarg.argv = argv;
3245 }
3246 set_progname(external_str_new_cstr(script_name)); /* for the time being */
3247 rb_argv0 = rb_str_new4(rb_progname);
3248 rb_vm_register_global_object(rb_argv0);
3249
3250#ifndef HAVE_SETPROCTITLE
3251 ruby_init_setproctitle(argc, argv);
3252#endif
3253
3254 if (getenv("RUBY_FREE_AT_EXIT")) {
3255 rb_free_at_exit = true;
3256 rb_category_warn(RB_WARN_CATEGORY_EXPERIMENTAL, "Free at exit is experimental and may be unstable");
3257 }
3258
3259 iseq = process_options(argc, argv, cmdline_options_init(&opt));
3260
3261 if (opt.crash_report && *opt.crash_report) {
3262 void ruby_set_crash_report(const char *template);
3263 ruby_set_crash_report(opt.crash_report);
3264 }
3265
3266 return (void*)(struct RData*)iseq;
3267}
3268
3269static void
3270fill_standard_fds(void)
3271{
3272 int f0, f1, f2, fds[2];
3273 struct stat buf;
3274 f0 = fstat(0, &buf) == -1 && errno == EBADF;
3275 f1 = fstat(1, &buf) == -1 && errno == EBADF;
3276 f2 = fstat(2, &buf) == -1 && errno == EBADF;
3277 if (f0) {
3278 if (pipe(fds) == 0) {
3279 close(fds[1]);
3280 if (fds[0] != 0) {
3281 dup2(fds[0], 0);
3282 close(fds[0]);
3283 }
3284 }
3285 }
3286 if (f1 || f2) {
3287 if (pipe(fds) == 0) {
3288 close(fds[0]);
3289 if (f1 && fds[1] != 1)
3290 dup2(fds[1], 1);
3291 if (f2 && fds[1] != 2)
3292 dup2(fds[1], 2);
3293 if (fds[1] != 1 && fds[1] != 2)
3294 close(fds[1]);
3295 }
3296 }
3297}
3298
3299void
3300ruby_sysinit(int *argc, char ***argv)
3301{
3302#if defined(_WIN32)
3303 rb_w32_sysinit(argc, argv);
3304#endif
3305 if (*argc >= 0 && *argv) {
3306 origarg.argc = *argc;
3307 origarg.argv = *argv;
3308 }
3309 fill_standard_fds();
3310}
3311
3312#ifdef RUBY_ASAN_ENABLED
3313RUBY_SYMBOL_EXPORT_BEGIN
3314const char ruby_asan_default_options[] = "use_sigaltstack=0:detect_leaks=0";
3315RUBY_SYMBOL_EXPORT_END
3316#endif
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define rb_define_module_function(klass, mid, func, arity)
Defines klass#mid and makes it a module function.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define RUBY_EXTERN
Declaration of externally visible global variables.
Definition dllexport.h:45
#define PATH_ENV
Definition dosish.h:63
#define PATH_SEP_CHAR
Identical to PATH_SEP, except it is of type char.
Definition dosish.h:49
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
#define ISSPACE
Old name of rb_isspace.
Definition ctype.h:88
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ECONV_UNDEF_REPLACE
Old name of RUBY_ECONV_UNDEF_REPLACE.
Definition transcode.h:526
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
Definition encoding.h:109
#define ECONV_INVALID_REPLACE
Old name of RUBY_ECONV_INVALID_REPLACE.
Definition transcode.h:524
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define STRNCASECMP
Old name of st_locale_insensitive_strncasecmp.
Definition ctype.h:103
#define TOLOWER
Old name of rb_tolower.
Definition ctype.h:101
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define ENC_CODERANGE_BROKEN
Old name of RUBY_ENC_CODERANGE_BROKEN.
Definition coderange.h:182
#define NIL_P
Old name of RB_NIL_P.
#define UINT2NUM
Old name of RB_UINT2NUM.
Definition int.h:46
#define scan_oct(s, l, e)
Old name of ruby_scan_oct.
Definition util.h:85
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define ISALNUM
Old name of rb_isalnum.
Definition ctype.h:91
#define rb_str_new4
Old name of rb_str_new_frozen.
Definition string.h:1678
void ruby_script(const char *name)
Sets the current script name to this value.
Definition ruby.c:3108
void ruby_set_argv(int argc, char **argv)
Sets argv that ruby understands.
Definition ruby.c:3221
void ruby_set_script_name(VALUE name)
Sets the current script name to this value.
Definition ruby.c:3120
void ruby_init_loadpath(void)
Sets up $LOAD_PATH.
Definition ruby.c:670
void * ruby_process_options(int argc, char **argv)
Identical to ruby_options(), except it raises ruby-level exceptions on failure.
Definition ruby.c:3236
void ruby_prog_init(void)
Defines built-in variables.
Definition ruby.c:3189
void ruby_incpush(const char *path)
Appends the given path to the end of the load path.
Definition ruby.c:511
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
Definition error.h:487
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:478
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:672
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:476
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eNameError
NameError exception.
Definition error.c:1436
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:468
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1482
void rb_enc_raise(rb_encoding *enc, VALUE exc, const char *fmt,...)
Identical to rb_raise(), except it additionally takes an encoding.
Definition error.c:3910
void rb_loaderror(const char *fmt,...)
Raises an instance of rb_eLoadError.
Definition error.c:3949
VALUE rb_eSecurityError
SecurityError exception.
Definition error.c:1440
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:499
@ RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK
Warning is for checking unused block strictly.
Definition error.h:57
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
@ RB_WARN_CATEGORY_EXPERIMENTAL
Warning is for experimental features.
Definition error.h:51
@ RB_WARN_CATEGORY_PERFORMANCE
Warning is for performance issues (not enabled by -w).
Definition error.h:54
VALUE rb_cObject
Object class.
Definition object.c:58
VALUE rb_mProcess
Process module.
Definition process.c:8697
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2280
VALUE rb_stdin
STDIN constant.
Definition io.c:203
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1297
VALUE rb_stdout
STDOUT constant.
Definition io.c:203
VALUE rb_cString
String class.
Definition string.c:84
void ruby_show_copyright(void)
Prints the copyright notice of the CRuby interpreter to stdout.
Definition version.c:302
void ruby_sysinit(int *argc, char ***argv)
Initializes the process for libruby.
Definition ruby.c:3300
void ruby_show_version(void)
Prints the version information of the CRuby interpreter to stdout.
Definition version.c:288
Encoding relates APIs.
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
Definition string.c:1361
VALUE rb_str_conv_enc_opts(VALUE str, rb_encoding *from, rb_encoding *to, int ecflags, VALUE ecopts)
Identical to rb_str_conv_enc(), except it additionally takes IO encoder options.
Definition string.c:1245
VALUE rb_enc_interned_str(const char *ptr, long len, rb_encoding *enc)
Identical to rb_enc_str_new(), except it returns a "f"string.
Definition string.c:13325
Declares rb_raise().
VALUE rb_funcall_passing_block(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv_public(), except you can pass the passed block.
Definition vm_eval.c:1186
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1123
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition vm_eval.c:1081
VALUE rb_ary_shift(VALUE ary)
Destructively deletes an element from the beginning of the passed array and returns what was deleted.
void rb_ary_modify(VALUE ary)
Declares that the array is about to be modified.
VALUE rb_ary_replace(VALUE copy, VALUE orig)
Replaces the contents of the former object with the contents of the latter.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_io_gets(VALUE io)
Reads a "line" from the given IO.
Definition io.c:4339
VALUE rb_io_ungetbyte(VALUE io, VALUE b)
Identical to rb_io_ungetc(), except it doesn't take the encoding of the passed IO into account.
Definition io.c:5211
VALUE rb_io_getbyte(VALUE io)
Reads a byte from the given IO.
Definition io.c:5116
VALUE rb_io_fdopen(int fd, int flags, const char *path)
Creates an IO instance whose backend is the given file descriptor.
Definition io.c:9385
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
Definition io.c:250
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
Definition io.c:330
VALUE rb_fs
The field separator character for inputs, or the $;.
Definition string.c:722
VALUE rb_output_rs
The record separator character for outputs, or the $\.
Definition io.c:208
int rb_pipe(int *pipes)
This is an rb_cloexec_pipe() + rb_update_max_fd() combo.
Definition io.c:7438
VALUE rb_io_close(VALUE io)
Closes the IO.
Definition io.c:5803
void rb_lastline_set(VALUE str)
Updates $_.
Definition vm.c:2109
VALUE rb_lastline_get(void)
Queries the last line, or the $_.
Definition vm.c:2103
rb_pid_t rb_waitpid(rb_pid_t pid, int *status, int flags)
Waits for a process, with releasing GVL.
Definition process.c:1161
VALUE rb_f_exec(int argc, const VALUE *argv)
Replaces the current process by running the given external command.
Definition process.c:2900
VALUE rb_reg_new(const char *src, long len, int opts)
Creates a new Regular expression.
Definition re.c:3650
#define rb_utf8_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "UTF-8" encoding.
Definition string.h:1584
#define rb_str_new_lit(str)
Identical to rb_str_new_static(), except it cannot take string variables.
Definition string.h:1706
VALUE rb_str_tmp_new(long len)
Allocates a "temporary" string.
Definition string.c:1765
VALUE rb_str_subseq(VALUE str, long beg, long len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3233
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1537
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2005
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3648
#define rb_external_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "default external" encoding.
Definition string.h:1605
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3467
#define rb_strlen_lit(str)
Length of a string literal.
Definition string.h:1693
VALUE rb_str_freeze(VALUE str)
This is the implementation of String#freeze.
Definition string.c:3358
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1657
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
Definition string.h:1550
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2783
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1515
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition variable.c:3408
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2059
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
void rb_define_global_const(const char *name, VALUE val)
Identical to rb_define_const(), except it defines that of "global", i.e.
Definition variable.c:3997
rb_gvar_setter_t rb_gvar_readonly_setter
This function just raises rb_eNameError.
Definition variable.h:135
VALUE rb_gv_set(const char *name, VALUE val)
Assigns to a global variable.
Definition variable.c:1060
@ RUBY_IO_READABLE
IO::READABLE
Definition io.h:97
VALUE rb_io_wait(VALUE io, VALUE events, VALUE timeout)
Blocks until the passed IO is ready for the passed events.
Definition io.c:1486
int len
Length of the buffer.
Definition io.h:8
void ruby_each_words(const char *str, void(*func)(const char *word, int len, void *argv), void *argv)
Scans the passed string, with calling the callback function every time it encounters a "word".
const char ruby_engine[]
This is just "ruby" for us.
Definition version.c:98
const int ruby_patchlevel
This is a monotonic increasing integer that describes specific "patch" level.
Definition version.c:86
#define RB_INT2NUM
Just another name of rb_int2num_inline.
Definition int.h:37
#define RB_ALLOCV_N(type, v, n)
Allocates a memory region, possibly on stack.
Definition memory.h:336
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
#define RB_ALLOCV_END(v)
Polite way to declare that the given array is not used any longer.
Definition memory.h:349
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:384
void rb_define_hooked_variable(const char *q, VALUE *w, type *e, void_type *r)
Define a function-backended global variable.
VALUE type(ANYARGS)
ANYARGS-ed function type.
void rb_define_virtual_variable(const char *q, type *w, void_type *e)
Define a function-backended global variable.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
static const uint8_t PM_OPTIONS_COMMAND_LINE_E
A bit representing whether or not the command line -e option was set.
Definition options.h:84
static const uint8_t PM_OPTIONS_COMMAND_LINE_L
A bit representing whether or not the command line -l option was set.
Definition options.h:90
static const uint8_t PM_OPTIONS_COMMAND_LINE_A
A bit representing whether or not the command line -a option was set.
Definition options.h:77
static const uint8_t PM_OPTIONS_COMMAND_LINE_N
A bit representing whether or not the command line -n option was set.
Definition options.h:96
static const uint8_t PM_OPTIONS_COMMAND_LINE_X
A bit representing whether or not the command line -x option was set.
Definition options.h:108
static const uint8_t PM_OPTIONS_COMMAND_LINE_P
A bit representing whether or not the command line -p option was set.
Definition options.h:102
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
Definition rarray.h:385
#define RARRAY_AREF(a, i)
Definition rarray.h:402
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:51
#define RFILE(obj)
Convenient casting macro.
Definition rfile.h:50
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
static int RSTRING_LENINT(VALUE str)
Identical to RSTRING_LEN(), except it differs for the return type.
Definition rstring.h:438
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
VALUE rb_argv0
The value of $0 at process bootup.
Definition ruby.c:1910
void * rb_load_file_str(VALUE file)
Identical to rb_load_file(), except it takes the argument as a Ruby's string instead of C's.
Definition ruby.c:3012
void * rb_load_file(const char *file)
Loads the given file.
Definition ruby.c:3005
#define rb_argv
Just another name of rb_get_argv.
Definition ruby.h:31
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:529
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Definition rdata.h:77
This struct represents a slice in the source code, defined by an offset and a length.
Definition ast.h:572
uint32_t start
The offset of the location from the start of the source.
Definition ast.h:574
uint32_t length
The length of the location.
Definition ast.h:577
pm_parser_t * parser
The parser that will do the actual parsing.
pm_scope_node_t node
The resulting scope node that will hold the generated AST.
pm_options_t * options
The options that will be passed to the parser.
Internal header for Ruby Box.
Definition box.h:14
Definition dtoa.c:309
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376