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