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