Ruby 3.3.7p123 (2025-01-15 revision be31f993d7fa0219d85f7b3c694d454da4ecc10b)
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(insns) \
157 SEP \
158 X(insns_without_opt) \
159 /* END OF DUMPS */
160enum dump_flag_bits {
161 dump_version_v,
162 dump_error_tolerant,
163 EACH_DUMPS(DEFINE_DUMP, COMMA),
164 dump_error_tolerant_bits = (DUMP_BIT(yydebug) |
165 DUMP_BIT(parsetree) |
166 DUMP_BIT(parsetree_with_comment)),
167 dump_exit_bits = (DUMP_BIT(yydebug) | DUMP_BIT(syntax) |
168 DUMP_BIT(parsetree) | DUMP_BIT(parsetree_with_comment) |
169 DUMP_BIT(insns) | DUMP_BIT(insns_without_opt))
170};
171
172static inline void
173rb_feature_set_to(ruby_features_t *feat, unsigned int bit_mask, unsigned int bit_set)
174{
175 feat->mask |= bit_mask;
176 feat->set = (feat->set & ~bit_mask) | bit_set;
177}
178
179#define FEATURE_SET_TO(feat, bit_mask, bit_set) \
180 rb_feature_set_to(&(feat), bit_mask, bit_set)
181#define FEATURE_SET(feat, bits) FEATURE_SET_TO(feat, bits, bits)
182#define FEATURE_SET_RESTORE(feat, save) FEATURE_SET_TO(feat, (save).mask, (save).set & (save).mask)
183#define FEATURE_SET_P(feat, bits) ((feat).set & FEATURE_BIT(bits))
184#define FEATURE_USED_P(feat, bits) ((feat).mask & FEATURE_BIT(bits))
185#define FEATURE_SET_BITS(feat) ((feat).set & (feat).mask)
186
187static void init_ids(ruby_cmdline_options_t *);
188
189#define src_encoding_index GET_VM()->src_encoding_index
190
191enum {
192 COMPILATION_FEATURES = (
193 0
194 | FEATURE_BIT(frozen_string_literal)
195 | FEATURE_BIT(debug_frozen_string_literal)
196 ),
197 DEFAULT_FEATURES = (
198 (FEATURE_BIT(debug_flag_first)-1)
199#if DISABLE_RUBYGEMS
200 & ~FEATURE_BIT(gems)
201#endif
202 & ~FEATURE_BIT(frozen_string_literal)
203 & ~feature_jit_mask
204 )
205};
206
207#define BACKTRACE_LENGTH_LIMIT_VALID_P(n) ((n) >= -1)
208#define OPT_BACKTRACE_LENGTH_LIMIT_VALID_P(opt) \
209 BACKTRACE_LENGTH_LIMIT_VALID_P((opt)->backtrace_length_limit)
210
211static ruby_cmdline_options_t *
212cmdline_options_init(ruby_cmdline_options_t *opt)
213{
214 MEMZERO(opt, *opt, 1);
215 init_ids(opt);
216 opt->src.enc.index = src_encoding_index;
217 opt->ext.enc.index = -1;
218 opt->intern.enc.index = -1;
219 opt->features.set = DEFAULT_FEATURES;
220#ifdef RJIT_FORCE_ENABLE /* to use with: ./configure cppflags="-DRJIT_FORCE_ENABLE" */
221 opt->features.set |= FEATURE_BIT(rjit);
222#elif defined(YJIT_FORCE_ENABLE)
223 opt->features.set |= FEATURE_BIT(yjit);
224#endif
225 opt->backtrace_length_limit = LONG_MIN;
226
227 return opt;
228}
229
230static rb_ast_t *load_file(VALUE parser, VALUE fname, VALUE f, int script,
231 ruby_cmdline_options_t *opt);
232static VALUE open_load_file(VALUE fname_v, int *xflag);
233static void forbid_setid(const char *, const ruby_cmdline_options_t *);
234#define forbid_setid(s) forbid_setid((s), opt)
235
236static struct {
237 int argc;
238 char **argv;
239} origarg;
240
241static const char esc_standout[] = "\n\033[1;7m";
242static const char esc_bold[] = "\033[1m";
243static const char esc_reset[] = "\033[0m";
244static const char esc_none[] = "";
245#define USAGE_INDENT " " /* macro for concatenation */
246
247static void
248show_usage_part(const char *str, const unsigned int namelen,
249 const char *str2, const unsigned int secondlen,
250 const char *desc,
251 int help, int highlight, unsigned int w, int columns)
252{
253 static const int indent_width = (int)rb_strlen_lit(USAGE_INDENT);
254 const char *sb = highlight ? esc_bold : esc_none;
255 const char *se = highlight ? esc_reset : esc_none;
256 unsigned int desclen = (unsigned int)strcspn(desc, "\n");
257 if (help && (namelen + 1 > w) && /* a padding space */
258 (int)(namelen + secondlen + indent_width) >= columns) {
259 printf(USAGE_INDENT "%s" "%.*s" "%s\n", sb, namelen, str, se);
260 if (secondlen > 0) {
261 const int second_end = secondlen;
262 int n = 0;
263 if (str2[n] == ',') n++;
264 if (str2[n] == ' ') n++;
265 printf(USAGE_INDENT "%s" "%.*s" "%s\n", sb, second_end-n, str2+n, se);
266 }
267 printf("%-*s%.*s\n", w + indent_width, USAGE_INDENT, desclen, desc);
268 }
269 else {
270 const int wrap = help && namelen + secondlen >= w;
271 printf(USAGE_INDENT "%s%.*s%-*.*s%s%-*s%.*s\n", sb, namelen, str,
272 (wrap ? 0 : w - namelen),
273 (help ? secondlen : 0), str2, se,
274 (wrap ? (int)(w + rb_strlen_lit("\n" USAGE_INDENT)) : 0),
275 (wrap ? "\n" USAGE_INDENT : ""),
276 desclen, desc);
277 }
278 if (help) {
279 while (desc[desclen]) {
280 desc += desclen + rb_strlen_lit("\n");
281 desclen = (unsigned int)strcspn(desc, "\n");
282 printf("%-*s%.*s\n", w + indent_width, USAGE_INDENT, desclen, desc);
283 }
284 }
285}
286
287static void
288show_usage_line(const struct ruby_opt_message *m,
289 int help, int highlight, unsigned int w, int columns)
290{
291 const char *str = m->str;
292 const unsigned int namelen = m->namelen, secondlen = m->secondlen;
293 const char *desc = str + namelen + secondlen;
294 show_usage_part(str, namelen - 1, str + namelen, secondlen - 1, desc,
295 help, highlight, w, columns);
296}
297
298void
299ruby_show_usage_line(const char *name, const char *secondary, const char *description,
300 int help, int highlight, unsigned int width, int columns)
301{
302 unsigned int namelen = (unsigned int)strlen(name);
303 unsigned int secondlen = (secondary ? (unsigned int)strlen(secondary) : 0);
304 show_usage_part(name, namelen, secondary, secondlen,
305 description, help, highlight, width, columns);
306}
307
308static void
309usage(const char *name, int help, int highlight, int columns)
310{
311#define M(shortopt, longopt, desc) RUBY_OPT_MESSAGE(shortopt, longopt, desc)
312
313#if USE_YJIT
314# define PLATFORM_JIT_OPTION "--yjit"
315#else
316# define PLATFORM_JIT_OPTION "--rjit (experimental)"
317#endif
318
319 /* This message really ought to be max 23 lines.
320 * Removed -h because the user already knows that option. Others? */
321 static const struct ruby_opt_message usage_msg[] = {
322 M("-0[octal]", "", "specify record separator (\\0, if no argument)\n"
323 "(-00 for paragraph mode, -0777 for slurp mode)"),
324 M("-a", "", "autosplit mode with -n or -p (splits $_ into $F)"),
325 M("-c", "", "check syntax only"),
326 M("-Cdirectory", "", "cd to directory before executing your script"),
327 M("-d", ", --debug", "set debugging flags (set $DEBUG to true)"),
328 M("-e 'command'", "", "one line of script. Several -e's allowed. Omit [programfile]"),
329 M("-Eex[:in]", ", --encoding=ex[:in]", "specify the default external and internal character encodings"),
330 M("-Fpattern", "", "split() pattern for autosplit (-a)"),
331 M("-i[extension]", "", "edit ARGV files in place (make backup if extension supplied)"),
332 M("-Idirectory", "", "specify $LOAD_PATH directory (may be used more than once)"),
333 M("-l", "", "enable line ending processing"),
334 M("-n", "", "assume 'while gets(); ... end' loop around your script"),
335 M("-p", "", "assume loop like -n but print line also like sed"),
336 M("-rlibrary", "", "require the library before executing your script"),
337 M("-s", "", "enable some switch parsing for switches after script name"),
338 M("-S", "", "look for the script using PATH environment variable"),
339 M("-v", "", "print the version number, then turn on verbose mode"),
340 M("-w", "", "turn warnings on for your script"),
341 M("-W[level=2|:category]", "", "set warning level; 0=silence, 1=medium, 2=verbose"),
342 M("-x[directory]", "", "strip off text before #!ruby line and perhaps cd to directory"),
343 M("--jit", "", "enable JIT for the platform, same as " PLATFORM_JIT_OPTION),
344#if USE_YJIT
345 M("--yjit", "", "enable in-process JIT compiler"),
346#endif
347#if USE_RJIT
348 M("--rjit", "", "enable pure-Ruby JIT compiler (experimental)"),
349#endif
350 M("-h", "", "show this message, --help for more info"),
351 };
352 STATIC_ASSERT(usage_msg_size, numberof(usage_msg) < 25);
353
354 static const struct ruby_opt_message help_msg[] = {
355 M("--copyright", "", "print the copyright"),
356 M("--dump={insns|parsetree|...}[,...]", "",
357 "dump debug information. see below for available dump list"),
358 M("--enable={jit|rubyopt|...}[,...]", ", --disable={jit|rubyopt|...}[,...]",
359 "enable or disable features. see below for available features"),
360 M("--external-encoding=encoding", ", --internal-encoding=encoding",
361 "specify the default external or internal character encoding"),
362 M("--parser={parse.y|prism}", ", --parser=prism",
363 "the parser used to parse Ruby code (experimental)"),
364 M("--backtrace-limit=num", "", "limit the maximum length of backtrace"),
365 M("--verbose", "", "turn on verbose mode and disable script from stdin"),
366 M("--version", "", "print the version number, then exit"),
367 M("--crash-report=TEMPLATE", "", "template of crash report files"),
368 M("-y", ", --yydebug", "print log of parser. Backward compatibility is not guaranteed"),
369 M("--help", "", "show this message, -h for short message"),
370 };
371 static const struct ruby_opt_message dumps[] = {
372 M("insns", "", "instruction sequences"),
373 M("insns_without_opt", "", "instruction sequences compiled with no optimization"),
374 M("yydebug(+error-tolerant)", "", "yydebug of yacc parser generator"),
375 M("parsetree(+error-tolerant)","", "AST"),
376 M("parsetree_with_comment(+error-tolerant)", "", "AST with comments"),
377 M("prism_parsetree", "", "Prism AST with comments"),
378 };
379 static const struct ruby_opt_message features[] = {
380 M("gems", "", "rubygems (only for debugging, default: "DEFAULT_RUBYGEMS_ENABLED")"),
381 M("error_highlight", "", "error_highlight (default: "DEFAULT_RUBYGEMS_ENABLED")"),
382 M("did_you_mean", "", "did_you_mean (default: "DEFAULT_RUBYGEMS_ENABLED")"),
383 M("syntax_suggest", "", "syntax_suggest (default: "DEFAULT_RUBYGEMS_ENABLED")"),
384 M("rubyopt", "", "RUBYOPT environment variable (default: enabled)"),
385 M("frozen-string-literal", "", "freeze all string literals (default: disabled)"),
386#if USE_YJIT
387 M("yjit", "", "in-process JIT compiler (default: disabled)"),
388#endif
389#if USE_RJIT
390 M("rjit", "", "pure-Ruby JIT compiler (experimental, default: disabled)"),
391#endif
392 };
393 static const struct ruby_opt_message warn_categories[] = {
394 M("deprecated", "", "deprecated features"),
395 M("experimental", "", "experimental features"),
396 M("performance", "", "performance issues"),
397 };
398#if USE_RJIT
399 extern const struct ruby_opt_message rb_rjit_option_messages[];
400#endif
401 int i;
402 const char *sb = highlight ? esc_standout+1 : esc_none;
403 const char *se = highlight ? esc_reset : esc_none;
404 const int num = numberof(usage_msg) - (help ? 1 : 0);
405 unsigned int w = (columns > 80 ? (columns - 79) / 2 : 0) + 16;
406#define SHOW(m) show_usage_line(&(m), help, highlight, w, columns)
407
408 printf("%sUsage:%s %s [switches] [--] [programfile] [arguments]\n", sb, se, name);
409 for (i = 0; i < num; ++i)
410 SHOW(usage_msg[i]);
411
412 if (!help) return;
413
414 if (highlight) sb = esc_standout;
415
416 for (i = 0; i < numberof(help_msg); ++i)
417 SHOW(help_msg[i]);
418 printf("%s""Dump List:%s\n", sb, se);
419 for (i = 0; i < numberof(dumps); ++i)
420 SHOW(dumps[i]);
421 printf("%s""Features:%s\n", sb, se);
422 for (i = 0; i < numberof(features); ++i)
423 SHOW(features[i]);
424 printf("%s""Warning categories:%s\n", sb, se);
425 for (i = 0; i < numberof(warn_categories); ++i)
426 SHOW(warn_categories[i]);
427#if USE_YJIT
428 printf("%s""YJIT options:%s\n", sb, se);
429 rb_yjit_show_usage(help, highlight, w, columns);
430#endif
431#if USE_RJIT
432 printf("%s""RJIT options (experimental):%s\n", sb, se);
433 for (i = 0; rb_rjit_option_messages[i].str; ++i)
434 SHOW(rb_rjit_option_messages[i]);
435#endif
436}
437
438#define rubylib_path_new rb_str_new
439
440static void
441push_include(const char *path, VALUE (*filter)(VALUE))
442{
443 const char sep = PATH_SEP_CHAR;
444 const char *p, *s;
445 VALUE load_path = GET_VM()->load_path;
446
447 p = path;
448 while (*p) {
449 while (*p == sep)
450 p++;
451 if (!*p) break;
452 for (s = p; *s && *s != sep; s = CharNext(s));
453 rb_ary_push(load_path, (*filter)(rubylib_path_new(p, s - p)));
454 p = s;
455 }
456}
457
458#ifdef __CYGWIN__
459static void
460push_include_cygwin(const char *path, VALUE (*filter)(VALUE))
461{
462 const char *p, *s;
463 char rubylib[FILENAME_MAX];
464 VALUE buf = 0;
465
466 p = path;
467 while (*p) {
468 unsigned int len;
469 while (*p == ';')
470 p++;
471 if (!*p) break;
472 for (s = p; *s && *s != ';'; s = CharNext(s));
473 len = s - p;
474 if (*s) {
475 if (!buf) {
476 buf = rb_str_new(p, len);
477 p = RSTRING_PTR(buf);
478 }
479 else {
480 rb_str_resize(buf, len);
481 p = strncpy(RSTRING_PTR(buf), p, len);
482 }
483 }
484#ifdef HAVE_CYGWIN_CONV_PATH
485#define CONV_TO_POSIX_PATH(p, lib) \
486 cygwin_conv_path(CCP_WIN_A_TO_POSIX|CCP_RELATIVE, (p), (lib), sizeof(lib))
487#else
488# error no cygwin_conv_path
489#endif
490 if (CONV_TO_POSIX_PATH(p, rubylib) == 0)
491 p = rubylib;
492 push_include(p, filter);
493 if (!*s) break;
494 p = s + 1;
495 }
496}
497
498#define push_include push_include_cygwin
499#endif
500
501void
502ruby_push_include(const char *path, VALUE (*filter)(VALUE))
503{
504 if (path == 0)
505 return;
506 push_include(path, filter);
507}
508
509static VALUE
510identical_path(VALUE path)
511{
512 return path;
513}
514static VALUE
515locale_path(VALUE path)
516{
517 rb_enc_associate(path, rb_locale_encoding());
518 return path;
519}
520
521void
522ruby_incpush(const char *path)
523{
524 ruby_push_include(path, locale_path);
525}
526
527static VALUE
528expand_include_path(VALUE path)
529{
530 char *p = RSTRING_PTR(path);
531 if (!p)
532 return path;
533 if (*p == '.' && p[1] == '/')
534 return path;
535 return rb_file_expand_path(path, Qnil);
536}
537
538void
539ruby_incpush_expand(const char *path)
540{
541 ruby_push_include(path, expand_include_path);
542}
543
544#undef UTF8_PATH
545#if defined _WIN32 || defined __CYGWIN__
546static HMODULE libruby;
547
548BOOL WINAPI
549DllMain(HINSTANCE dll, DWORD reason, LPVOID reserved)
550{
551 if (reason == DLL_PROCESS_ATTACH)
552 libruby = dll;
553 return TRUE;
554}
555
556HANDLE
557rb_libruby_handle(void)
558{
559 return libruby;
560}
561
562static inline void
563translit_char_bin(char *p, int from, int to)
564{
565 while (*p) {
566 if ((unsigned char)*p == from)
567 *p = to;
568 p++;
569 }
570}
571#endif
572
573#ifdef _WIN32
574# undef chdir
575# define chdir rb_w32_uchdir
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_category_warn(RB_WARN_CATEGORY_EXPERIMENTAL, "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 rb_ast_t *
1990process_script(ruby_cmdline_options_t *opt)
1991{
1992 rb_ast_t *ast;
1993 VALUE parser = rb_parser_new();
1994
1995 if (opt->dump & DUMP_BIT(yydebug)) {
1996 rb_parser_set_yydebug(parser, Qtrue);
1997 }
1998
1999 if (opt->dump & DUMP_BIT(error_tolerant)) {
2000 rb_parser_error_tolerant(parser);
2001 }
2002
2003 if (opt->e_script) {
2004 VALUE progname = rb_progname;
2005 rb_parser_set_context(parser, 0, TRUE);
2006
2007 ruby_opt_init(opt);
2008 ruby_set_script_name(progname);
2009 rb_parser_set_options(parser, opt->do_print, opt->do_loop,
2010 opt->do_line, opt->do_split);
2011 ast = rb_parser_compile_string(parser, opt->script, opt->e_script, 1);
2012 }
2013 else {
2014 VALUE f;
2015 int xflag = opt->xflag;
2016 f = open_load_file(opt->script_name, &xflag);
2017 opt->xflag = xflag != 0;
2018 rb_parser_set_context(parser, 0, f == rb_stdin);
2019 ast = load_file(parser, opt->script_name, f, 1, opt);
2020 }
2021 if (!ast->body.root) {
2022 rb_ast_dispose(ast);
2023 return NULL;
2024 }
2025 return ast;
2026}
2027
2028static void
2029prism_script(ruby_cmdline_options_t *opt, pm_string_t *input, pm_options_t *options)
2030{
2031 ruby_opt_init(opt);
2032
2033 if (strcmp(opt->script, "-") == 0) {
2034 rb_warn("Prism support for streaming code from stdin is not currently supported");
2035 pm_string_constant_init(input, "", 0);
2036 pm_options_filepath_set(options, "-e");
2037 }
2038 else if (opt->e_script) {
2039 pm_string_constant_init(input, RSTRING_PTR(opt->e_script), RSTRING_LEN(opt->e_script));
2040 pm_options_filepath_set(options, "-e");
2041 }
2042 else {
2043 pm_string_mapped_init(input, RSTRING_PTR(opt->script_name));
2044 pm_options_filepath_set(options, RSTRING_PTR(opt->script_name));
2045 }
2046}
2047
2048static VALUE
2049prism_dump_tree(pm_string_t *input, pm_options_t *options)
2050{
2051 pm_parser_t parser;
2052 pm_parser_init(&parser, pm_string_source(input), pm_string_length(input), options);
2053
2054 pm_node_t *node = pm_parse(&parser);
2055
2056 pm_buffer_t output_buffer = { 0 };
2057
2058 pm_prettyprint(&output_buffer, &parser, node);
2059
2060 VALUE tree = rb_str_new(output_buffer.value, output_buffer.length);
2061
2062 pm_buffer_free(&output_buffer);
2063 pm_node_destroy(&parser, node);
2064 pm_parser_free(&parser);
2065
2066 return tree;
2067}
2068
2069static VALUE
2070process_options(int argc, char **argv, ruby_cmdline_options_t *opt)
2071{
2072 rb_ast_t *ast = NULL;
2073 pm_string_t pm_input = { 0 };
2074 pm_options_t pm_options = { 0 };
2075
2076#define dispose_result() \
2077 (ast ? rb_ast_dispose(ast) : (pm_string_free(&pm_input), pm_options_free(&pm_options)))
2078
2079 const rb_iseq_t *iseq;
2080 rb_encoding *enc, *lenc;
2081#if UTF8_PATH
2082 rb_encoding *ienc = 0;
2083 rb_encoding *const uenc = rb_utf8_encoding();
2084#endif
2085 const char *s;
2086 char fbuf[MAXPATHLEN];
2087 int i = (int)proc_options(argc, argv, opt, 0);
2088 unsigned int dump = opt->dump & dump_exit_bits;
2089 rb_vm_t *vm = GET_VM();
2090 const long loaded_before_enc = RARRAY_LEN(vm->loaded_features);
2091
2092 if (opt->dump & (DUMP_BIT(usage)|DUMP_BIT(help))) {
2093 int tty = isatty(1);
2094 const char *const progname =
2095 (argc > 0 && argv && argv[0] ? argv[0] :
2096 origarg.argc > 0 && origarg.argv && origarg.argv[0] ? origarg.argv[0] :
2097 ruby_engine);
2098 int columns = 0;
2099 if ((opt->dump & DUMP_BIT(help)) && tty) {
2100 const char *pager_env = getenv("RUBY_PAGER");
2101 if (!pager_env) pager_env = getenv("PAGER");
2102 if (pager_env && *pager_env && isatty(0)) {
2103 const char *columns_env = getenv("COLUMNS");
2104 if (columns_env) columns = atoi(columns_env);
2105 VALUE pager = rb_str_new_cstr(pager_env);
2106#ifdef HAVE_WORKING_FORK
2107 int fds[2];
2108 if (rb_pipe(fds) == 0) {
2109 rb_pid_t pid = rb_fork_ruby(NULL);
2110 if (pid > 0) {
2111 /* exec PAGER with reading from child */
2112 dup2(fds[0], 0);
2113 }
2114 else if (pid == 0) {
2115 /* send the help message to the parent PAGER */
2116 dup2(fds[1], 1);
2117 dup2(fds[1], 2);
2118 }
2119 close(fds[0]);
2120 close(fds[1]);
2121 if (pid > 0) {
2122 setup_pager_env();
2123 rb_f_exec(1, &pager);
2124 kill(SIGTERM, pid);
2125 rb_waitpid(pid, 0, 0);
2126 }
2127 }
2128#else
2129 setup_pager_env();
2130 VALUE port = rb_io_popen(pager, rb_str_new_lit("w"), Qnil, Qnil);
2131 if (!NIL_P(port)) {
2132 int oldout = dup(1);
2133 int olderr = dup(2);
2134 int fd = RFILE(port)->fptr->fd;
2135 tty = tty_enabled();
2136 dup2(fd, 1);
2137 dup2(fd, 2);
2138 usage(progname, 1, tty, columns);
2139 fflush(stdout);
2140 dup2(oldout, 1);
2141 dup2(olderr, 2);
2142 rb_io_close(port);
2143 return Qtrue;
2144 }
2145#endif
2146 }
2147 }
2148 usage(progname, (opt->dump & DUMP_BIT(help)), tty, columns);
2149 return Qtrue;
2150 }
2151
2152 argc -= i;
2153 argv += i;
2154
2155 if (FEATURE_SET_P(opt->features, rubyopt) && (s = getenv("RUBYOPT"))) {
2156 moreswitches(s, opt, 1);
2157 }
2158
2159 if (opt->src.enc.name)
2160 /* cannot set deprecated category, as enabling deprecation warnings based on flags
2161 * has not happened yet.
2162 */
2163 rb_warning("-K is specified; it is for 1.8 compatibility and may cause odd behavior");
2164
2165 if (!(FEATURE_SET_BITS(opt->features) & feature_jit_mask)) {
2166#if USE_YJIT
2167 if (!FEATURE_USED_P(opt->features, yjit) && env_var_truthy("RUBY_YJIT_ENABLE")) {
2168 FEATURE_SET(opt->features, FEATURE_BIT(yjit));
2169 }
2170#endif
2171 }
2172 if (MULTI_BITS_P(FEATURE_SET_BITS(opt->features) & feature_jit_mask)) {
2173 rb_warn("RJIT and YJIT cannot both be enabled at the same time. Exiting");
2174 return Qfalse;
2175 }
2176
2177#if USE_RJIT
2178 if (FEATURE_SET_P(opt->features, rjit)) {
2179 opt->rjit.on = true; // set opt->rjit.on for Init_ruby_description() and calling rb_rjit_init()
2180 }
2181#endif
2182#if USE_YJIT
2183 if (FEATURE_SET_P(opt->features, yjit)) {
2184 bool rb_yjit_option_disable(void);
2185 opt->yjit = !rb_yjit_option_disable(); // set opt->yjit for Init_ruby_description() and calling rb_yjit_init()
2186 }
2187#endif
2188
2189 ruby_mn_threads_params();
2190 Init_ruby_description(opt);
2191
2192 if (opt->dump & (DUMP_BIT(version) | DUMP_BIT(version_v))) {
2194 if (opt->dump & DUMP_BIT(version)) return Qtrue;
2195 }
2196 if (opt->dump & DUMP_BIT(copyright)) {
2198 return Qtrue;
2199 }
2200
2201 if (!opt->e_script) {
2202 if (argc <= 0) { /* no more args */
2203 if (opt->verbose)
2204 return Qtrue;
2205 opt->script = "-";
2206 }
2207 else {
2208 opt->script = argv[0];
2209 if (!opt->script || opt->script[0] == '\0') {
2210 opt->script = "-";
2211 }
2212 else if (opt->do_search) {
2213 const char *path = getenv("RUBYPATH");
2214
2215 opt->script = 0;
2216 if (path) {
2217 opt->script = dln_find_file_r(argv[0], path, fbuf, sizeof(fbuf));
2218 }
2219 if (!opt->script) {
2220 opt->script = dln_find_file_r(argv[0], getenv(PATH_ENV), fbuf, sizeof(fbuf));
2221 }
2222 if (!opt->script)
2223 opt->script = argv[0];
2224 }
2225 argc--;
2226 argv++;
2227 }
2228 if (opt->script[0] == '-' && !opt->script[1]) {
2229 forbid_setid("program input from stdin");
2230 }
2231 }
2232
2233 opt->script_name = rb_str_new_cstr(opt->script);
2234 opt->script = RSTRING_PTR(opt->script_name);
2235
2236#ifdef _WIN32
2237 translit_char_bin(RSTRING_PTR(opt->script_name), '\\', '/');
2238#elif defined DOSISH
2239 translit_char(RSTRING_PTR(opt->script_name), '\\', '/');
2240#endif
2241
2242 ruby_gc_set_params();
2244
2245 Init_enc();
2246 lenc = rb_locale_encoding();
2247 rb_enc_associate(rb_progname, lenc);
2248 rb_obj_freeze(rb_progname);
2249 if (opt->ext.enc.name != 0) {
2250 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2251 }
2252 if (opt->intern.enc.name != 0) {
2253 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
2254 }
2255 if (opt->src.enc.name != 0) {
2256 opt->src.enc.index = opt_enc_index(opt->src.enc.name);
2257 src_encoding_index = opt->src.enc.index;
2258 }
2259 if (opt->ext.enc.index >= 0) {
2260 enc = rb_enc_from_index(opt->ext.enc.index);
2261 }
2262 else {
2263 enc = IF_UTF8_PATH(uenc, lenc);
2264 }
2265 rb_enc_set_default_external(rb_enc_from_encoding(enc));
2266 if (opt->intern.enc.index >= 0) {
2267 enc = rb_enc_from_index(opt->intern.enc.index);
2268 rb_enc_set_default_internal(rb_enc_from_encoding(enc));
2269 opt->intern.enc.index = -1;
2270#if UTF8_PATH
2271 ienc = enc;
2272#endif
2273 }
2274 rb_enc_associate(opt->script_name, IF_UTF8_PATH(uenc, lenc));
2275#if UTF8_PATH
2276 if (uenc != lenc) {
2277 opt->script_name = str_conv_enc(opt->script_name, uenc, lenc);
2278 opt->script = RSTRING_PTR(opt->script_name);
2279 }
2280#endif
2281 rb_obj_freeze(opt->script_name);
2282 if (IF_UTF8_PATH(uenc != lenc, 1)) {
2283 long i;
2284 VALUE load_path = vm->load_path;
2285 const ID id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK;
2286 int modifiable = FALSE;
2287
2288 rb_get_expanded_load_path();
2289 for (i = 0; i < RARRAY_LEN(load_path); ++i) {
2290 VALUE path = RARRAY_AREF(load_path, i);
2291 int mark = rb_attr_get(path, id_initial_load_path_mark) == path;
2292#if UTF8_PATH
2293 VALUE newpath = rb_str_conv_enc(path, uenc, lenc);
2294 if (newpath == path) continue;
2295 path = newpath;
2296#else
2297 if (!(path = copy_str(path, lenc, !mark))) continue;
2298#endif
2299 if (mark) rb_ivar_set(path, id_initial_load_path_mark, path);
2300 if (!modifiable) {
2301 rb_ary_modify(load_path);
2302 modifiable = TRUE;
2303 }
2304 RARRAY_ASET(load_path, i, path);
2305 }
2306 if (modifiable) {
2307 rb_ary_replace(vm->load_path_snapshot, load_path);
2308 }
2309 }
2310 {
2311 VALUE loaded_features = vm->loaded_features;
2312 bool modified = false;
2313 for (long i = loaded_before_enc; i < RARRAY_LEN(loaded_features); ++i) {
2314 VALUE path = RARRAY_AREF(loaded_features, i);
2315 if (!(path = copy_str(path, IF_UTF8_PATH(uenc, lenc), true))) continue;
2316 if (!modified) {
2317 rb_ary_modify(loaded_features);
2318 modified = true;
2319 }
2320 RARRAY_ASET(loaded_features, i, path);
2321 }
2322 if (modified) {
2323 rb_ary_replace(vm->loaded_features_snapshot, loaded_features);
2324 }
2325 }
2326
2327 if (opt->features.mask & COMPILATION_FEATURES) {
2328 VALUE option = rb_hash_new();
2329#define SET_COMPILE_OPTION(h, o, name) \
2330 rb_hash_aset((h), ID2SYM(rb_intern_const(#name)), \
2331 RBOOL(FEATURE_SET_P(o->features, name)))
2332 SET_COMPILE_OPTION(option, opt, frozen_string_literal);
2333 SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal);
2334 rb_funcallv(rb_cISeq, rb_intern_const("compile_option="), 1, &option);
2335#undef SET_COMPILE_OPTION
2336 }
2337 ruby_set_argv(argc, argv);
2338 opt->sflag = process_sflag(opt->sflag);
2339
2340 if (opt->e_script) {
2341 rb_encoding *eenc;
2342 if (opt->src.enc.index >= 0) {
2343 eenc = rb_enc_from_index(opt->src.enc.index);
2344 }
2345 else {
2346 eenc = lenc;
2347#if UTF8_PATH
2348 if (ienc) eenc = ienc;
2349#endif
2350 }
2351#if UTF8_PATH
2352 if (eenc != uenc) {
2353 opt->e_script = str_conv_enc(opt->e_script, uenc, eenc);
2354 }
2355#endif
2356 rb_enc_associate(opt->e_script, eenc);
2357 }
2358
2359 if (!(*rb_ruby_prism_ptr())) {
2360 if (!(ast = process_script(opt))) return Qfalse;
2361 }
2362 else {
2363 prism_script(opt, &pm_input, &pm_options);
2364 }
2365 ruby_set_script_name(opt->script_name);
2366 if ((dump & DUMP_BIT(yydebug)) && !(dump &= ~DUMP_BIT(yydebug))) {
2367 dispose_result();
2368 return Qtrue;
2369 }
2370
2371 if (opt->ext.enc.index >= 0) {
2372 enc = rb_enc_from_index(opt->ext.enc.index);
2373 }
2374 else {
2375 enc = IF_UTF8_PATH(uenc, lenc);
2376 }
2377 rb_enc_set_default_external(rb_enc_from_encoding(enc));
2378 if (opt->intern.enc.index >= 0) {
2379 /* Set in the shebang line */
2380 enc = rb_enc_from_index(opt->intern.enc.index);
2381 rb_enc_set_default_internal(rb_enc_from_encoding(enc));
2382 }
2383 else if (!rb_default_internal_encoding())
2384 /* Freeze default_internal */
2385 rb_enc_set_default_internal(Qnil);
2386 rb_stdio_set_default_encoding();
2387
2388 opt->sflag = process_sflag(opt->sflag);
2389 opt->xflag = 0;
2390
2391 if (dump & DUMP_BIT(syntax)) {
2392 printf("Syntax OK\n");
2393 dump &= ~DUMP_BIT(syntax);
2394 if (!dump) return Qtrue;
2395 }
2396
2397 if (opt->do_loop) {
2398 rb_define_global_function("sub", rb_f_sub, -1);
2399 rb_define_global_function("gsub", rb_f_gsub, -1);
2400 rb_define_global_function("chop", rb_f_chop, 0);
2401 rb_define_global_function("chomp", rb_f_chomp, -1);
2402 }
2403
2404 if (dump & (DUMP_BIT(parsetree)|DUMP_BIT(parsetree_with_comment))) {
2405 VALUE tree;
2406 if (ast) {
2407 int comment = dump & DUMP_BIT(parsetree_with_comment);
2408 tree = rb_parser_dump_tree(ast->body.root, comment);
2409 }
2410 else {
2411 tree = prism_dump_tree(&pm_input, &pm_options);
2412 }
2413 rb_io_write(rb_stdout, tree);
2414 rb_io_flush(rb_stdout);
2415 dump &= ~DUMP_BIT(parsetree)&~DUMP_BIT(parsetree_with_comment);
2416 if (!dump) {
2417 dispose_result();
2418 return Qtrue;
2419 }
2420 }
2421
2422 {
2423 VALUE path = Qnil;
2424 if (!opt->e_script && strcmp(opt->script, "-")) {
2425 path = rb_realpath_internal(Qnil, opt->script_name, 1);
2426#if UTF8_PATH
2427 if (uenc != lenc) {
2428 path = str_conv_enc(path, uenc, lenc);
2429 }
2430#endif
2431 if (!ENCODING_GET(path)) { /* ASCII-8BIT */
2432 rb_enc_copy(path, opt->script_name);
2433 }
2434 }
2435
2436 bool optimize = !(dump & DUMP_BIT(insns_without_opt));
2437
2438 if (!ast) {
2439 iseq = rb_iseq_new_main_prism(&pm_input, &pm_options, path);
2440 }
2441 else {
2442 rb_binding_t *toplevel_binding;
2443 GetBindingPtr(rb_const_get(rb_cObject, rb_intern("TOPLEVEL_BINDING")),
2444 toplevel_binding);
2445 const struct rb_block *base_block = toplevel_context(toplevel_binding);
2446 iseq = rb_iseq_new_main(&ast->body, opt->script_name, path, vm_block_iseq(base_block), optimize);
2447 rb_ast_dispose(ast);
2448 }
2449 }
2450
2451 if (dump & (DUMP_BIT(insns) | DUMP_BIT(insns_without_opt))) {
2452 rb_io_write(rb_stdout, rb_iseq_disasm((const rb_iseq_t *)iseq));
2453 rb_io_flush(rb_stdout);
2454 dump &= ~DUMP_BIT(insns);
2455 if (!dump) return Qtrue;
2456 }
2457 if (opt->dump & dump_exit_bits) return Qtrue;
2458
2459 if (OPT_BACKTRACE_LENGTH_LIMIT_VALID_P(opt)) {
2460 rb_backtrace_length_limit = opt->backtrace_length_limit;
2461 }
2462
2463 rb_define_readonly_boolean("$-p", opt->do_print);
2464 rb_define_readonly_boolean("$-l", opt->do_line);
2465 rb_define_readonly_boolean("$-a", opt->do_split);
2466
2467 rb_gvar_ractor_local("$-p");
2468 rb_gvar_ractor_local("$-l");
2469 rb_gvar_ractor_local("$-a");
2470
2471 if ((rb_e_script = opt->e_script) != 0) {
2472 rb_str_freeze(rb_e_script);
2473 rb_gc_register_mark_object(opt->e_script);
2474 }
2475
2476 {
2477 rb_execution_context_t *ec = GET_EC();
2478
2479 if (opt->e_script) {
2480 /* -e */
2481 rb_exec_event_hook_script_compiled(ec, iseq, opt->e_script);
2482 }
2483 else {
2484 /* file */
2485 rb_exec_event_hook_script_compiled(ec, iseq, Qnil);
2486 }
2487 }
2488 return (VALUE)iseq;
2489}
2490
2491#ifndef DOSISH
2492static void
2493warn_cr_in_shebang(const char *str, long len)
2494{
2495 if (str[len-1] == '\n' && str[len-2] == '\r') {
2496 rb_warn("shebang line ending with \\r may cause problems");
2497 }
2498}
2499#else
2500#define warn_cr_in_shebang(str, len) (void)0
2501#endif
2502
2503void rb_reset_argf_lineno(long n);
2504
2506 VALUE parser;
2507 VALUE fname;
2508 int script;
2509 ruby_cmdline_options_t *opt;
2510 VALUE f;
2511};
2512
2513VALUE rb_script_lines_for(VALUE path, bool add);
2514
2515static VALUE
2516load_file_internal(VALUE argp_v)
2517{
2518 struct load_file_arg *argp = (struct load_file_arg *)argp_v;
2519 VALUE parser = argp->parser;
2520 VALUE orig_fname = argp->fname;
2521 int script = argp->script;
2522 ruby_cmdline_options_t *opt = argp->opt;
2523 VALUE f = argp->f;
2524 int line_start = 1;
2525 rb_ast_t *ast = 0;
2526 rb_encoding *enc;
2527 ID set_encoding;
2528
2529 CONST_ID(set_encoding, "set_encoding");
2530 if (script) {
2531 VALUE c = 1; /* something not nil */
2532 VALUE line;
2533 char *p, *str;
2534 long len;
2535 int no_src_enc = !opt->src.enc.name;
2536 int no_ext_enc = !opt->ext.enc.name;
2537 int no_int_enc = !opt->intern.enc.name;
2538
2539 enc = rb_ascii8bit_encoding();
2540 rb_funcall(f, set_encoding, 1, rb_enc_from_encoding(enc));
2541
2542 if (opt->xflag) {
2543 line_start--;
2544 search_shebang:
2545 while (!NIL_P(line = rb_io_gets(f))) {
2546 line_start++;
2547 RSTRING_GETMEM(line, str, len);
2548 if (len > 2 && str[0] == '#' && str[1] == '!') {
2549 if (line_start == 1) warn_cr_in_shebang(str, len);
2550 if ((p = strstr(str+2, ruby_engine)) != 0) {
2551 goto start_read;
2552 }
2553 }
2554 }
2555 rb_loaderror("no Ruby script found in input");
2556 }
2557
2558 c = rb_io_getbyte(f);
2559 if (c == INT2FIX('#')) {
2560 c = rb_io_getbyte(f);
2561 if (c == INT2FIX('!') && !NIL_P(line = rb_io_gets(f))) {
2562 RSTRING_GETMEM(line, str, len);
2563 warn_cr_in_shebang(str, len);
2564 if ((p = strstr(str, ruby_engine)) == 0) {
2565 /* not ruby script, assume -x flag */
2566 goto search_shebang;
2567 }
2568
2569 start_read:
2570 str += len - 1;
2571 if (*str == '\n') *str-- = '\0';
2572 if (*str == '\r') *str-- = '\0';
2573 /* ruby_engine should not contain a space */
2574 if ((p = strstr(p, " -")) != 0) {
2575 opt->warning = 0;
2576 moreswitches(p + 1, opt, 0);
2577 }
2578
2579 /* push back shebang for pragma may exist in next line */
2580 rb_io_ungetbyte(f, rb_str_new2("!\n"));
2581 }
2582 else if (!NIL_P(c)) {
2583 rb_io_ungetbyte(f, c);
2584 }
2585 rb_io_ungetbyte(f, INT2FIX('#'));
2586 if (no_src_enc && opt->src.enc.name) {
2587 opt->src.enc.index = opt_enc_index(opt->src.enc.name);
2588 src_encoding_index = opt->src.enc.index;
2589 }
2590 if (no_ext_enc && opt->ext.enc.name) {
2591 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2592 }
2593 if (no_int_enc && opt->intern.enc.name) {
2594 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
2595 }
2596 }
2597 else if (!NIL_P(c)) {
2598 rb_io_ungetbyte(f, c);
2599 }
2600 if (NIL_P(c)) {
2601 argp->f = f = Qnil;
2602 }
2603 rb_reset_argf_lineno(0);
2604 ruby_opt_init(opt);
2605 }
2606 if (opt->src.enc.index >= 0) {
2607 enc = rb_enc_from_index(opt->src.enc.index);
2608 }
2609 else if (f == rb_stdin) {
2610 enc = rb_locale_encoding();
2611 }
2612 else {
2613 enc = rb_utf8_encoding();
2614 }
2615 rb_parser_set_options(parser, opt->do_print, opt->do_loop,
2616 opt->do_line, opt->do_split);
2617
2618 VALUE lines = rb_script_lines_for(orig_fname, true);
2619 if (!NIL_P(lines)) {
2620 rb_parser_set_script_lines(parser, lines);
2621 }
2622
2623 if (NIL_P(f)) {
2624 f = rb_str_new(0, 0);
2625 rb_enc_associate(f, enc);
2626 return (VALUE)rb_parser_compile_string_path(parser, orig_fname, f, line_start);
2627 }
2628 rb_funcall(f, set_encoding, 2, rb_enc_from_encoding(enc), rb_str_new_cstr("-"));
2629 ast = rb_parser_compile_file_path(parser, orig_fname, f, line_start);
2630 rb_funcall(f, set_encoding, 1, rb_parser_encoding(parser));
2631 if (script && rb_parser_end_seen_p(parser)) {
2632 /*
2633 * DATA is a File that contains the data section of the executed file.
2634 * To create a data section use <tt>__END__</tt>:
2635 *
2636 * $ cat t.rb
2637 * puts DATA.gets
2638 * __END__
2639 * hello world!
2640 *
2641 * $ ruby t.rb
2642 * hello world!
2643 */
2644 rb_define_global_const("DATA", f);
2645 argp->f = Qnil;
2646 }
2647 return (VALUE)ast;
2648}
2649
2650/* disabling O_NONBLOCK, and returns 0 on success, otherwise errno */
2651static inline int
2652disable_nonblock(int fd)
2653{
2654#if defined(HAVE_FCNTL) && defined(F_SETFL)
2655 if (fcntl(fd, F_SETFL, 0) < 0) {
2656 const int e = errno;
2657 ASSUME(e != 0);
2658# if defined ENOTSUP
2659 if (e == ENOTSUP) return 0;
2660# endif
2661# if defined B_UNSUPPORTED
2662 if (e == B_UNSUPPORTED) return 0;
2663# endif
2664 return e;
2665 }
2666#endif
2667 return 0;
2668}
2669
2670static VALUE
2671open_load_file(VALUE fname_v, int *xflag)
2672{
2673 const char *fname = (fname_v = rb_str_encode_ospath(fname_v),
2674 StringValueCStr(fname_v));
2675 long flen = RSTRING_LEN(fname_v);
2676 VALUE f;
2677 int e;
2678
2679 if (flen == 1 && fname[0] == '-') {
2680 f = rb_stdin;
2681 }
2682 else {
2683 int fd;
2684 /* open(2) may block if fname is point to FIFO and it's empty. Let's
2685 use O_NONBLOCK. */
2686 const int MODE_TO_LOAD = O_RDONLY | (
2687#if defined O_NONBLOCK && HAVE_FCNTL
2688 /* TODO: fix conflicting O_NONBLOCK in ruby/win32.h */
2689 !(O_NONBLOCK & O_ACCMODE) ? O_NONBLOCK :
2690#endif
2691#if defined O_NDELAY && HAVE_FCNTL
2692 !(O_NDELAY & O_ACCMODE) ? O_NDELAY :
2693#endif
2694 0);
2695 int mode = MODE_TO_LOAD;
2696#if defined DOSISH || defined __CYGWIN__
2697# define isdirsep(x) ((x) == '/' || (x) == '\\')
2698 {
2699 static const char exeext[] = ".exe";
2700 enum {extlen = sizeof(exeext)-1};
2701 if (flen > extlen && !isdirsep(fname[flen-extlen-1]) &&
2702 STRNCASECMP(fname+flen-extlen, exeext, extlen) == 0) {
2703 mode |= O_BINARY;
2704 *xflag = 1;
2705 }
2706 }
2707#endif
2708
2709 if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) {
2710 e = errno;
2711 if (!rb_gc_for_fd(e)) {
2712 rb_load_fail(fname_v, strerror(e));
2713 }
2714 if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) {
2715 rb_load_fail(fname_v, strerror(errno));
2716 }
2717 }
2718 rb_update_max_fd(fd);
2719
2720 if (MODE_TO_LOAD != O_RDONLY && (e = disable_nonblock(fd)) != 0) {
2721 (void)close(fd);
2722 rb_load_fail(fname_v, strerror(e));
2723 }
2724
2725 e = ruby_is_fd_loadable(fd);
2726 if (!e) {
2727 e = errno;
2728 (void)close(fd);
2729 rb_load_fail(fname_v, strerror(e));
2730 }
2731
2732 f = rb_io_fdopen(fd, mode, fname);
2733 if (e < 0) {
2734 /*
2735 We need to wait if FIFO is empty. It's FIFO's semantics.
2736 rb_thread_wait_fd() release GVL. So, it's safe.
2737 */
2739 }
2740 }
2741 return f;
2742}
2743
2744static VALUE
2745restore_load_file(VALUE arg)
2746{
2747 struct load_file_arg *argp = (struct load_file_arg *)arg;
2748 VALUE f = argp->f;
2749
2750 if (!NIL_P(f) && f != rb_stdin) {
2751 rb_io_close(f);
2752 }
2753 return Qnil;
2754}
2755
2756static rb_ast_t *
2757load_file(VALUE parser, VALUE fname, VALUE f, int script, ruby_cmdline_options_t *opt)
2758{
2759 struct load_file_arg arg;
2760 arg.parser = parser;
2761 arg.fname = fname;
2762 arg.script = script;
2763 arg.opt = opt;
2764 arg.f = f;
2765 return (rb_ast_t *)rb_ensure(load_file_internal, (VALUE)&arg,
2766 restore_load_file, (VALUE)&arg);
2767}
2768
2769void *
2770rb_load_file(const char *fname)
2771{
2772 VALUE fname_v = rb_str_new_cstr(fname);
2773 return rb_load_file_str(fname_v);
2774}
2775
2776void *
2778{
2779 return rb_parser_load_file(rb_parser_new(), fname_v);
2780}
2781
2782void *
2783rb_parser_load_file(VALUE parser, VALUE fname_v)
2784{
2785 ruby_cmdline_options_t opt;
2786 int xflag = 0;
2787 VALUE f = open_load_file(fname_v, &xflag);
2788 cmdline_options_init(&opt)->xflag = xflag != 0;
2789 return load_file(parser, fname_v, f, 0, &opt);
2790}
2791
2792/*
2793 * call-seq:
2794 * Process.argv0 -> frozen_string
2795 *
2796 * Returns the name of the script being executed. The value is not
2797 * affected by assigning a new value to $0.
2798 *
2799 * This method first appeared in Ruby 2.1 to serve as a global
2800 * variable free means to get the script name.
2801 */
2802
2803static VALUE
2804proc_argv0(VALUE process)
2805{
2806 return rb_orig_progname;
2807}
2808
2809static VALUE ruby_setproctitle(VALUE title);
2810
2811/*
2812 * call-seq:
2813 * Process.setproctitle(string) -> string
2814 *
2815 * Sets the process title that appears on the ps(1) command. Not
2816 * necessarily effective on all platforms. No exception will be
2817 * raised regardless of the result, nor will NotImplementedError be
2818 * raised even if the platform does not support the feature.
2819 *
2820 * Calling this method does not affect the value of $0.
2821 *
2822 * Process.setproctitle('myapp: worker #%d' % worker_id)
2823 *
2824 * This method first appeared in Ruby 2.1 to serve as a global
2825 * variable free means to change the process title.
2826 */
2827
2828static VALUE
2829proc_setproctitle(VALUE process, VALUE title)
2830{
2831 return ruby_setproctitle(title);
2832}
2833
2834static VALUE
2835ruby_setproctitle(VALUE title)
2836{
2837 const char *ptr = StringValueCStr(title);
2838 setproctitle("%.*s", RSTRING_LENINT(title), ptr);
2839 return title;
2840}
2841
2842static void
2843set_arg0(VALUE val, ID id, VALUE *_)
2844{
2845 if (origarg.argv == 0)
2846 rb_raise(rb_eRuntimeError, "$0 not initialized");
2847
2848 rb_progname = rb_str_new_frozen(ruby_setproctitle(val));
2849}
2850
2851static inline VALUE
2852external_str_new_cstr(const char *p)
2853{
2854#if UTF8_PATH
2855 VALUE str = rb_utf8_str_new_cstr(p);
2856 str = str_conv_enc(str, NULL, rb_default_external_encoding());
2857 return str;
2858#else
2859 return rb_external_str_new_cstr(p);
2860#endif
2861}
2862
2863static void
2864set_progname(VALUE name)
2865{
2866 rb_orig_progname = rb_progname = name;
2867 rb_vm_set_progname(rb_progname);
2868}
2869
2870void
2871ruby_script(const char *name)
2872{
2873 if (name) {
2874 set_progname(rb_str_freeze(external_str_new_cstr(name)));
2875 }
2876}
2877
2882void
2884{
2885 set_progname(rb_str_new_frozen(name));
2886}
2887
2888static void
2889init_ids(ruby_cmdline_options_t *opt)
2890{
2891 rb_uid_t uid = getuid();
2892 rb_uid_t euid = geteuid();
2893 rb_gid_t gid = getgid();
2894 rb_gid_t egid = getegid();
2895
2896 if (uid != euid) opt->setids |= 1;
2897 if (egid != gid) opt->setids |= 2;
2898}
2899
2900#undef forbid_setid
2901static void
2902forbid_setid(const char *s, const ruby_cmdline_options_t *opt)
2903{
2904 if (opt->setids & 1)
2905 rb_raise(rb_eSecurityError, "no %s allowed while running setuid", s);
2906 if (opt->setids & 2)
2907 rb_raise(rb_eSecurityError, "no %s allowed while running setgid", s);
2908}
2909
2910static VALUE
2911verbose_getter(ID id, VALUE *ptr)
2912{
2913 return *rb_ruby_verbose_ptr();
2914}
2915
2916static void
2917verbose_setter(VALUE val, ID id, VALUE *variable)
2918{
2919 *rb_ruby_verbose_ptr() = RTEST(val) ? Qtrue : val;
2920}
2921
2922static VALUE
2923opt_W_getter(ID id, VALUE *dmy)
2924{
2925 VALUE v = *rb_ruby_verbose_ptr();
2926
2927 switch (v) {
2928 case Qnil:
2929 return INT2FIX(0);
2930 case Qfalse:
2931 return INT2FIX(1);
2932 case Qtrue:
2933 return INT2FIX(2);
2934 default:
2935 return Qnil;
2936 }
2937}
2938
2939static VALUE
2940debug_getter(ID id, VALUE *dmy)
2941{
2942 return *rb_ruby_debug_ptr();
2943}
2944
2945static void
2946debug_setter(VALUE val, ID id, VALUE *dmy)
2947{
2948 *rb_ruby_debug_ptr() = val;
2949}
2950
2951void
2953{
2954 rb_define_virtual_variable("$VERBOSE", verbose_getter, verbose_setter);
2955 rb_define_virtual_variable("$-v", verbose_getter, verbose_setter);
2956 rb_define_virtual_variable("$-w", verbose_getter, verbose_setter);
2958 rb_define_virtual_variable("$DEBUG", debug_getter, debug_setter);
2959 rb_define_virtual_variable("$-d", debug_getter, debug_setter);
2960
2961 rb_gvar_ractor_local("$VERBOSE");
2962 rb_gvar_ractor_local("$-v");
2963 rb_gvar_ractor_local("$-w");
2964 rb_gvar_ractor_local("$-W");
2965 rb_gvar_ractor_local("$DEBUG");
2966 rb_gvar_ractor_local("$-d");
2967
2968 rb_define_hooked_variable("$0", &rb_progname, 0, set_arg0);
2969 rb_define_hooked_variable("$PROGRAM_NAME", &rb_progname, 0, set_arg0);
2970
2971 rb_define_module_function(rb_mProcess, "argv0", proc_argv0, 0);
2972 rb_define_module_function(rb_mProcess, "setproctitle", proc_setproctitle, 1);
2973
2974 /*
2975 * ARGV contains the command line arguments used to run ruby.
2976 *
2977 * A library like OptionParser can be used to process command-line
2978 * arguments.
2979 */
2981}
2982
2983void
2984ruby_set_argv(int argc, char **argv)
2985{
2986 int i;
2987 VALUE av = rb_argv;
2988
2989 rb_ary_clear(av);
2990 for (i = 0; i < argc; i++) {
2991 VALUE arg = external_str_new_cstr(argv[i]);
2992
2993 OBJ_FREEZE(arg);
2994 rb_ary_push(av, arg);
2995 }
2996}
2997
2998void *
2999ruby_process_options(int argc, char **argv)
3000{
3001 ruby_cmdline_options_t opt;
3002 VALUE iseq;
3003 const char *script_name = (argc > 0 && argv[0]) ? argv[0] : ruby_engine;
3004
3005 (*rb_ruby_prism_ptr()) = false;
3006
3007 if (!origarg.argv || origarg.argc <= 0) {
3008 origarg.argc = argc;
3009 origarg.argv = argv;
3010 }
3011 set_progname(external_str_new_cstr(script_name)); /* for the time being */
3012 rb_argv0 = rb_str_new4(rb_progname);
3013 rb_gc_register_mark_object(rb_argv0);
3014
3015#ifndef HAVE_SETPROCTITLE
3016 ruby_init_setproctitle(argc, argv);
3017#endif
3018
3019 iseq = process_options(argc, argv, cmdline_options_init(&opt));
3020
3021 if (opt.crash_report && *opt.crash_report) {
3022 void ruby_set_crash_report(const char *template);
3023 ruby_set_crash_report(opt.crash_report);
3024 }
3025 return (void*)(struct RData*)iseq;
3026}
3027
3028static void
3029fill_standard_fds(void)
3030{
3031 int f0, f1, f2, fds[2];
3032 struct stat buf;
3033 f0 = fstat(0, &buf) == -1 && errno == EBADF;
3034 f1 = fstat(1, &buf) == -1 && errno == EBADF;
3035 f2 = fstat(2, &buf) == -1 && errno == EBADF;
3036 if (f0) {
3037 if (pipe(fds) == 0) {
3038 close(fds[1]);
3039 if (fds[0] != 0) {
3040 dup2(fds[0], 0);
3041 close(fds[0]);
3042 }
3043 }
3044 }
3045 if (f1 || f2) {
3046 if (pipe(fds) == 0) {
3047 close(fds[0]);
3048 if (f1 && fds[1] != 1)
3049 dup2(fds[1], 1);
3050 if (f2 && fds[1] != 2)
3051 dup2(fds[1], 2);
3052 if (fds[1] != 1 && fds[1] != 2)
3053 close(fds[1]);
3054 }
3055 }
3056}
3057
3058void
3059ruby_sysinit(int *argc, char ***argv)
3060{
3061#if defined(_WIN32)
3062 rb_w32_sysinit(argc, argv);
3063#endif
3064 if (*argc >= 0 && *argv) {
3065 origarg.argc = *argc;
3066 origarg.argv = *argv;
3067 }
3068 fill_standard_fds();
3069}
#define RUBY_ASSERT(expr)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:177
struct pm_node pm_node_t
This is the base structure that represents a node in the syntax tree.
#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:1085
#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:2871
void ruby_set_argv(int argc, char **argv)
Sets argv that ruby understands.
Definition ruby.c:2984
void ruby_set_script_name(VALUE name)
Sets the current script name to this value.
Definition ruby.c:2883
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:2999
void ruby_prog_init(void)
Defines built-in variables.
Definition ruby.c:2952
void ruby_incpush(const char *path)
Appends the given path to the end of the load path.
Definition ruby.c:522
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
Definition error.h:482
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:433
#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:8747
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2099
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:212
void ruby_sysinit(int *argc, char ***argv)
Initializes the process for libruby.
Definition ruby.c:3059
void ruby_show_version(void)
Prints the version information of the CRuby interpreter to stdout.
Definition version.c:198
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:12090
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:4268
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:5144
VALUE rb_io_getbyte(VALUE io)
Reads a byte from the given IO.
Definition io.c:5050
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:9298
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:7343
VALUE rb_io_close(VALUE io)
Closes the IO.
Definition io.c:5731
void rb_lastline_set(VALUE str)
Updates $_.
Definition vm.c:1820
VALUE rb_lastline_get(void)
Queries the last line, or the $_.
Definition vm.c:1814
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:3015
VALUE rb_reg_new(const char *src, long len, int opts)
Creates a new Regular expression.
Definition re.c:3408
#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:1532
#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 "defaultexternal" 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:3001
#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:2486
#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".
Definition util.c:593
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.
struct pm_parser pm_parser_t
The parser used to parse Ruby source.
Definition parser.h:259
#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:2777
void * rb_load_file(const char *file)
Loads the given file.
Definition ruby.c:2770
#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
The options that can be passed to the parser.
Definition options.h:30
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