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