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