Ruby: ruby.c Source File

Ruby 4.0.5p0 (2026-05-20 revision 64336ffd0ee9e1f4c05891695a3d7b49cb709721)

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