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