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