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