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