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