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