Ruby 3.5.0dev (2025-05-15 revision 7afee53fa068918a03d5b7465a53c5552234a782)
ruby.c (7afee53fa068918a03d5b7465a53c5552234a782)
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 rb_const_set(rb_cObject, rb_intern_const("TMP_RUBY_PREFIX"), ruby_prefix_path);
762}
763
764
765static void
766add_modules(VALUE *req_list, const char *mod)
767{
768 VALUE list = *req_list;
769 VALUE feature;
770
771 if (!list) {
772 *req_list = list = rb_ary_hidden_new(0);
773 }
774 feature = rb_str_cat_cstr(rb_str_tmp_new(0), mod);
775 rb_ary_push(list, feature);
776}
777
778static void
779require_libraries(VALUE *req_list)
780{
781 VALUE list = *req_list;
782 VALUE self = rb_vm_top_self();
783 ID require;
784 rb_encoding *extenc = rb_default_external_encoding();
785
786 CONST_ID(require, "require");
787 while (list && RARRAY_LEN(list) > 0) {
788 VALUE feature = rb_ary_shift(list);
789 rb_enc_associate(feature, extenc);
790 RBASIC_SET_CLASS_RAW(feature, rb_cString);
791 OBJ_FREEZE(feature);
792 rb_funcallv(self, require, 1, &feature);
793 }
794 *req_list = 0;
795}
796
797static const struct rb_block*
798toplevel_context(rb_binding_t *bind)
799{
800 return &bind->block;
801}
802
803static int
804process_sflag(int sflag)
805{
806 if (sflag > 0) {
807 long n;
808 const VALUE *args;
809 VALUE argv = rb_argv;
810
811 n = RARRAY_LEN(argv);
812 args = RARRAY_CONST_PTR(argv);
813 while (n > 0) {
814 VALUE v = *args++;
815 char *s = StringValuePtr(v);
816 char *p;
817 int hyphen = FALSE;
818
819 if (s[0] != '-')
820 break;
821 n--;
822 if (s[1] == '-' && s[2] == '\0')
823 break;
824
825 v = Qtrue;
826 /* check if valid name before replacing - with _ */
827 for (p = s + 1; *p; p++) {
828 if (*p == '=') {
829 *p++ = '\0';
830 v = rb_str_new2(p);
831 break;
832 }
833 if (*p == '-') {
834 hyphen = TRUE;
835 }
836 else if (*p != '_' && !ISALNUM(*p)) {
837 VALUE name_error[2];
838 name_error[0] =
839 rb_str_new2("invalid name for global variable - ");
840 if (!(p = strchr(p, '='))) {
841 rb_str_cat2(name_error[0], s);
842 }
843 else {
844 rb_str_cat(name_error[0], s, p - s);
845 }
846 name_error[1] = args[-1];
848 }
849 }
850 s[0] = '$';
851 if (hyphen) {
852 for (p = s + 1; *p; ++p) {
853 if (*p == '-')
854 *p = '_';
855 }
856 }
857 rb_gv_set(s, v);
858 }
859 n = RARRAY_LEN(argv) - n;
860 while (n--) {
861 rb_ary_shift(argv);
862 }
863 return -1;
864 }
865 return sflag;
866}
867
868static long proc_options(long argc, char **argv, ruby_cmdline_options_t *opt, int envopt);
869
870static void
871moreswitches(const char *s, ruby_cmdline_options_t *opt, int envopt)
872{
873 long argc, i, len;
874 char **argv, *p;
875 const char *ap = 0;
876 VALUE argstr, argary;
877 void *ptr;
878
879 VALUE src_enc_name = opt->src.enc.name;
880 VALUE ext_enc_name = opt->ext.enc.name;
881 VALUE int_enc_name = opt->intern.enc.name;
882 ruby_features_t feat = opt->features;
883 ruby_features_t warn = opt->warn;
884 long backtrace_length_limit = opt->backtrace_length_limit;
885 const char *crash_report = opt->crash_report;
886
887 while (ISSPACE(*s)) s++;
888 if (!*s) return;
889
890 opt->src.enc.name = opt->ext.enc.name = opt->intern.enc.name = 0;
891
892 const int hyphen = *s != '-';
893 argstr = rb_str_tmp_new((len = strlen(s)) + hyphen);
894 argary = rb_str_tmp_new(0);
895
896 p = RSTRING_PTR(argstr);
897 if (hyphen) *p = '-';
898 memcpy(p + hyphen, s, len + 1);
899 ap = 0;
900 rb_str_cat(argary, (char *)&ap, sizeof(ap));
901 while (*p) {
902 ap = p;
903 rb_str_cat(argary, (char *)&ap, sizeof(ap));
904 while (*p && !ISSPACE(*p)) ++p;
905 if (!*p) break;
906 *p++ = '\0';
907 while (ISSPACE(*p)) ++p;
908 }
909 argc = RSTRING_LEN(argary) / sizeof(ap);
910 ap = 0;
911 rb_str_cat(argary, (char *)&ap, sizeof(ap));
912 argv = ptr = ALLOC_N(char *, argc);
913 MEMMOVE(argv, RSTRING_PTR(argary), char *, argc);
914
915 while ((i = proc_options(argc, argv, opt, envopt)) > 1 && envopt && (argc -= i) > 0) {
916 argv += i;
917 if (**argv != '-') {
918 *--*argv = '-';
919 }
920 if ((*argv)[1]) {
921 ++argc;
922 --argv;
923 }
924 }
925
926 if (src_enc_name) {
927 opt->src.enc.name = src_enc_name;
928 }
929 if (ext_enc_name) {
930 opt->ext.enc.name = ext_enc_name;
931 }
932 if (int_enc_name) {
933 opt->intern.enc.name = int_enc_name;
934 }
935 FEATURE_SET_RESTORE(opt->features, feat);
936 FEATURE_SET_RESTORE(opt->warn, warn);
937 if (BACKTRACE_LENGTH_LIMIT_VALID_P(backtrace_length_limit)) {
938 opt->backtrace_length_limit = backtrace_length_limit;
939 }
940 if (crash_report) {
941 opt->crash_report = crash_report;
942 }
943
944 ruby_xfree(ptr);
945 /* get rid of GC */
946 rb_str_resize(argary, 0);
947 rb_str_resize(argstr, 0);
948}
949
950static int
951name_match_p(const char *name, const char *str, size_t len)
952{
953 if (len == 0) return 0;
954 while (1) {
955 while (TOLOWER(*str) == *name) {
956 if (!--len) return 1;
957 ++name;
958 ++str;
959 }
960 if (*str != '-' && *str != '_') return 0;
961 while (ISALNUM(*name)) name++;
962 if (*name != '-' && *name != '_') return 0;
963 if (!*++name) return 1;
964 ++str;
965 if (--len == 0) return 1;
966 }
967}
968
969#define NAME_MATCH_P(name, str, len) \
970 ((len) < (int)sizeof(name) && name_match_p((name), (str), (len)))
971
972#define UNSET_WHEN(name, bit, str, len) \
973 if (NAME_MATCH_P((name), (str), (len))) { \
974 *(unsigned int *)arg &= ~(bit); \
975 return; \
976 }
977
978#define SET_WHEN(name, bit, str, len) \
979 if (NAME_MATCH_P((name), (str), (len))) { \
980 *(unsigned int *)arg |= (bit); \
981 return; \
982 }
983
984#define LITERAL_NAME_ELEMENT(name) #name
985
986static void
987feature_option(const char *str, int len, void *arg, const unsigned int enable)
988{
989 static const char list[] = EACH_FEATURES(LITERAL_NAME_ELEMENT, ", ");
990 ruby_features_t *argp = arg;
991 unsigned int mask = ~0U;
992 unsigned int set = 0U;
993#if AMBIGUOUS_FEATURE_NAMES
994 int matched = 0;
995# define FEATURE_FOUND ++matched
996#else
997# define FEATURE_FOUND goto found
998#endif
999#define SET_FEATURE(bit) \
1000 if (NAME_MATCH_P(#bit, str, len)) {set |= mask = FEATURE_BIT(bit); FEATURE_FOUND;}
1001 EACH_FEATURES(SET_FEATURE, ;);
1002 if (NAME_MATCH_P("jit", str, len)) { // This allows you to cancel --jit
1003 set |= mask = FEATURE_BIT(jit);
1004 goto found;
1005 }
1006 if (NAME_MATCH_P("all", str, len)) {
1007 // We enable only one JIT for --enable=all.
1008 mask &= ~feature_jit_mask | FEATURE_BIT(jit);
1009 goto found;
1010 }
1011#if AMBIGUOUS_FEATURE_NAMES
1012 if (matched == 1) goto found;
1013 if (matched > 1) {
1014 VALUE mesg = rb_sprintf("ambiguous feature: '%.*s' (", len, str);
1015#define ADD_FEATURE_NAME(bit) \
1016 if (FEATURE_BIT(bit) & set) { \
1017 rb_str_cat_cstr(mesg, #bit); \
1018 if (--matched) rb_str_cat_cstr(mesg, ", "); \
1019 }
1020 EACH_FEATURES(ADD_FEATURE_NAME, ;);
1021 rb_str_cat_cstr(mesg, ")");
1023#undef ADD_FEATURE_NAME
1024 }
1025#else
1026 (void)set;
1027#endif
1028 rb_warn("unknown argument for --%s: '%.*s'",
1029 enable ? "enable" : "disable", len, str);
1030 rb_warn("features are [%.*s].", (int)strlen(list), list);
1031 return;
1032
1033 found:
1034 FEATURE_SET_TO(*argp, mask, (mask & enable));
1035 if (NAME_MATCH_P("frozen_string_literal", str, len)) {
1036 FEATURE_SET_TO(*argp, FEATURE_BIT(frozen_string_literal_set), FEATURE_BIT(frozen_string_literal_set));
1037 }
1038 return;
1039}
1040
1041static void
1042enable_option(const char *str, int len, void *arg)
1043{
1044 feature_option(str, len, arg, ~0U);
1045}
1046
1047static void
1048disable_option(const char *str, int len, void *arg)
1049{
1050 feature_option(str, len, arg, 0U);
1051}
1052
1054int ruby_env_debug_option(const char *str, int len, void *arg);
1055
1056static void
1057debug_option(const char *str, int len, void *arg)
1058{
1059 static const char list[] = EACH_DEBUG_FEATURES(LITERAL_NAME_ELEMENT, ", ");
1060 ruby_features_t *argp = arg;
1061#define SET_WHEN_DEBUG(bit) \
1062 if (NAME_MATCH_P(#bit, str, len)) { \
1063 FEATURE_SET(*argp, DEBUG_BIT(bit)); \
1064 return; \
1065 }
1066 EACH_DEBUG_FEATURES(SET_WHEN_DEBUG, ;);
1067#ifdef RUBY_DEVEL
1068 if (ruby_patchlevel < 0 && ruby_env_debug_option(str, len, 0)) return;
1069#endif
1070 rb_warn("unknown argument for --debug: '%.*s'", len, str);
1071 rb_warn("debug features are [%.*s].", (int)strlen(list), list);
1072}
1073
1074static int
1075memtermspn(const char *str, char term, int len)
1076{
1077 RUBY_ASSERT(len >= 0);
1078 if (len <= 0) return 0;
1079 const char *next = memchr(str, term, len);
1080 return next ? (int)(next - str) : len;
1081}
1082
1083static const char additional_opt_sep = '+';
1084
1085static unsigned int
1086dump_additional_option_flag(const char *str, int len, unsigned int bits, bool set)
1087{
1088#define SET_DUMP_OPT(bit) if (NAME_MATCH_P(#bit, str, len)) { \
1089 return set ? (bits | DUMP_BIT(opt_ ## bit)) : (bits & ~DUMP_BIT(opt_ ## bit)); \
1090 }
1091 SET_DUMP_OPT(error_tolerant);
1092 SET_DUMP_OPT(comment);
1093 SET_DUMP_OPT(optimize);
1094#undef SET_DUMP_OPT
1095 rb_warn("don't know how to dump with%s '%.*s'", set ? "" : "out", len, str);
1096 return bits;
1097}
1098
1099static unsigned int
1100dump_additional_option(const char *str, int len, unsigned int bits)
1101{
1102 int w;
1103 for (; len-- > 0 && *str++ == additional_opt_sep; len -= w, str += w) {
1104 w = memtermspn(str, additional_opt_sep, len);
1105 bool set = true;
1106 if (*str == '-' || *str == '+') {
1107 set = *str++ == '+';
1108 --w;
1109 }
1110 else {
1111 int n = memtermspn(str, '-', w);
1112 if (str[n] == '-') {
1113 if (NAME_MATCH_P("with", str, n)) {
1114 str += n;
1115 w -= n;
1116 }
1117 else if (NAME_MATCH_P("without", str, n)) {
1118 set = false;
1119 str += n;
1120 w -= n;
1121 }
1122 }
1123 }
1124 bits = dump_additional_option_flag(str, w, bits, set);
1125 }
1126 return bits;
1127}
1128
1129static void
1130dump_option(const char *str, int len, void *arg)
1131{
1132 static const char list[] = EACH_DUMPS(LITERAL_NAME_ELEMENT, ", ");
1133 unsigned int *bits_ptr = (unsigned int *)arg;
1134 if (*str == '+' || *str == '-') {
1135 bool set = *str++ == '+';
1136 *bits_ptr = dump_additional_option_flag(str, --len, *bits_ptr, set);
1137 return;
1138 }
1139 int w = memtermspn(str, additional_opt_sep, len);
1140
1141#define SET_WHEN_DUMP(bit) \
1142 if (NAME_MATCH_P(#bit "-", (str), (w))) { \
1143 *bits_ptr = dump_additional_option(str + w, len - w, *bits_ptr | DUMP_BIT(bit)); \
1144 return; \
1145 }
1146 EACH_DUMPS(SET_WHEN_DUMP, ;);
1147 rb_warn("don't know how to dump '%.*s',", len, str);
1148 rb_warn("but only [%.*s].", (int)strlen(list), list);
1149}
1150
1151static void
1152set_option_encoding_once(const char *type, VALUE *name, const char *e, long elen)
1153{
1154 VALUE ename;
1155
1156 if (!elen) elen = strlen(e);
1157 ename = rb_str_new(e, elen);
1158
1159 if (*name &&
1160 rb_funcall(ename, rb_intern("casecmp"), 1, *name) != INT2FIX(0)) {
1161 rb_raise(rb_eRuntimeError,
1162 "%s already set to %"PRIsVALUE, type, *name);
1163 }
1164 *name = ename;
1165}
1166
1167#define set_internal_encoding_once(opt, e, elen) \
1168 set_option_encoding_once("default_internal", &(opt)->intern.enc.name, (e), (elen))
1169#define set_external_encoding_once(opt, e, elen) \
1170 set_option_encoding_once("default_external", &(opt)->ext.enc.name, (e), (elen))
1171#define set_source_encoding_once(opt, e, elen) \
1172 set_option_encoding_once("source", &(opt)->src.enc.name, (e), (elen))
1173
1174#define yjit_opt_match_noarg(s, l, name) \
1175 opt_match(s, l, name) && (*(s) ? (rb_warn("argument to --yjit-" name " is ignored"), 1) : 1)
1176#define yjit_opt_match_arg(s, l, name) \
1177 opt_match(s, l, name) && (*(s) && *(s+1) ? 1 : (rb_raise(rb_eRuntimeError, "--yjit-" name " needs an argument"), 0))
1178
1179#if USE_YJIT
1180static bool
1181setup_yjit_options(const char *s)
1182{
1183 // The option parsing is done in yjit/src/options.rs
1184 bool rb_yjit_parse_option(const char* s);
1185 bool success = rb_yjit_parse_option(s);
1186
1187 if (success) {
1188 return true;
1189 }
1190
1191 rb_raise(
1193 "invalid YJIT option '%s' (--help will show valid yjit options)",
1194 s
1195 );
1196}
1197#endif
1198
1199#if USE_ZJIT
1200static void
1201setup_zjit_options(ruby_cmdline_options_t *opt, const char *s)
1202{
1203 // The option parsing is done in zjit/src/options.rs
1204 extern void *rb_zjit_init_options(void);
1205 extern bool rb_zjit_parse_option(void *options, const char *s);
1206
1207 if (!opt->zjit) opt->zjit = rb_zjit_init_options();
1208 if (!rb_zjit_parse_option(opt->zjit, s)) {
1209 rb_raise(rb_eRuntimeError, "invalid ZJIT option '%s' (--help will show valid zjit options)", s);
1210 }
1211}
1212#endif
1213
1214/*
1215 * Following proc_*_option functions are tree kinds:
1216 *
1217 * - with a required argument, takes also `argc` and `argv`, and
1218 * returns the number of consumed argv including the option itself.
1219 *
1220 * - with a mandatory argument just after the option.
1221 *
1222 * - no required argument, this returns the address of
1223 * the next character after the last consumed character.
1224 */
1225
1226/* optional */
1227static const char *
1228proc_W_option(ruby_cmdline_options_t *opt, const char *s, int *warning)
1229{
1230 if (s[1] == ':') {
1231 unsigned int bits = 0;
1232 static const char no_prefix[] = "no-";
1233 int enable = strncmp(s += 2, no_prefix, sizeof(no_prefix)-1) != 0;
1234 if (!enable) s += sizeof(no_prefix)-1;
1235 size_t len = strlen(s);
1236 if (NAME_MATCH_P("deprecated", s, len)) {
1237 bits = 1U << RB_WARN_CATEGORY_DEPRECATED;
1238 }
1239 else if (NAME_MATCH_P("experimental", s, len)) {
1240 bits = 1U << RB_WARN_CATEGORY_EXPERIMENTAL;
1241 }
1242 else if (NAME_MATCH_P("performance", s, len)) {
1243 bits = 1U << RB_WARN_CATEGORY_PERFORMANCE;
1244 }
1245 else if (NAME_MATCH_P("strict_unused_block", s, len)) {
1247 }
1248 else {
1249 rb_warn("unknown warning category: '%s'", s);
1250 }
1251 if (bits) FEATURE_SET_TO(opt->warn, bits, enable ? bits : 0);
1252 return 0;
1253 }
1254 else {
1255 size_t numlen;
1256 int v = 2; /* -W as -W2 */
1257
1258 if (*++s) {
1259 v = scan_oct(s, 1, &numlen);
1260 if (numlen == 0)
1261 v = 2;
1262 s += numlen;
1263 }
1264 if (!opt->warning) {
1265 switch (v) {
1266 case 0:
1268 break;
1269 case 1:
1271 break;
1272 default:
1274 break;
1275 }
1276 }
1277 *warning = 1;
1278 switch (v) {
1279 case 0:
1280 FEATURE_SET_TO(opt->warn, RB_WARN_CATEGORY_DEFAULT_BITS, 0);
1281 break;
1282 case 1:
1283 FEATURE_SET_TO(opt->warn, 1U << RB_WARN_CATEGORY_DEPRECATED, 0);
1284 break;
1285 default:
1286 FEATURE_SET(opt->warn, RB_WARN_CATEGORY_DEFAULT_BITS);
1287 break;
1288 }
1289 return s;
1290 }
1291}
1292
1293/* required */
1294static long
1295proc_e_option(ruby_cmdline_options_t *opt, const char *s, long argc, char **argv)
1296{
1297 long n = 1;
1298 forbid_setid("-e");
1299 if (!*++s) {
1300 if (!--argc)
1301 rb_raise(rb_eRuntimeError, "no code specified for -e");
1302 s = *++argv;
1303 n++;
1304 }
1305 if (!opt->e_script) {
1306 opt->e_script = rb_str_new(0, 0);
1307 if (opt->script == 0)
1308 opt->script = "-e";
1309 }
1310 rb_str_cat2(opt->e_script, s);
1311 rb_str_cat2(opt->e_script, "\n");
1312 return n;
1313}
1314
1315/* optional */
1316static const char *
1317proc_K_option(ruby_cmdline_options_t *opt, const char *s)
1318{
1319 if (*++s) {
1320 const char *enc_name = 0;
1321 switch (*s) {
1322 case 'E': case 'e':
1323 enc_name = "EUC-JP";
1324 break;
1325 case 'S': case 's':
1326 enc_name = "Windows-31J";
1327 break;
1328 case 'U': case 'u':
1329 enc_name = "UTF-8";
1330 break;
1331 case 'N': case 'n': case 'A': case 'a':
1332 enc_name = "ASCII-8BIT";
1333 break;
1334 }
1335 if (enc_name) {
1336 opt->src.enc.name = rb_str_new2(enc_name);
1337 if (!opt->ext.enc.name)
1338 opt->ext.enc.name = opt->src.enc.name;
1339 }
1340 s++;
1341 }
1342 return s;
1343}
1344
1345/* optional */
1346static const char *
1347proc_0_option(ruby_cmdline_options_t *opt, const char *s)
1348{
1349 size_t numlen;
1350 int v;
1351 char c;
1352
1353 v = scan_oct(s, 4, &numlen);
1354 s += numlen;
1355 if (v > 0377)
1356 rb_rs = Qnil;
1357 else if (v == 0 && numlen >= 2) {
1358 rb_rs = rb_fstring_lit("");
1359 }
1360 else {
1361 c = v & 0xff;
1362 rb_rs = rb_str_freeze(rb_str_new(&c, 1));
1363 }
1364 return s;
1365}
1366
1367/* mandatory */
1368static void
1369proc_encoding_option(ruby_cmdline_options_t *opt, const char *s, const char *opt_name)
1370{
1371 char *p;
1372# define set_encoding_part(type) \
1373 if (!(p = strchr(s, ':'))) { \
1374 set_##type##_encoding_once(opt, s, 0); \
1375 return; \
1376 } \
1377 else if (p > s) { \
1378 set_##type##_encoding_once(opt, s, p-s); \
1379 }
1380 set_encoding_part(external);
1381 if (!*(s = ++p)) return;
1382 set_encoding_part(internal);
1383 if (!*(s = ++p)) return;
1384#if defined ALLOW_DEFAULT_SOURCE_ENCODING && ALLOW_DEFAULT_SOURCE_ENCODING
1385 set_encoding_part(source);
1386 if (!*(s = ++p)) return;
1387#endif
1388 rb_raise(rb_eRuntimeError, "extra argument for %s: %s", opt_name, s);
1389# undef set_encoding_part
1391}
1392
1393static long
1394proc_long_options(ruby_cmdline_options_t *opt, const char *s, long argc, char **argv, int envopt)
1395{
1396 size_t n;
1397 long argc0 = argc;
1398# define is_option_end(c, allow_hyphen) \
1399 (!(c) || ((allow_hyphen) && (c) == '-') || (c) == '=')
1400# define check_envopt(name, allow_envopt) \
1401 (((allow_envopt) || !envopt) ? (void)0 : \
1402 rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --" name))
1403# define need_argument(name, s, needs_arg, next_arg) \
1404 ((*(s) ? !*++(s) : (next_arg) && (argc <= 1 || !((s) = argv[1]) || (--argc, ++argv, 0))) && (needs_arg) ? \
1405 rb_raise(rb_eRuntimeError, "missing argument for --" name) \
1406 : (void)0)
1407# define is_option_with_arg(name, allow_hyphen, allow_envopt) \
1408 is_option_with_optarg(name, allow_hyphen, allow_envopt, Qtrue, Qtrue)
1409# define is_option_with_optarg(name, allow_hyphen, allow_envopt, needs_arg, next_arg) \
1410 (strncmp((name), s, n = sizeof(name) - 1) == 0 && is_option_end(s[n], (allow_hyphen)) && \
1411 (s[n] != '-' || (s[n] && s[n+1])) ? \
1412 (check_envopt(name, (allow_envopt)), s += n, \
1413 need_argument(name, s, needs_arg, next_arg), 1) : 0)
1414
1415 if (strcmp("copyright", s) == 0) {
1416 if (envopt) goto noenvopt_long;
1417 opt->dump |= DUMP_BIT(copyright);
1418 }
1419 else if (is_option_with_optarg("debug", Qtrue, Qtrue, Qfalse, Qfalse)) {
1420 if (s && *s) {
1421 ruby_each_words(s, debug_option, &opt->features);
1422 }
1423 else {
1424 ruby_debug = Qtrue;
1426 }
1427 }
1428 else if (is_option_with_arg("enable", Qtrue, Qtrue)) {
1429 ruby_each_words(s, enable_option, &opt->features);
1430 }
1431 else if (is_option_with_arg("disable", Qtrue, Qtrue)) {
1432 ruby_each_words(s, disable_option, &opt->features);
1433 }
1434 else if (is_option_with_arg("encoding", Qfalse, Qtrue)) {
1435 proc_encoding_option(opt, s, "--encoding");
1436 }
1437 else if (is_option_with_arg("internal-encoding", Qfalse, Qtrue)) {
1438 set_internal_encoding_once(opt, s, 0);
1439 }
1440 else if (is_option_with_arg("external-encoding", Qfalse, Qtrue)) {
1441 set_external_encoding_once(opt, s, 0);
1442 }
1443 else if (is_option_with_arg("parser", Qfalse, Qtrue)) {
1444 if (strcmp("prism", s) == 0) {
1445 rb_ruby_default_parser_set(RB_DEFAULT_PARSER_PRISM);
1446 }
1447 else if (strcmp("parse.y", s) == 0) {
1448 rb_ruby_default_parser_set(RB_DEFAULT_PARSER_PARSE_Y);
1449 }
1450 else {
1451 rb_raise(rb_eRuntimeError, "unknown parser %s", s);
1452 }
1453 }
1454#if defined ALLOW_DEFAULT_SOURCE_ENCODING && ALLOW_DEFAULT_SOURCE_ENCODING
1455 else if (is_option_with_arg("source-encoding", Qfalse, Qtrue)) {
1456 set_source_encoding_once(opt, s, 0);
1457 }
1458#endif
1459 else if (strcmp("version", s) == 0) {
1460 if (envopt) goto noenvopt_long;
1461 opt->dump |= DUMP_BIT(version);
1462 }
1463 else if (strcmp("verbose", s) == 0) {
1464 opt->verbose = 1;
1466 }
1467 else if (strcmp("jit", s) == 0) {
1468#if USE_YJIT
1469 FEATURE_SET(opt->features, FEATURE_BIT(jit));
1470#else
1471 rb_warn("Ruby was built without JIT support");
1472#endif
1473 }
1474 else if (is_option_with_optarg("yjit", '-', true, false, false)) {
1475#if USE_YJIT
1476 FEATURE_SET(opt->features, FEATURE_BIT(yjit));
1477 setup_yjit_options(s);
1478#else
1479 rb_warn("Ruby was built without YJIT support."
1480 " You may need to install rustc to build Ruby with YJIT.");
1481#endif
1482 }
1483 else if (is_option_with_optarg("zjit", '-', true, false, false)) {
1484#if USE_ZJIT
1485 FEATURE_SET(opt->features, FEATURE_BIT(zjit));
1486 setup_zjit_options(opt, s);
1487#else
1488 rb_warn("Ruby was built without ZJIT support."
1489 " You may need to install rustc to build Ruby with ZJIT.");
1490#endif
1491 }
1492 else if (strcmp("yydebug", s) == 0) {
1493 if (envopt) goto noenvopt_long;
1494 opt->dump |= DUMP_BIT(yydebug);
1495 }
1496 else if (is_option_with_arg("dump", Qfalse, Qfalse)) {
1497 ruby_each_words(s, dump_option, &opt->dump);
1498 }
1499 else if (strcmp("help", s) == 0) {
1500 if (envopt) goto noenvopt_long;
1501 opt->dump |= DUMP_BIT(help);
1502 return 0;
1503 }
1504 else if (is_option_with_arg("backtrace-limit", Qfalse, Qtrue)) {
1505 char *e;
1506 long n = strtol(s, &e, 10);
1507 if (errno == ERANGE || !BACKTRACE_LENGTH_LIMIT_VALID_P(n) || *e) {
1508 rb_raise(rb_eRuntimeError, "wrong limit for backtrace length");
1509 }
1510 else {
1511 opt->backtrace_length_limit = n;
1512 }
1513 }
1514 else if (is_option_with_arg("crash-report", true, true)) {
1515 opt->crash_report = s;
1516 }
1517 else {
1518 rb_raise(rb_eRuntimeError,
1519 "invalid option --%s (-h will show valid options)", s);
1520 }
1521 return argc0 - argc + 1;
1522
1523 noenvopt_long:
1524 rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --%s", s);
1525# undef is_option_end
1526# undef check_envopt
1527# undef need_argument
1528# undef is_option_with_arg
1529# undef is_option_with_optarg
1531}
1532
1533static long
1534proc_options(long argc, char **argv, ruby_cmdline_options_t *opt, int envopt)
1535{
1536 long n, argc0 = argc;
1537 const char *s;
1538 int warning = opt->warning;
1539
1540 if (argc <= 0 || !argv)
1541 return 0;
1542
1543 for (argc--, argv++; argc > 0; argc--, argv++) {
1544 const char *const arg = argv[0];
1545 if (!arg || arg[0] != '-' || !arg[1])
1546 break;
1547
1548 s = arg + 1;
1549 reswitch:
1550 switch (*s) {
1551 case 'a':
1552 if (envopt) goto noenvopt;
1553 opt->do_split = TRUE;
1554 s++;
1555 goto reswitch;
1556
1557 case 'p':
1558 if (envopt) goto noenvopt;
1559 opt->do_print = TRUE;
1560 /* through */
1561 case 'n':
1562 if (envopt) goto noenvopt;
1563 opt->do_loop = TRUE;
1564 s++;
1565 goto reswitch;
1566
1567 case 'd':
1568 ruby_debug = Qtrue;
1570 s++;
1571 goto reswitch;
1572
1573 case 'y':
1574 if (envopt) goto noenvopt;
1575 opt->dump |= DUMP_BIT(yydebug);
1576 s++;
1577 goto reswitch;
1578
1579 case 'v':
1580 if (opt->verbose) {
1581 s++;
1582 goto reswitch;
1583 }
1584 opt->dump |= DUMP_BIT(version_v);
1585 opt->verbose = 1;
1586 case 'w':
1587 if (!opt->warning) {
1588 warning = 1;
1590 }
1591 FEATURE_SET(opt->warn, RB_WARN_CATEGORY_DEFAULT_BITS);
1592 s++;
1593 goto reswitch;
1594
1595 case 'W':
1596 if (!(s = proc_W_option(opt, s, &warning))) break;
1597 goto reswitch;
1598
1599 case 'c':
1600 if (envopt) goto noenvopt;
1601 opt->dump |= DUMP_BIT(syntax);
1602 s++;
1603 goto reswitch;
1604
1605 case 's':
1606 if (envopt) goto noenvopt;
1607 forbid_setid("-s");
1608 if (!opt->sflag) opt->sflag = 1;
1609 s++;
1610 goto reswitch;
1611
1612 case 'h':
1613 if (envopt) goto noenvopt;
1614 opt->dump |= DUMP_BIT(usage);
1615 goto switch_end;
1616
1617 case 'l':
1618 if (envopt) goto noenvopt;
1619 opt->do_line = TRUE;
1620 rb_output_rs = rb_rs;
1621 s++;
1622 goto reswitch;
1623
1624 case 'S':
1625 if (envopt) goto noenvopt;
1626 forbid_setid("-S");
1627 opt->do_search = TRUE;
1628 s++;
1629 goto reswitch;
1630
1631 case 'e':
1632 if (envopt) goto noenvopt;
1633 if (!(n = proc_e_option(opt, s, argc, argv))) break;
1634 --n;
1635 argc -= n;
1636 argv += n;
1637 break;
1638
1639 case 'r':
1640 forbid_setid("-r");
1641 if (*++s) {
1642 add_modules(&opt->req_list, s);
1643 }
1644 else if (argc > 1) {
1645 add_modules(&opt->req_list, argv[1]);
1646 argc--, argv++;
1647 }
1648 break;
1649
1650 case 'i':
1651 if (envopt) goto noenvopt;
1652 forbid_setid("-i");
1653 ruby_set_inplace_mode(s + 1);
1654 break;
1655
1656 case 'x':
1657 if (envopt) goto noenvopt;
1658 forbid_setid("-x");
1659 opt->xflag = TRUE;
1660 s++;
1661 if (*s && chdir(s) < 0) {
1662 rb_fatal("Can't chdir to %s", s);
1663 }
1664 break;
1665
1666 case 'C':
1667 case 'X':
1668 if (envopt) goto noenvopt;
1669 if (!*++s && (!--argc || !(s = *++argv) || !*s)) {
1670 rb_fatal("Can't chdir");
1671 }
1672 if (chdir(s) < 0) {
1673 rb_fatal("Can't chdir to %s", s);
1674 }
1675 break;
1676
1677 case 'F':
1678 if (envopt) goto noenvopt;
1679 if (*++s) {
1680 rb_fs = rb_reg_new(s, strlen(s), 0);
1681 }
1682 break;
1683
1684 case 'E':
1685 if (!*++s && (!--argc || !(s = *++argv))) {
1686 rb_raise(rb_eRuntimeError, "missing argument for -E");
1687 }
1688 proc_encoding_option(opt, s, "-E");
1689 break;
1690
1691 case 'U':
1692 set_internal_encoding_once(opt, "UTF-8", 0);
1693 ++s;
1694 goto reswitch;
1695
1696 case 'K':
1697 if (!(s = proc_K_option(opt, s))) break;
1698 goto reswitch;
1699
1700 case 'I':
1701 forbid_setid("-I");
1702 if (*++s)
1703 ruby_incpush_expand(s);
1704 else if (argc > 1) {
1705 ruby_incpush_expand(argv[1]);
1706 argc--, argv++;
1707 }
1708 break;
1709
1710 case '0':
1711 if (envopt) goto noenvopt;
1712 if (!(s = proc_0_option(opt, s))) break;
1713 goto reswitch;
1714
1715 case '-':
1716 if (!s[1] || (s[1] == '\r' && !s[2])) {
1717 argc--, argv++;
1718 goto switch_end;
1719 }
1720 s++;
1721
1722 if (!(n = proc_long_options(opt, s, argc, argv, envopt))) goto switch_end;
1723 --n;
1724 argc -= n;
1725 argv += n;
1726 break;
1727
1728 case '\r':
1729 if (!s[1])
1730 break;
1731
1732 default: {
1733 rb_encoding *enc = IF_UTF8_PATH(rb_utf8_encoding(), rb_locale_encoding());
1734 const char *e = s + strlen(s);
1735 int r = rb_enc_precise_mbclen(s, e, enc);
1736 unsigned int c = (unsigned char)*s;
1737 if (r > 0) {
1738 c = rb_enc_mbc_to_codepoint(s, e, enc);
1739 if (ONIGENC_IS_CODE_GRAPH(enc, c) ||
1740 ((s = ruby_escaped_char(c)) != 0 &&
1741 (r = (int)strlen(s), /* 3 at most */ 1))) {
1743 "invalid option -%.*s (-h will show valid options)",
1744 r, s);
1745 }
1746 }
1747 rb_raise(rb_eRuntimeError,
1748 "invalid option -\\x%.2x (-h will show valid options)",
1749 c);
1750
1751 goto switch_end;
1752 }
1753
1754 noenvopt:
1755 /* "EIdvwWrKU" only */
1756 rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: -%c", *s);
1757 break;
1758
1759 case 0:
1760 break;
1761 }
1762 }
1763
1764 switch_end:
1765 if (warning) opt->warning = warning;
1766 return argc0 - argc;
1767}
1768
1769void Init_builtin_features(void);
1770
1771static void
1772ruby_init_prelude(void)
1773{
1774 Init_builtin_features();
1775 rb_const_remove(rb_cObject, rb_intern_const("TMP_RUBY_PREFIX"));
1776}
1777
1778void rb_call_builtin_inits(void);
1779
1780// Initialize extra optional exts linked statically.
1781// This empty definition will be replaced with the actual strong symbol by linker.
1782#if RBIMPL_HAS_ATTRIBUTE(weak)
1783__attribute__((weak))
1784#endif
1785void
1786Init_extra_exts(void)
1787{
1788}
1789
1790static void
1791ruby_opt_init(ruby_cmdline_options_t *opt)
1792{
1793 rb_warning_category_update(opt->warn.mask, opt->warn.set);
1794
1795 if (opt->dump & dump_exit_bits) return;
1796
1797 if (FEATURE_SET_P(opt->features, gems)) {
1798 rb_define_module("Gem");
1799 if (opt->features.set & FEATURE_BIT(error_highlight)) {
1800 rb_define_module("ErrorHighlight");
1801 }
1802 if (opt->features.set & FEATURE_BIT(did_you_mean)) {
1803 rb_define_module("DidYouMean");
1804 }
1805 if (opt->features.set & FEATURE_BIT(syntax_suggest)) {
1806 rb_define_module("SyntaxSuggest");
1807 }
1808 }
1809
1810 /* [Feature #19785] Warning for removed GC environment variable.
1811 * Remove this in Ruby 3.4. */
1812 if (getenv("RUBY_GC_HEAP_INIT_SLOTS")) {
1813 rb_warn_deprecated("The environment variable RUBY_GC_HEAP_INIT_SLOTS",
1814 "environment variables RUBY_GC_HEAP_%d_INIT_SLOTS");
1815 }
1816
1817 Init_ext(); /* load statically linked extensions before rubygems */
1818 Init_extra_exts();
1819
1820 GET_VM()->running = 0;
1821 rb_call_builtin_inits();
1822 GET_VM()->running = 1;
1823 memset(ruby_vm_redefined_flag, 0, sizeof(ruby_vm_redefined_flag));
1824
1825 ruby_init_prelude();
1826
1827 if (rb_namespace_available())
1828 rb_initialize_main_namespace();
1829
1830 // Initialize JITs after prelude because JITing prelude is typically not optimal.
1831#if USE_YJIT
1832 rb_yjit_init(opt->yjit);
1833#endif
1834#if USE_ZJIT
1835 if (opt->zjit) {
1836 extern void rb_zjit_init(void *options);
1837 rb_zjit_init(opt->zjit);
1838 }
1839#endif
1840
1841#if USE_YJIT
1842 // Call yjit_hook.rb after rb_yjit_init() to use `RubyVM::YJIT.enabled?`
1843 void Init_builtin_yjit_hook();
1844 Init_builtin_yjit_hook();
1845#endif
1846
1847 ruby_set_script_name(opt->script_name);
1848 require_libraries(&opt->req_list);
1849}
1850
1851static int
1852opt_enc_index(VALUE enc_name)
1853{
1854 const char *s = RSTRING_PTR(enc_name);
1855 int i = rb_enc_find_index(s);
1856
1857 if (i < 0) {
1858 rb_raise(rb_eRuntimeError, "unknown encoding name - %s", s);
1859 }
1860 else if (rb_enc_dummy_p(rb_enc_from_index(i))) {
1861 rb_raise(rb_eRuntimeError, "dummy encoding is not acceptable - %s ", s);
1862 }
1863 return i;
1864}
1865
1866#define rb_progname (GET_VM()->progname)
1867#define rb_orig_progname (GET_VM()->orig_progname)
1869VALUE rb_e_script;
1870
1871static VALUE
1872false_value(ID _x, VALUE *_y)
1873{
1874 return Qfalse;
1875}
1876
1877static VALUE
1878true_value(ID _x, VALUE *_y)
1879{
1880 return Qtrue;
1881}
1882
1883#define rb_define_readonly_boolean(name, val) \
1884 rb_define_virtual_variable((name), (val) ? true_value : false_value, 0)
1885
1886static VALUE
1887uscore_get(void)
1888{
1889 VALUE line;
1890
1891 line = rb_lastline_get();
1892 if (!RB_TYPE_P(line, T_STRING)) {
1893 rb_raise(rb_eTypeError, "$_ value need to be String (%s given)",
1894 NIL_P(line) ? "nil" : rb_obj_classname(line));
1895 }
1896 return line;
1897}
1898
1899/*
1900 * call-seq:
1901 * sub(pattern, replacement) -> $_
1902 * sub(pattern) {|...| block } -> $_
1903 *
1904 * Equivalent to <code>$_.sub(<i>args</i>)</code>, except that
1905 * <code>$_</code> will be updated if substitution occurs.
1906 * Available only when -p/-n command line option specified.
1907 */
1908
1909static VALUE
1910rb_f_sub(int argc, VALUE *argv, VALUE _)
1911{
1912 VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("sub"), argc, argv);
1913 rb_lastline_set(str);
1914 return str;
1915}
1916
1917/*
1918 * call-seq:
1919 * gsub(pattern, replacement) -> $_
1920 * gsub(pattern) {|...| block } -> $_
1921 *
1922 * Equivalent to <code>$_.gsub...</code>, except that <code>$_</code>
1923 * will be updated if substitution occurs.
1924 * Available only when -p/-n command line option specified.
1925 *
1926 */
1927
1928static VALUE
1929rb_f_gsub(int argc, VALUE *argv, VALUE _)
1930{
1931 VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("gsub"), argc, argv);
1932 rb_lastline_set(str);
1933 return str;
1934}
1935
1936/*
1937 * call-seq:
1938 * chop -> $_
1939 *
1940 * Equivalent to <code>($_.dup).chop!</code>, except <code>nil</code>
1941 * is never returned. See String#chop!.
1942 * Available only when -p/-n command line option specified.
1943 *
1944 */
1945
1946static VALUE
1947rb_f_chop(VALUE _)
1948{
1949 VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("chop"), 0, 0);
1950 rb_lastline_set(str);
1951 return str;
1952}
1953
1954
1955/*
1956 * call-seq:
1957 * chomp -> $_
1958 * chomp(string) -> $_
1959 *
1960 * Equivalent to <code>$_ = $_.chomp(<em>string</em>)</code>. See
1961 * String#chomp.
1962 * Available only when -p/-n command line option specified.
1963 *
1964 */
1965
1966static VALUE
1967rb_f_chomp(int argc, VALUE *argv, VALUE _)
1968{
1969 VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("chomp"), argc, argv);
1970 rb_lastline_set(str);
1971 return str;
1972}
1973
1974static void
1975setup_pager_env(void)
1976{
1977 if (!getenv("LESS")) {
1978 // Output "raw" control characters, and move per sections.
1979 ruby_setenv("LESS", "-R +/^[A-Z].*");
1980 }
1981}
1982
1983#ifdef _WIN32
1984static int
1985tty_enabled(void)
1986{
1987 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
1988 DWORD m;
1989 if (!GetConsoleMode(h, &m)) return 0;
1990# ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
1991# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
1992# endif
1993 if (!(m & ENABLE_VIRTUAL_TERMINAL_PROCESSING)) return 0;
1994 return 1;
1995}
1996#elif !defined(HAVE_WORKING_FORK)
1997# define tty_enabled() 0
1998#endif
1999
2000static VALUE
2001copy_str(VALUE str, rb_encoding *enc, bool intern)
2002{
2003 if (!intern) {
2004 if (rb_enc_str_coderange_scan(str, enc) == ENC_CODERANGE_BROKEN)
2005 return 0;
2006 return rb_enc_associate(rb_str_dup(str), enc);
2007 }
2008 return rb_enc_interned_str(RSTRING_PTR(str), RSTRING_LEN(str), enc);
2009}
2010
2011#if USE_YJIT || USE_ZJIT
2012// Check that an environment variable is set to a truthy value
2013static bool
2014env_var_truthy(const char *name)
2015{
2016 const char *value = getenv(name);
2017
2018 if (!value)
2019 return false;
2020 if (strcmp(value, "1") == 0)
2021 return true;
2022 if (strcmp(value, "true") == 0)
2023 return true;
2024 if (strcmp(value, "yes") == 0)
2025 return true;
2026
2027 return false;
2028}
2029#endif
2030
2031rb_pid_t rb_fork_ruby(int *status);
2032
2033static void
2034show_help(const char *progname, int help)
2035{
2036 int tty = isatty(1);
2037 int columns = 0;
2038 if (help && tty) {
2039 const char *pager_env = getenv("RUBY_PAGER");
2040 if (!pager_env) pager_env = getenv("PAGER");
2041 if (pager_env && *pager_env && isatty(0)) {
2042 const char *columns_env = getenv("COLUMNS");
2043 if (columns_env) columns = atoi(columns_env);
2044 VALUE pager = rb_str_new_cstr(pager_env);
2045#ifdef HAVE_WORKING_FORK
2046 int fds[2];
2047 if (rb_pipe(fds) == 0) {
2048 rb_pid_t pid = rb_fork_ruby(NULL);
2049 if (pid > 0) {
2050 /* exec PAGER with reading from child */
2051 dup2(fds[0], 0);
2052 }
2053 else if (pid == 0) {
2054 /* send the help message to the parent PAGER */
2055 dup2(fds[1], 1);
2056 dup2(fds[1], 2);
2057 }
2058 close(fds[0]);
2059 close(fds[1]);
2060 if (pid > 0) {
2061 setup_pager_env();
2062 rb_f_exec(1, &pager);
2063 kill(SIGTERM, pid);
2064 rb_waitpid(pid, 0, 0);
2065 }
2066 }
2067#else
2068 setup_pager_env();
2069 VALUE port = rb_io_popen(pager, rb_str_new_lit("w"), Qnil, Qnil);
2070 if (!NIL_P(port)) {
2071 int oldout = dup(1);
2072 int olderr = dup(2);
2073 int fd = RFILE(port)->fptr->fd;
2074 tty = tty_enabled();
2075 dup2(fd, 1);
2076 dup2(fd, 2);
2077 usage(progname, 1, tty, columns);
2078 fflush(stdout);
2079 dup2(oldout, 1);
2080 dup2(olderr, 2);
2081 rb_io_close(port);
2082 return;
2083 }
2084#endif
2085 }
2086 }
2087 usage(progname, help, tty, columns);
2088}
2089
2090static VALUE
2091process_script(ruby_cmdline_options_t *opt)
2092{
2093 rb_ast_t *ast;
2094 VALUE ast_value;
2095 VALUE parser = rb_parser_new();
2096 const unsigned int dump = opt->dump;
2097
2098 if (dump & DUMP_BIT(yydebug)) {
2099 rb_parser_set_yydebug(parser, Qtrue);
2100 }
2101
2102 if ((dump & dump_exit_bits) && (dump & DUMP_BIT(opt_error_tolerant))) {
2103 rb_parser_error_tolerant(parser);
2104 }
2105
2106 if (opt->e_script) {
2107 VALUE progname = rb_progname;
2108 rb_parser_set_context(parser, 0, TRUE);
2109
2110 ruby_opt_init(opt);
2111 ruby_set_script_name(progname);
2112 rb_parser_set_options(parser, opt->do_print, opt->do_loop,
2113 opt->do_line, opt->do_split);
2114 ast_value = rb_parser_compile_string(parser, opt->script, opt->e_script, 1);
2115 }
2116 else {
2117 VALUE f;
2118 int xflag = opt->xflag;
2119 f = open_load_file(opt->script_name, &xflag);
2120 opt->xflag = xflag != 0;
2121 rb_parser_set_context(parser, 0, f == rb_stdin);
2122 ast_value = load_file(parser, opt->script_name, f, 1, opt);
2123 }
2124 ast = rb_ruby_ast_data_get(ast_value);
2125 if (!ast->body.root) {
2126 rb_ast_dispose(ast);
2127 return Qnil;
2128 }
2129 return ast_value;
2130}
2131
2132static uint8_t
2133prism_script_command_line(ruby_cmdline_options_t *opt)
2134{
2135 uint8_t command_line = 0;
2136 if (opt->do_split) command_line |= PM_OPTIONS_COMMAND_LINE_A;
2137 if (opt->do_line) command_line |= PM_OPTIONS_COMMAND_LINE_L;
2138 if (opt->do_loop) command_line |= PM_OPTIONS_COMMAND_LINE_N;
2139 if (opt->do_print) command_line |= PM_OPTIONS_COMMAND_LINE_P;
2140 if (opt->xflag) command_line |= PM_OPTIONS_COMMAND_LINE_X;
2141 return command_line;
2142}
2143
2144static void
2145prism_script_shebang_callback(pm_options_t *options, const uint8_t *source, size_t length, void *data)
2146{
2148 opt->warning = 0;
2149
2150 char *switches = malloc(length + 1);
2151 memcpy(switches, source, length);
2152 switches[length] = '\0';
2153
2154 int no_src_enc = !opt->src.enc.name;
2155 int no_ext_enc = !opt->ext.enc.name;
2156 int no_int_enc = !opt->intern.enc.name;
2157
2158 moreswitches(switches, opt, 0);
2159 free(switches);
2160
2161 pm_options_command_line_set(options, prism_script_command_line(opt));
2162
2163 if (no_src_enc && opt->src.enc.name) {
2164 opt->src.enc.index = opt_enc_index(opt->src.enc.name);
2165 pm_options_encoding_set(options, StringValueCStr(opt->ext.enc.name));
2166 }
2167 if (no_ext_enc && opt->ext.enc.name) {
2168 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2169 }
2170 if (no_int_enc && opt->intern.enc.name) {
2171 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
2172 }
2173}
2174
2179static void
2180prism_script(ruby_cmdline_options_t *opt, pm_parse_result_t *result)
2181{
2182 memset(result, 0, sizeof(pm_parse_result_t));
2183
2184 pm_options_t *options = &result->options;
2185 pm_options_line_set(options, 1);
2186 pm_options_main_script_set(options, true);
2187
2188 const bool read_stdin = (strcmp(opt->script, "-") == 0);
2189
2190 if (read_stdin) {
2191 pm_options_encoding_set(options, rb_enc_name(rb_locale_encoding()));
2192 }
2193 if (opt->src.enc.name != 0) {
2194 pm_options_encoding_set(options, StringValueCStr(opt->src.enc.name));
2195 }
2196
2197 uint8_t command_line = prism_script_command_line(opt);
2198 VALUE error;
2199
2200 if (read_stdin) {
2201 pm_options_command_line_set(options, command_line);
2202 pm_options_filepath_set(options, "-");
2203 pm_options_shebang_callback_set(options, prism_script_shebang_callback, (void *) opt);
2204
2205 ruby_opt_init(opt);
2206 error = pm_parse_stdin(result);
2207
2208 // If we found an __END__ marker, then we're going to define a global
2209 // DATA constant that is a file object that can be read to read the
2210 // contents after the marker.
2211 if (NIL_P(error) && result->parser.data_loc.start != NULL) {
2213 }
2214 }
2215 else if (opt->e_script) {
2216 command_line = (uint8_t) ((command_line | PM_OPTIONS_COMMAND_LINE_E) & ~PM_OPTIONS_COMMAND_LINE_X);
2217 pm_options_command_line_set(options, command_line);
2218
2219 ruby_opt_init(opt);
2220 result->node.coverage_enabled = 0;
2221 error = pm_parse_string(result, opt->e_script, rb_str_new2("-e"), NULL);
2222 }
2223 else {
2224 VALUE script_name = rb_str_encode_ospath(opt->script_name);
2225
2226 pm_options_command_line_set(options, command_line);
2227 pm_options_shebang_callback_set(options, prism_script_shebang_callback, (void *) opt);
2228
2229 error = pm_load_file(result, script_name, true);
2230
2231 // If reading the file did not error, at that point we load the command
2232 // line options. We do it in this order so that if the main script fails
2233 // to load, it doesn't require files required by -r.
2234 if (NIL_P(error)) {
2235 ruby_opt_init(opt);
2236 error = pm_parse_file(result, opt->script_name, NULL);
2237 }
2238
2239 // Check if (after requiring all of the files through -r flags) we have
2240 // coverage enabled and need to enable coverage on the main script.
2241 if (RTEST(rb_get_coverages())) {
2242 result->node.coverage_enabled = 1;
2243 }
2244
2245 // If we found an __END__ marker, then we're going to define a global
2246 // DATA constant that is a file object that can be read to read the
2247 // contents after the marker.
2248 if (NIL_P(error) && result->parser.data_loc.start != NULL) {
2249 int xflag = opt->xflag;
2250 VALUE file = open_load_file(script_name, &xflag);
2251
2252 const pm_parser_t *parser = &result->parser;
2253 size_t offset = parser->data_loc.start - parser->start + 7;
2254
2255 if ((parser->start + offset < parser->end) && parser->start[offset] == '\r') offset++;
2256 if ((parser->start + offset < parser->end) && parser->start[offset] == '\n') offset++;
2257
2258 rb_funcall(file, rb_intern_const("seek"), 2, SIZET2NUM(offset), INT2FIX(SEEK_SET));
2259 rb_define_global_const("DATA", file);
2260 }
2261 }
2262
2263 if (!NIL_P(error)) {
2264 pm_parse_result_free(result);
2265 rb_exc_raise(error);
2266 }
2267}
2268
2269static VALUE
2270prism_dump_tree(pm_parse_result_t *result)
2271{
2272 pm_buffer_t output_buffer = { 0 };
2273
2274 pm_prettyprint(&output_buffer, &result->parser, result->node.ast_node);
2275 VALUE tree = rb_str_new(output_buffer.value, output_buffer.length);
2276 pm_buffer_free(&output_buffer);
2277 return tree;
2278}
2279
2280static void
2281process_options_global_setup(const ruby_cmdline_options_t *opt, const rb_iseq_t *iseq)
2282{
2283 if (OPT_BACKTRACE_LENGTH_LIMIT_VALID_P(opt)) {
2284 rb_backtrace_length_limit = opt->backtrace_length_limit;
2285 }
2286
2287 if (opt->do_loop) {
2288 rb_define_global_function("sub", rb_f_sub, -1);
2289 rb_define_global_function("gsub", rb_f_gsub, -1);
2290 rb_define_global_function("chop", rb_f_chop, 0);
2291 rb_define_global_function("chomp", rb_f_chomp, -1);
2292 }
2293
2294 rb_define_readonly_boolean("$-p", opt->do_print);
2295 rb_define_readonly_boolean("$-l", opt->do_line);
2296 rb_define_readonly_boolean("$-a", opt->do_split);
2297
2298 rb_gvar_ractor_local("$-p");
2299 rb_gvar_ractor_local("$-l");
2300 rb_gvar_ractor_local("$-a");
2301
2302 if ((rb_e_script = opt->e_script) != 0) {
2303 rb_str_freeze(rb_e_script);
2304 rb_vm_register_global_object(opt->e_script);
2305 }
2306
2307 rb_execution_context_t *ec = GET_EC();
2308 VALUE script = (opt->e_script ? opt->e_script : Qnil);
2309 rb_exec_event_hook_script_compiled(ec, iseq, script);
2310}
2311
2312static VALUE
2313process_options(int argc, char **argv, ruby_cmdline_options_t *opt)
2314{
2315 VALUE ast_value = Qnil;
2316 struct {
2317 rb_ast_t *ast;
2318 pm_parse_result_t prism;
2319 } result = {0};
2320#define dispose_result() \
2321 (result.ast ? rb_ast_dispose(result.ast) : pm_parse_result_free(&result.prism))
2322
2323 const rb_iseq_t *iseq;
2324 rb_encoding *enc, *lenc;
2325#if UTF8_PATH
2326 rb_encoding *ienc = 0;
2327 rb_encoding *const uenc = rb_utf8_encoding();
2328#endif
2329 const char *s;
2330 char fbuf[MAXPATHLEN];
2331 int i = (int)proc_options(argc, argv, opt, 0);
2332 unsigned int dump = opt->dump & dump_exit_bits;
2333 rb_vm_t *vm = GET_VM();
2334 const long loaded_before_enc = RARRAY_LEN(vm->loaded_features);
2335
2336 if (opt->dump & (DUMP_BIT(usage)|DUMP_BIT(help))) {
2337 const char *const progname =
2338 (argc > 0 && argv && argv[0] ? argv[0] :
2339 origarg.argc > 0 && origarg.argv && origarg.argv[0] ? origarg.argv[0] :
2340 ruby_engine);
2341 show_help(progname, (opt->dump & DUMP_BIT(help)));
2342 return Qtrue;
2343 }
2344
2345 argc -= i;
2346 argv += i;
2347
2348 if (FEATURE_SET_P(opt->features, rubyopt) && (s = getenv("RUBYOPT"))) {
2349 moreswitches(s, opt, 1);
2350 }
2351
2352 if (opt->src.enc.name)
2353 /* cannot set deprecated category, as enabling deprecation warnings based on flags
2354 * has not happened yet.
2355 */
2356 rb_warning("-K is specified; it is for 1.8 compatibility and may cause odd behavior");
2357
2358 if (!(FEATURE_SET_BITS(opt->features) & feature_jit_mask)) {
2359#if USE_YJIT
2360 if (!FEATURE_USED_P(opt->features, yjit) && env_var_truthy("RUBY_YJIT_ENABLE")) {
2361 FEATURE_SET(opt->features, FEATURE_BIT(yjit));
2362 }
2363#elif USE_ZJIT
2364 if (!FEATURE_USED_P(opt->features, zjit) && env_var_truthy("RUBY_ZJIT_ENABLE")) {
2365 FEATURE_SET(opt->features, FEATURE_BIT(zjit));
2366 }
2367#endif
2368 }
2369 if (MULTI_BITS_P(FEATURE_SET_BITS(opt->features) & feature_jit_mask)) {
2370 rb_warn("Only one JIT can be enabled at the same time. Exiting");
2371 return Qfalse;
2372 }
2373
2374#if USE_YJIT
2375 if (FEATURE_SET_P(opt->features, yjit)) {
2376 bool rb_yjit_option_disable(void);
2377 opt->yjit = !rb_yjit_option_disable(); // set opt->yjit for Init_ruby_description() and calling rb_yjit_init()
2378 }
2379#endif
2380#if USE_ZJIT
2381 if (FEATURE_SET_P(opt->features, zjit) && !opt->zjit) {
2382 extern void *rb_zjit_init_options(void);
2383 opt->zjit = rb_zjit_init_options();
2384 }
2385#endif
2386
2387 ruby_mn_threads_params();
2388 Init_ruby_description(opt);
2389
2390 if (opt->dump & (DUMP_BIT(version) | DUMP_BIT(version_v))) {
2392 if (opt->dump & DUMP_BIT(version)) return Qtrue;
2393 }
2394 if (opt->dump & DUMP_BIT(copyright)) {
2396 return Qtrue;
2397 }
2398
2399 if (!opt->e_script) {
2400 if (argc <= 0) { /* no more args */
2401 if (opt->verbose)
2402 return Qtrue;
2403 opt->script = "-";
2404 }
2405 else {
2406 opt->script = argv[0];
2407 if (!opt->script || opt->script[0] == '\0') {
2408 opt->script = "-";
2409 }
2410 else if (opt->do_search) {
2411 const char *path = getenv("RUBYPATH");
2412
2413 opt->script = 0;
2414 if (path) {
2415 opt->script = dln_find_file_r(argv[0], path, fbuf, sizeof(fbuf));
2416 }
2417 if (!opt->script) {
2418 opt->script = dln_find_file_r(argv[0], getenv(PATH_ENV), fbuf, sizeof(fbuf));
2419 }
2420 if (!opt->script)
2421 opt->script = argv[0];
2422 }
2423 argc--;
2424 argv++;
2425 }
2426 if (opt->script[0] == '-' && !opt->script[1]) {
2427 forbid_setid("program input from stdin");
2428 }
2429 }
2430
2431 opt->script_name = rb_str_new_cstr(opt->script);
2432 opt->script = RSTRING_PTR(opt->script_name);
2433
2434#ifdef _WIN32
2435 translit_char_bin(RSTRING_PTR(opt->script_name), '\\', '/');
2436#endif
2437
2438 ruby_gc_set_params();
2440
2441 Init_enc();
2442 lenc = rb_locale_encoding();
2443 rb_enc_associate(rb_progname, lenc);
2444 rb_obj_freeze(rb_progname);
2445 if (opt->ext.enc.name != 0) {
2446 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2447 }
2448 if (opt->intern.enc.name != 0) {
2449 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
2450 }
2451 if (opt->src.enc.name != 0) {
2452 opt->src.enc.index = opt_enc_index(opt->src.enc.name);
2453 src_encoding_index = opt->src.enc.index;
2454 }
2455 if (opt->ext.enc.index >= 0) {
2456 enc = rb_enc_from_index(opt->ext.enc.index);
2457 }
2458 else {
2459 enc = IF_UTF8_PATH(uenc, lenc);
2460 }
2461 rb_enc_set_default_external(rb_enc_from_encoding(enc));
2462 if (opt->intern.enc.index >= 0) {
2463 enc = rb_enc_from_index(opt->intern.enc.index);
2464 rb_enc_set_default_internal(rb_enc_from_encoding(enc));
2465 opt->intern.enc.index = -1;
2466#if UTF8_PATH
2467 ienc = enc;
2468#endif
2469 }
2470 rb_enc_associate(opt->script_name, IF_UTF8_PATH(uenc, lenc));
2471#if UTF8_PATH
2472 if (uenc != lenc) {
2473 opt->script_name = str_conv_enc(opt->script_name, uenc, lenc);
2474 opt->script = RSTRING_PTR(opt->script_name);
2475 }
2476#endif
2477 rb_obj_freeze(opt->script_name);
2478 if (IF_UTF8_PATH(uenc != lenc, 1)) {
2479 long i;
2480 VALUE load_path = vm->load_path;
2481 const ID id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK;
2482 int modifiable = FALSE;
2483
2484 rb_get_expanded_load_path();
2485 for (i = 0; i < RARRAY_LEN(load_path); ++i) {
2486 VALUE path = RARRAY_AREF(load_path, i);
2487 int mark = rb_attr_get(path, id_initial_load_path_mark) == path;
2488#if UTF8_PATH
2489 VALUE newpath = rb_str_conv_enc(path, uenc, lenc);
2490 if (newpath == path) continue;
2491 path = newpath;
2492#else
2493 if (!(path = copy_str(path, lenc, !mark))) continue;
2494#endif
2495 if (mark) rb_ivar_set(path, id_initial_load_path_mark, path);
2496 if (!modifiable) {
2497 rb_ary_modify(load_path);
2498 modifiable = TRUE;
2499 }
2500 RARRAY_ASET(load_path, i, path);
2501 }
2502 if (modifiable) {
2503 rb_ary_replace(vm->load_path_snapshot, load_path);
2504 }
2505 }
2506 {
2507 VALUE loaded_features = vm->loaded_features;
2508 bool modified = false;
2509 for (long i = loaded_before_enc; i < RARRAY_LEN(loaded_features); ++i) {
2510 VALUE path = RARRAY_AREF(loaded_features, i);
2511 if (!(path = copy_str(path, IF_UTF8_PATH(uenc, lenc), true))) continue;
2512 if (!modified) {
2513 rb_ary_modify(loaded_features);
2514 modified = true;
2515 }
2516 RARRAY_ASET(loaded_features, i, path);
2517 }
2518 if (modified) {
2519 rb_ary_replace(vm->loaded_features_snapshot, loaded_features);
2520 }
2521 }
2522
2523 if (opt->features.mask & COMPILATION_FEATURES) {
2524 VALUE option = rb_hash_new();
2525#define SET_COMPILE_OPTION(h, o, name) \
2526 rb_hash_aset((h), ID2SYM(rb_intern_const(#name)), \
2527 RBOOL(FEATURE_SET_P(o->features, name)))
2528
2529 if (FEATURE_SET_P(opt->features, frozen_string_literal_set)) {
2530 SET_COMPILE_OPTION(option, opt, frozen_string_literal);
2531 }
2532 SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal);
2533 rb_funcallv(rb_cISeq, rb_intern_const("compile_option="), 1, &option);
2534#undef SET_COMPILE_OPTION
2535 }
2536 ruby_set_argv(argc, argv);
2537 opt->sflag = process_sflag(opt->sflag);
2538
2539 if (opt->e_script) {
2540 rb_encoding *eenc;
2541 if (opt->src.enc.index >= 0) {
2542 eenc = rb_enc_from_index(opt->src.enc.index);
2543 }
2544 else {
2545 eenc = lenc;
2546#if UTF8_PATH
2547 if (ienc) eenc = ienc;
2548#endif
2549 }
2550#if UTF8_PATH
2551 if (eenc != uenc) {
2552 opt->e_script = str_conv_enc(opt->e_script, uenc, eenc);
2553 }
2554#endif
2555 rb_enc_associate(opt->e_script, eenc);
2556 }
2557
2558 if (!rb_ruby_prism_p()) {
2559 ast_value = process_script(opt);
2560 if (!(result.ast = rb_ruby_ast_data_get(ast_value))) return Qfalse;
2561 }
2562 else {
2563 prism_script(opt, &result.prism);
2564 }
2565 ruby_set_script_name(opt->script_name);
2566 if ((dump & DUMP_BIT(yydebug)) && !(dump &= ~DUMP_BIT(yydebug))) {
2567 dispose_result();
2568 return Qtrue;
2569 }
2570
2571 if (opt->ext.enc.index >= 0) {
2572 enc = rb_enc_from_index(opt->ext.enc.index);
2573 }
2574 else {
2575 enc = IF_UTF8_PATH(uenc, lenc);
2576 }
2577 rb_enc_set_default_external(rb_enc_from_encoding(enc));
2578 if (opt->intern.enc.index >= 0) {
2579 /* Set in the shebang line */
2580 enc = rb_enc_from_index(opt->intern.enc.index);
2581 rb_enc_set_default_internal(rb_enc_from_encoding(enc));
2582 }
2583 else if (!rb_default_internal_encoding())
2584 /* Freeze default_internal */
2585 rb_enc_set_default_internal(Qnil);
2586 rb_stdio_set_default_encoding();
2587
2588 opt->sflag = process_sflag(opt->sflag);
2589 opt->xflag = 0;
2590
2591 if (dump & DUMP_BIT(syntax)) {
2592 printf("Syntax OK\n");
2593 dump &= ~DUMP_BIT(syntax);
2594 if (!dump) {
2595 dispose_result();
2596 return Qtrue;
2597 }
2598 }
2599
2600 if (dump & DUMP_BIT(parsetree)) {
2601 VALUE tree;
2602 if (result.ast) {
2603 int comment = opt->dump & DUMP_BIT(opt_comment);
2604 tree = rb_parser_dump_tree(result.ast->body.root, comment);
2605 }
2606 else {
2607 tree = prism_dump_tree(&result.prism);
2608 }
2609 rb_io_write(rb_stdout, tree);
2610 rb_io_flush(rb_stdout);
2611 dump &= ~DUMP_BIT(parsetree);
2612 if (!dump) {
2613 dispose_result();
2614 return Qtrue;
2615 }
2616 }
2617
2618 {
2619 VALUE path = Qnil;
2620 if (!opt->e_script && strcmp(opt->script, "-")) {
2621 path = rb_realpath_internal(Qnil, opt->script_name, 1);
2622#if UTF8_PATH
2623 if (uenc != lenc) {
2624 path = str_conv_enc(path, uenc, lenc);
2625 }
2626#endif
2627 if (!ENCODING_GET(path)) { /* ASCII-8BIT */
2628 rb_enc_copy(path, opt->script_name);
2629 }
2630 }
2631
2632 rb_binding_t *toplevel_binding;
2633 GetBindingPtr(rb_const_get(rb_cObject, rb_intern("TOPLEVEL_BINDING")), toplevel_binding);
2634 const struct rb_block *base_block = toplevel_context(toplevel_binding);
2635 const rb_iseq_t *parent = vm_block_iseq(base_block);
2636 bool optimize = (opt->dump & DUMP_BIT(opt_optimize)) != 0;
2637
2638 if (!result.ast) {
2639 pm_parse_result_t *pm = &result.prism;
2640 int error_state;
2641 iseq = pm_iseq_new_main(&pm->node, opt->script_name, path, parent, optimize, &error_state);
2642
2643 pm_parse_result_free(pm);
2644
2645 if (error_state) {
2646 RUBY_ASSERT(iseq == NULL);
2647 rb_jump_tag(error_state);
2648 }
2649 }
2650 else {
2651 rb_ast_t *ast = result.ast;
2652 iseq = rb_iseq_new_main(ast_value, opt->script_name, path, parent, optimize);
2653 rb_ast_dispose(ast);
2654 }
2655 }
2656
2657 if (dump & DUMP_BIT(insns)) {
2658 rb_io_write(rb_stdout, rb_iseq_disasm((const rb_iseq_t *)iseq));
2659 rb_io_flush(rb_stdout);
2660 dump &= ~DUMP_BIT(insns);
2661 if (!dump) return Qtrue;
2662 }
2663 if (opt->dump & dump_exit_bits) return Qtrue;
2664
2665 process_options_global_setup(opt, iseq);
2666 return (VALUE)iseq;
2667}
2668
2669#ifndef DOSISH
2670static void
2671warn_cr_in_shebang(const char *str, long len)
2672{
2673 if (len > 1 && str[len-1] == '\n' && str[len-2] == '\r') {
2674 rb_warn("shebang line ending with \\r may cause problems");
2675 }
2676}
2677#else
2678#define warn_cr_in_shebang(str, len) (void)0
2679#endif
2680
2681void rb_reset_argf_lineno(long n);
2682
2684 VALUE parser;
2685 VALUE fname;
2686 int script;
2688 VALUE f;
2689};
2690
2691void rb_set_script_lines_for(VALUE vparser, VALUE path);
2692
2693static VALUE
2694load_file_internal(VALUE argp_v)
2695{
2696 struct load_file_arg *argp = (struct load_file_arg *)argp_v;
2697 VALUE parser = argp->parser;
2698 VALUE orig_fname = argp->fname;
2699 int script = argp->script;
2700 ruby_cmdline_options_t *opt = argp->opt;
2701 VALUE f = argp->f;
2702 int line_start = 1;
2703 VALUE ast_value = Qnil;
2704 rb_encoding *enc;
2705 ID set_encoding;
2706
2707 CONST_ID(set_encoding, "set_encoding");
2708 if (script) {
2709 VALUE c = 1; /* something not nil */
2710 VALUE line;
2711 char *p, *str;
2712 long len;
2713 int no_src_enc = !opt->src.enc.name;
2714 int no_ext_enc = !opt->ext.enc.name;
2715 int no_int_enc = !opt->intern.enc.name;
2716
2717 enc = rb_ascii8bit_encoding();
2718 rb_funcall(f, set_encoding, 1, rb_enc_from_encoding(enc));
2719
2720 if (opt->xflag) {
2721 line_start--;
2722 search_shebang:
2723 while (!NIL_P(line = rb_io_gets(f))) {
2724 line_start++;
2725 RSTRING_GETMEM(line, str, len);
2726 if (len > 2 && str[0] == '#' && str[1] == '!') {
2727 if (line_start == 1) warn_cr_in_shebang(str, len);
2728 if ((p = strstr(str+2, ruby_engine)) != 0) {
2729 goto start_read;
2730 }
2731 }
2732 }
2733 rb_loaderror("no Ruby script found in input");
2734 }
2735
2736 c = rb_io_getbyte(f);
2737 if (c == INT2FIX('#')) {
2738 c = rb_io_getbyte(f);
2739 if (c == INT2FIX('!') && !NIL_P(line = rb_io_gets(f))) {
2740 RSTRING_GETMEM(line, str, len);
2741 warn_cr_in_shebang(str, len);
2742 if ((p = strstr(str, ruby_engine)) == 0) {
2743 /* not ruby script, assume -x flag */
2744 goto search_shebang;
2745 }
2746
2747 start_read:
2748 str += len - 1;
2749 if (*str == '\n') *str-- = '\0';
2750 if (*str == '\r') *str-- = '\0';
2751 /* ruby_engine should not contain a space */
2752 if ((p = strstr(p, " -")) != 0) {
2753 opt->warning = 0;
2754 moreswitches(p + 1, opt, 0);
2755 }
2756
2757 /* push back shebang for pragma may exist in next line */
2758 rb_io_ungetbyte(f, rb_str_new2("!\n"));
2759 }
2760 else if (!NIL_P(c)) {
2761 rb_io_ungetbyte(f, c);
2762 }
2763 rb_io_ungetbyte(f, INT2FIX('#'));
2764 if (no_src_enc && opt->src.enc.name) {
2765 opt->src.enc.index = opt_enc_index(opt->src.enc.name);
2766 src_encoding_index = opt->src.enc.index;
2767 }
2768 if (no_ext_enc && opt->ext.enc.name) {
2769 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2770 }
2771 if (no_int_enc && opt->intern.enc.name) {
2772 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
2773 }
2774 }
2775 else if (!NIL_P(c)) {
2776 rb_io_ungetbyte(f, c);
2777 }
2778 if (NIL_P(c)) {
2779 argp->f = f = Qnil;
2780 }
2781 rb_reset_argf_lineno(0);
2782 ruby_opt_init(opt);
2783 }
2784 if (opt->src.enc.index >= 0) {
2785 enc = rb_enc_from_index(opt->src.enc.index);
2786 }
2787 else if (f == rb_stdin) {
2788 enc = rb_locale_encoding();
2789 }
2790 else {
2791 enc = rb_utf8_encoding();
2792 }
2793 rb_parser_set_options(parser, opt->do_print, opt->do_loop,
2794 opt->do_line, opt->do_split);
2795
2796 rb_set_script_lines_for(parser, orig_fname);
2797
2798 if (NIL_P(f)) {
2799 f = rb_str_new(0, 0);
2800 rb_enc_associate(f, enc);
2801 return rb_parser_compile_string_path(parser, orig_fname, f, line_start);
2802 }
2803 rb_funcall(f, set_encoding, 2, rb_enc_from_encoding(enc), rb_str_new_cstr("-"));
2804 ast_value = rb_parser_compile_file_path(parser, orig_fname, f, line_start);
2805 rb_funcall(f, set_encoding, 1, rb_parser_encoding(parser));
2806 if (script && rb_parser_end_seen_p(parser)) {
2807 /*
2808 * DATA is a File that contains the data section of the executed file.
2809 * To create a data section use <tt>__END__</tt>:
2810 *
2811 * $ cat t.rb
2812 * puts DATA.gets
2813 * __END__
2814 * hello world!
2815 *
2816 * $ ruby t.rb
2817 * hello world!
2818 */
2819 rb_define_global_const("DATA", f);
2820 argp->f = Qnil;
2821 }
2822 return ast_value;
2823}
2824
2825/* disabling O_NONBLOCK, and returns 0 on success, otherwise errno */
2826static inline int
2827disable_nonblock(int fd)
2828{
2829#if defined(HAVE_FCNTL) && defined(F_SETFL)
2830 if (fcntl(fd, F_SETFL, 0) < 0) {
2831 const int e = errno;
2832 ASSUME(e != 0);
2833# if defined ENOTSUP
2834 if (e == ENOTSUP) return 0;
2835# endif
2836# if defined B_UNSUPPORTED
2837 if (e == B_UNSUPPORTED) return 0;
2838# endif
2839 return e;
2840 }
2841#endif
2842 return 0;
2843}
2844
2845static VALUE
2846open_load_file(VALUE fname_v, int *xflag)
2847{
2848 const char *fname = (fname_v = rb_str_encode_ospath(fname_v),
2849 StringValueCStr(fname_v));
2850 long flen = RSTRING_LEN(fname_v);
2851 VALUE f;
2852 int e;
2853
2854 if (flen == 1 && fname[0] == '-') {
2855 f = rb_stdin;
2856 }
2857 else {
2858 int fd;
2859 /* open(2) may block if fname is point to FIFO and it's empty. Let's
2860 use O_NONBLOCK. */
2861 const int MODE_TO_LOAD = O_RDONLY | (
2862#if defined O_NONBLOCK && HAVE_FCNTL
2863 /* TODO: fix conflicting O_NONBLOCK in ruby/win32.h */
2864 !(O_NONBLOCK & O_ACCMODE) ? O_NONBLOCK :
2865#endif
2866#if defined O_NDELAY && HAVE_FCNTL
2867 !(O_NDELAY & O_ACCMODE) ? O_NDELAY :
2868#endif
2869 0);
2870 int mode = MODE_TO_LOAD;
2871#if defined DOSISH || defined __CYGWIN__
2872# define isdirsep(x) ((x) == '/' || (x) == '\\')
2873 {
2874 static const char exeext[] = ".exe";
2875 enum {extlen = sizeof(exeext)-1};
2876 if (flen > extlen && !isdirsep(fname[flen-extlen-1]) &&
2877 STRNCASECMP(fname+flen-extlen, exeext, extlen) == 0) {
2878 mode |= O_BINARY;
2879 *xflag = 1;
2880 }
2881 }
2882#endif
2883
2884 if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) {
2885 e = errno;
2886 if (!rb_gc_for_fd(e)) {
2887 rb_load_fail(fname_v, strerror(e));
2888 }
2889 if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) {
2890 rb_load_fail(fname_v, strerror(errno));
2891 }
2892 }
2893 rb_update_max_fd(fd);
2894
2895 if (MODE_TO_LOAD != O_RDONLY && (e = disable_nonblock(fd)) != 0) {
2896 (void)close(fd);
2897 rb_load_fail(fname_v, strerror(e));
2898 }
2899
2900 e = ruby_is_fd_loadable(fd);
2901 if (!e) {
2902 e = errno;
2903 (void)close(fd);
2904 rb_load_fail(fname_v, strerror(e));
2905 }
2906
2907 f = rb_io_fdopen(fd, mode, fname);
2908 if (e < 0) {
2909 /*
2910 We need to wait if FIFO is empty. It's FIFO's semantics.
2911 rb_thread_wait_fd() release GVL. So, it's safe.
2912 */
2914 }
2915 }
2916 return f;
2917}
2918
2919static VALUE
2920restore_load_file(VALUE arg)
2921{
2922 struct load_file_arg *argp = (struct load_file_arg *)arg;
2923 VALUE f = argp->f;
2924
2925 if (!NIL_P(f) && f != rb_stdin) {
2926 rb_io_close(f);
2927 }
2928 return Qnil;
2929}
2930
2931static VALUE
2932load_file(VALUE parser, VALUE fname, VALUE f, int script, ruby_cmdline_options_t *opt)
2933{
2934 struct load_file_arg arg;
2935 arg.parser = parser;
2936 arg.fname = fname;
2937 arg.script = script;
2938 arg.opt = opt;
2939 arg.f = f;
2940 return rb_ensure(load_file_internal, (VALUE)&arg,
2941 restore_load_file, (VALUE)&arg);
2942}
2943
2944void *
2945rb_load_file(const char *fname)
2946{
2947 VALUE fname_v = rb_str_new_cstr(fname);
2948 return rb_load_file_str(fname_v);
2949}
2950
2951void *
2953{
2954 VALUE ast_value;
2955 ast_value = rb_parser_load_file(rb_parser_new(), fname_v);
2956 return (void *)rb_ruby_ast_data_get(ast_value);
2957}
2958
2959VALUE
2960rb_parser_load_file(VALUE parser, VALUE fname_v)
2961{
2963 int xflag = 0;
2964 VALUE f = open_load_file(fname_v, &xflag);
2965 cmdline_options_init(&opt)->xflag = xflag != 0;
2966 return load_file(parser, fname_v, f, 0, &opt);
2967}
2968
2969/*
2970 * call-seq:
2971 * Process.argv0 -> frozen_string
2972 *
2973 * Returns the name of the script being executed. The value is not
2974 * affected by assigning a new value to $0.
2975 *
2976 * This method first appeared in Ruby 2.1 to serve as a global
2977 * variable free means to get the script name.
2978 */
2979
2980static VALUE
2981proc_argv0(VALUE process)
2982{
2983 return rb_orig_progname;
2984}
2985
2986static VALUE ruby_setproctitle(VALUE title);
2987
2988/*
2989 * call-seq:
2990 * Process.setproctitle(string) -> string
2991 *
2992 * Sets the process title that appears on the ps(1) command. Not
2993 * necessarily effective on all platforms. No exception will be
2994 * raised regardless of the result, nor will NotImplementedError be
2995 * raised even if the platform does not support the feature.
2996 *
2997 * Calling this method does not affect the value of $0.
2998 *
2999 * Process.setproctitle('myapp: worker #%d' % worker_id)
3000 *
3001 * This method first appeared in Ruby 2.1 to serve as a global
3002 * variable free means to change the process title.
3003 */
3004
3005static VALUE
3006proc_setproctitle(VALUE process, VALUE title)
3007{
3008 return ruby_setproctitle(title);
3009}
3010
3011static VALUE
3012ruby_setproctitle(VALUE title)
3013{
3014 const char *ptr = StringValueCStr(title);
3015 setproctitle("%.*s", RSTRING_LENINT(title), ptr);
3016 return title;
3017}
3018
3019static void
3020set_arg0(VALUE val, ID id, VALUE *_)
3021{
3022 if (origarg.argv == 0)
3023 rb_raise(rb_eRuntimeError, "$0 not initialized");
3024
3025 rb_progname = rb_str_new_frozen(ruby_setproctitle(val));
3026}
3027
3028static inline VALUE
3029external_str_new_cstr(const char *p)
3030{
3031#if UTF8_PATH
3032 VALUE str = rb_utf8_str_new_cstr(p);
3033 str = str_conv_enc(str, NULL, rb_default_external_encoding());
3034 return str;
3035#else
3036 return rb_external_str_new_cstr(p);
3037#endif
3038}
3039
3040static void
3041set_progname(VALUE name)
3042{
3043 rb_orig_progname = rb_progname = name;
3044 rb_vm_set_progname(rb_progname);
3045}
3046
3047void
3048ruby_script(const char *name)
3049{
3050 if (name) {
3051 set_progname(rb_str_freeze(external_str_new_cstr(name)));
3052 }
3053}
3054
3059void
3061{
3062 set_progname(rb_str_new_frozen(name));
3063}
3064
3065static void
3066init_ids(ruby_cmdline_options_t *opt)
3067{
3068 rb_uid_t uid = getuid();
3069 rb_uid_t euid = geteuid();
3070 rb_gid_t gid = getgid();
3071 rb_gid_t egid = getegid();
3072
3073 if (uid != euid) opt->setids |= 1;
3074 if (egid != gid) opt->setids |= 2;
3075}
3076
3077#undef forbid_setid
3078static void
3079forbid_setid(const char *s, const ruby_cmdline_options_t *opt)
3080{
3081 if (opt->setids & 1)
3082 rb_raise(rb_eSecurityError, "no %s allowed while running setuid", s);
3083 if (opt->setids & 2)
3084 rb_raise(rb_eSecurityError, "no %s allowed while running setgid", s);
3085}
3086
3087static VALUE
3088verbose_getter(ID id, VALUE *ptr)
3089{
3090 return *rb_ruby_verbose_ptr();
3091}
3092
3093static void
3094verbose_setter(VALUE val, ID id, VALUE *variable)
3095{
3096 *rb_ruby_verbose_ptr() = RTEST(val) ? Qtrue : val;
3097}
3098
3099static VALUE
3100opt_W_getter(ID id, VALUE *dmy)
3101{
3102 VALUE v = *rb_ruby_verbose_ptr();
3103
3104 switch (v) {
3105 case Qnil:
3106 return INT2FIX(0);
3107 case Qfalse:
3108 return INT2FIX(1);
3109 case Qtrue:
3110 return INT2FIX(2);
3111 default:
3112 return Qnil;
3113 }
3114}
3115
3116static VALUE
3117debug_getter(ID id, VALUE *dmy)
3118{
3119 return *rb_ruby_debug_ptr();
3120}
3121
3122static void
3123debug_setter(VALUE val, ID id, VALUE *dmy)
3124{
3125 *rb_ruby_debug_ptr() = val;
3126}
3127
3128void
3130{
3131 rb_define_virtual_variable("$VERBOSE", verbose_getter, verbose_setter);
3132 rb_define_virtual_variable("$-v", verbose_getter, verbose_setter);
3133 rb_define_virtual_variable("$-w", verbose_getter, verbose_setter);
3135 rb_define_virtual_variable("$DEBUG", debug_getter, debug_setter);
3136 rb_define_virtual_variable("$-d", debug_getter, debug_setter);
3137
3138 rb_gvar_ractor_local("$VERBOSE");
3139 rb_gvar_ractor_local("$-v");
3140 rb_gvar_ractor_local("$-w");
3141 rb_gvar_ractor_local("$-W");
3142 rb_gvar_ractor_local("$DEBUG");
3143 rb_gvar_ractor_local("$-d");
3144
3145 rb_define_hooked_variable("$0", &rb_progname, 0, set_arg0);
3146 rb_define_hooked_variable("$PROGRAM_NAME", &rb_progname, 0, set_arg0);
3147
3148 rb_define_module_function(rb_mProcess, "argv0", proc_argv0, 0);
3149 rb_define_module_function(rb_mProcess, "setproctitle", proc_setproctitle, 1);
3150
3151 /*
3152 * ARGV contains the command line arguments used to run ruby.
3153 *
3154 * A library like OptionParser can be used to process command-line
3155 * arguments.
3156 */
3158}
3159
3160void
3161ruby_set_argv(int argc, char **argv)
3162{
3163 int i;
3164 VALUE av = rb_argv;
3165
3166 rb_ary_clear(av);
3167 for (i = 0; i < argc; i++) {
3168 VALUE arg = external_str_new_cstr(argv[i]);
3169
3170 OBJ_FREEZE(arg);
3171 rb_ary_push(av, arg);
3172 }
3173}
3174
3175void *
3176ruby_process_options(int argc, char **argv)
3177{
3179 VALUE iseq;
3180 const char *script_name = (argc > 0 && argv[0]) ? argv[0] : ruby_engine;
3181
3182 if (!origarg.argv || origarg.argc <= 0) {
3183 origarg.argc = argc;
3184 origarg.argv = argv;
3185 }
3186 set_progname(external_str_new_cstr(script_name)); /* for the time being */
3187 rb_argv0 = rb_str_new4(rb_progname);
3188 rb_vm_register_global_object(rb_argv0);
3189
3190#ifndef HAVE_SETPROCTITLE
3191 ruby_init_setproctitle(argc, argv);
3192#endif
3193
3194 if (getenv("RUBY_FREE_AT_EXIT")) {
3195 rb_free_at_exit = true;
3196 rb_category_warn(RB_WARN_CATEGORY_EXPERIMENTAL, "Free at exit is experimental and may be unstable");
3197 }
3198
3199 iseq = process_options(argc, argv, cmdline_options_init(&opt));
3200
3201 if (opt.crash_report && *opt.crash_report) {
3202 void ruby_set_crash_report(const char *template);
3203 ruby_set_crash_report(opt.crash_report);
3204 }
3205
3206 return (void*)(struct RData*)iseq;
3207}
3208
3209static void
3210fill_standard_fds(void)
3211{
3212 int f0, f1, f2, fds[2];
3213 struct stat buf;
3214 f0 = fstat(0, &buf) == -1 && errno == EBADF;
3215 f1 = fstat(1, &buf) == -1 && errno == EBADF;
3216 f2 = fstat(2, &buf) == -1 && errno == EBADF;
3217 if (f0) {
3218 if (pipe(fds) == 0) {
3219 close(fds[1]);
3220 if (fds[0] != 0) {
3221 dup2(fds[0], 0);
3222 close(fds[0]);
3223 }
3224 }
3225 }
3226 if (f1 || f2) {
3227 if (pipe(fds) == 0) {
3228 close(fds[0]);
3229 if (f1 && fds[1] != 1)
3230 dup2(fds[1], 1);
3231 if (f2 && fds[1] != 2)
3232 dup2(fds[1], 2);
3233 if (fds[1] != 1 && fds[1] != 2)
3234 close(fds[1]);
3235 }
3236 }
3237}
3238
3239void
3240ruby_sysinit(int *argc, char ***argv)
3241{
3242#if defined(_WIN32)
3243 rb_w32_sysinit(argc, argv);
3244#endif
3245 if (*argc >= 0 && *argv) {
3246 origarg.argc = *argc;
3247 origarg.argv = *argv;
3248 }
3249 fill_standard_fds();
3250}
3251
3252#ifdef RUBY_ASAN_ENABLED
3253RUBY_SYMBOL_EXPORT_BEGIN
3254const char ruby_asan_default_options[] = "use_sigaltstack=0:detect_leaks=0";
3255RUBY_SYMBOL_EXPORT_END
3256#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:1598
#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:3048
void ruby_set_argv(int argc, char **argv)
Sets argv that ruby understands.
Definition ruby.c:3161
void ruby_set_script_name(VALUE name)
Sets the current script name to this value.
Definition ruby.c:3060
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:3176
void ruby_prog_init(void)
Defines built-in variables.
Definition ruby.c:3129
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:676
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:475
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1430
VALUE rb_eNameError
NameError exception.
Definition error.c:1435
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1428
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1481
void rb_enc_raise(rb_encoding *enc, VALUE exc, const char *fmt,...)
Identical to rb_raise(), except it additionally takes an encoding.
Definition error.c:3773
void rb_loaderror(const char *fmt,...)
Raises an instance of rb_eLoadError.
Definition error.c:3812
VALUE rb_eSecurityError
SecurityError exception.
Definition error.c:1439
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:497
@ RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK
Warning is for checking unused block strictly.
Definition error.h:57
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
@ RB_WARN_CATEGORY_EXPERIMENTAL
Warning is for experimental features.
Definition error.h:51
@ RB_WARN_CATEGORY_PERFORMANCE
Warning is for performance issues (not enabled by -w).
Definition error.h:54
VALUE rb_mProcess
Process module.
Definition process.c:8725
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:82
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:3240
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:1665
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:1549
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:12989
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:1179
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1116
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:9362
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:1049
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:7376
VALUE rb_io_close(VALUE io)
Closes the IO.
Definition io.c:5748
void rb_lastline_set(VALUE str)
Updates $_.
Definition vm.c:1883
VALUE rb_lastline_get(void)
Queries the last line, or the $_.
Definition vm.c:1877
rb_pid_t rb_waitpid(rb_pid_t pid, int *status, int flags)
Waits for a process, with releasing GVL.
Definition process.c:1167
VALUE rb_f_exec(int argc, const VALUE *argv)
Replaces the current process by running the given external command.
Definition process.c:2916
VALUE rb_reg_new(const char *src, long len, int opts)
Creates a new Regular expression.
Definition re.c:3477
#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:2059
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:3460
#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:1841
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2304
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3870
#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:3692
#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:3585
#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:3051
#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:3651
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:2125
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:4126
VALUE rb_const_remove(VALUE space, ID name)
Identical to rb_mod_remove_const(), except it takes the name as ID instead of VALUE.
Definition variable.c:3769
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:4235
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:1020
@ RUBY_IO_READABLE
IO::READABLE
Definition io.h:82
VALUE rb_io_wait(VALUE io, VALUE events, VALUE timeout)
Blocks until the passed IO is ready for the passed events.
Definition io.c: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:201
static const uint8_t PM_OPTIONS_COMMAND_LINE_L
A bit representing whether or not the command line -l option was set.
Definition options.h:207
static const uint8_t PM_OPTIONS_COMMAND_LINE_A
A bit representing whether or not the command line -a option was set.
Definition options.h:194
static const uint8_t PM_OPTIONS_COMMAND_LINE_N
A bit representing whether or not the command line -n option was set.
Definition options.h:213
static const uint8_t PM_OPTIONS_COMMAND_LINE_X
A bit representing whether or not the command line -x option was set.
Definition options.h:225
static const uint8_t PM_OPTIONS_COMMAND_LINE_P
A bit representing whether or not the command line -p option was set.
Definition options.h:219
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
Definition rarray.h:386
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define RFILE(obj)
Convenient casting macro.
Definition rfile.h:50
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
static int RSTRING_LENINT(VALUE str)
Identical to RSTRING_LEN(), except it differs for the return type.
Definition rstring.h:468
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:488
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
VALUE rb_argv0
The value of $0 at process bootup.
Definition ruby.c:1868
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:2952
void * rb_load_file(const char *file)
Loads the given file.
Definition ruby.c:2945
#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:512
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Definition rdata.h:120
A pm_buffer_t is a simple memory buffer that stores data in a contiguous block of memory.
Definition pm_buffer.h:22
size_t length
The length of the buffer in bytes.
Definition pm_buffer.h:24
char * value
A pointer to the start of the buffer.
Definition pm_buffer.h:30
const uint8_t * start
A pointer to the start location of the range in the source.
Definition ast.h:547
The options that can be passed to the parser.
Definition options.h:98
pm_scope_node_t node
The resulting scope node that will hold the generated AST.
pm_parser_t parser
The parser that will do the actual parsing.
pm_options_t options
The options that will be passed to the parser.
This struct represents the overall parser.
Definition parser.h:640
pm_location_t data_loc
An optional location that represents the location of the END marker and the rest of the content of th...
Definition parser.h:728
const uint8_t * start
The pointer to the start of the source.
Definition parser.h:691
Definition dtoa.c: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