14 #include "ruby/internal/config.h"
18 #include <sys/types.h>
22 # include <sys/cygwin.h>
26 # include <sys/pstat.h>
29 #if (defined(LOAD_RELATIVE) || defined(__MACH__)) && defined(HAVE_DLADDR)
37 #if defined(HAVE_FCNTL_H)
39 #elif defined(HAVE_SYS_FCNTL_H)
40 # include <sys/fcntl.h>
43 #ifdef HAVE_SYS_PARAM_H
44 # include <sys/param.h>
48 #include "eval_intern.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"
70 # define MAXPATHLEN 1024
73 # define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
76 void Init_ruby_description(
void);
82 #ifndef DISABLE_RUBYGEMS
83 # define DISABLE_RUBYGEMS 0
86 #define DEFAULT_RUBYGEMS_ENABLED "disabled"
88 #define DEFAULT_RUBYGEMS_ENABLED "enabled"
91 void rb_warning_category_update(
unsigned int mask,
unsigned int bits);
94 #define FEATURE_BIT(bit) (1U << feature_##bit)
95 #define EACH_FEATURES(X, SEP) \
104 X(frozen_string_literal) \
110 #define EACH_DEBUG_FEATURES(X, SEP) \
111 X(frozen_string_literal) \
113 #define AMBIGUOUS_FEATURE_NAMES 0
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),
124 #define DEBUG_BIT(bit) (1U << feature_debug_##bit)
126 #define DUMP_BIT(bit) (1U << dump_##bit)
127 #define DEFINE_DUMP(bit) dump_##bit
128 #define EACH_DUMPS(X, SEP) \
143 X(parsetree_with_comment) \
147 X(insns_without_opt) \
149 enum dump_flag_bits {
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))
165 rb_feature_set_to(
ruby_features_t *feat,
unsigned int bit_mask,
unsigned int bit_set)
167 feat->mask |= bit_mask;
168 feat->set = (feat->set & ~bit_mask) | bit_set;
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))
192 struct mjit_options mjit;
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;
209 #define src_encoding_index GET_VM()->src_encoding_index
212 COMPILATION_FEATURES = (
214 | FEATURE_BIT(frozen_string_literal)
215 | FEATURE_BIT(debug_frozen_string_literal)
218 (FEATURE_BIT(debug_flag_first)-1)
222 & ~FEATURE_BIT(frozen_string_literal)
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
238 opt->features.set |= FEATURE_BIT(mjit);
239 #elif defined(YJIT_FORCE_ENABLE)
240 opt->features.set |= FEATURE_BIT(yjit);
243 if (getenv(
"RUBY_YJIT_ENABLE")) {
244 opt->features.set |= FEATURE_BIT(yjit);
252 static VALUE open_load_file(
VALUE fname_v,
int *xflag);
254 #define forbid_setid(s) forbid_setid((s), opt)
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[] =
"";
267 show_usage_line(
const char *str,
unsigned int namelen,
unsigned int secondlen,
int help,
int highlight,
unsigned int w)
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);
280 usage(
const char *name,
int help,
int highlight,
int columns)
287 unsigned short namelen, secondlen;
289 #define M(shortopt, longopt, desc) { \
290 shortopt " " longopt " " desc, \
291 (unsigned short)sizeof(shortopt), \
292 (unsigned short)sizeof(longopt), \
295 # define PLATFORM_JIT_OPTION "--yjit"
297 # define PLATFORM_JIT_OPTION "--mjit"
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"),
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"),
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"),
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)"),
354 static const struct message warn_categories[] = {
355 M(
"deprecated",
"",
"deprecated features"),
356 M(
"experimental",
"",
"experimental features"),
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)"),
367 static const struct message yjit_options[] = {
369 M(
"--yjit-stats",
"",
"Enable collecting YJIT statistics"),
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)"),
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)
383 printf(
"%sUsage:%s %s [switches] [--] [programfile] [arguments]\n", sb, se, name);
384 for (i = 0; i < num; ++i)
389 if (highlight) sb = esc_standout;
391 for (i = 0; i < numberof(help_msg); ++i)
393 printf(
"%s""Dump List:%s\n", sb, se);
394 for (i = 0; i < numberof(dumps); ++i)
396 printf(
"%s""Features:%s\n", sb, se);
397 for (i = 0; i < numberof(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]);
410 #define rubylib_path_new rb_str_new
413 push_include(
const char *path,
VALUE (*filter)(
VALUE))
417 VALUE load_path = GET_VM()->load_path;
424 for (s = p; *s && *s != sep; s = CharNext(s));
425 rb_ary_push(load_path, (*filter)(rubylib_path_new(p, s - p)));
432 push_include_cygwin(
const char *path,
VALUE (*filter)(
VALUE))
435 char rubylib[FILENAME_MAX];
444 for (s = p; *s && *s !=
';'; s = CharNext(s));
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))
460 # error no cygwin_conv_path
462 if (CONV_TO_POSIX_PATH(p, rubylib) == 0)
464 push_include(p, filter);
470 #define push_include push_include_cygwin
474 ruby_push_include(
const char *path,
VALUE (*filter)(
VALUE))
478 push_include(path, filter);
482 identical_path(
VALUE path)
487 locale_path(
VALUE path)
496 ruby_push_include(path, locale_path);
500 expand_include_path(
VALUE path)
505 if (*p ==
'.' && p[1] ==
'/')
511 ruby_incpush_expand(
const char *path)
513 ruby_push_include(path, expand_include_path);
517 #if defined _WIN32 || defined __CYGWIN__
518 static HMODULE libruby;
521 DllMain(HINSTANCE dll, DWORD reason, LPVOID reserved)
523 if (reason == DLL_PROCESS_ATTACH)
529 rb_libruby_handle(
void)
535 translit_char_bin(
char *p,
int from,
int to)
538 if ((
unsigned char)*p == from)
553 # define IF_UTF8_PATH(t, f) t
555 # define IF_UTF8_PATH(t, f) f
567 # define str_conv_enc(str, from, to) (str)
572 #if defined(LOAD_RELATIVE) || defined(__MACH__)
574 runtime_libruby_path(
void)
576 #if defined _WIN32 || defined __CYGWIN__
589 ret = GetModuleFileNameW(libruby, wlibpath, len),
595 if (!ret || ret > len)
rb_fatal(
"failed to get module file name");
596 #if defined __CYGWIN__
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");
603 if (cygwin_conv_path(win_to_posix, wlibpath, libpath, newsize)) {
610 for (len = ret, i = 0; i < len; ++i) {
611 if (wlibpath[i] == L
'\\') {
617 len = WideCharToMultiByte(CP_UTF8, 0, wlibpath, ret, NULL, 0, NULL, NULL);
620 WideCharToMultiByte(CP_UTF8, 0, wlibpath, ret, libpath, len, NULL, NULL);
624 #elif defined(HAVE_DLADDR)
627 const void* addr = (
void *)(
VALUE)expand_include_path;
629 if (!dladdr((
void *)addr, &dli)) {
633 else if (origarg.argc > 0 && origarg.argv && dli.dli_fname == origarg.argv[0]) {
635 path = rb_readlink(fname, NULL);
640 path = rb_realpath_internal(
Qnil, fname, 1);
645 # error relative load path is not supported on this platform.
650 #define INITIAL_LOAD_PATH_MARK rb_intern_const("@gem_prelude_index")
652 VALUE ruby_archlibdir_path, ruby_prefix_path;
653 #if defined(__MACH__)
655 VALUE rb_libruby_selfpath;
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;
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
678 # define RUBY_ARCH_PATH "/"RUBY_PLATFORM
685 sopath = libruby_path;
688 p = strrchr(libpath,
'/');
690 static const char libdir[] =
"/"
691 #ifdef LIBDIR_BASENAME
697 const ptrdiff_t libdir_len = (ptrdiff_t)
sizeof(libdir)
699 static const char bindir[] =
"/bin";
700 const ptrdiff_t bindir_len = (ptrdiff_t)
sizeof(bindir) - 1;
702 const char *p2 = NULL;
704 #ifdef ENABLE_MULTIARCH
707 if (p - libpath >= bindir_len && !
STRNCASECMP(p - bindir_len, bindir, bindir_len)) {
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);
718 #ifdef ENABLE_MULTIARCH
725 if (p)
goto multiarch;
729 baselen = p - libpath;
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))
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)
745 ruby_prefix_path = PREFIX_PATH();
747 if (!archlibdir) archlibdir = ruby_prefix_path;
749 ruby_archlibdir_path = archlibdir;
751 load_path = GET_VM()->load_path;
753 ruby_push_include(getenv(
"RUBYLIB"), identical_path);
755 id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK;
757 size_t len = strlen(paths);
758 VALUE path = RUBY_RELATIVE(paths, len);
759 rb_ivar_set(path, id_initial_load_path_mark, path);
769 add_modules(
VALUE *req_list,
const char *mod)
771 VALUE list = *req_list;
782 require_libraries(
VALUE *req_list)
784 VALUE list = *req_list;
785 VALUE self = rb_vm_top_self();
807 process_sflag(
int *sflag)
825 if (s[1] ==
'-' && s[2] ==
'\0')
830 for (p = s + 1; *p; p++) {
839 else if (*p !=
'_' && !
ISALNUM(*p)) {
842 rb_str_new2(
"invalid name for global variable - ");
843 if (!(p = strchr(p,
'='))) {
849 name_error[1] = args[-1];
855 for (p = s + 1; *p; ++p) {
878 VALUE argstr, argary;
887 if (envopt) *p++ =
' ';
888 memcpy(p, s, len + 1);
894 while (*p && !
ISSPACE(*p)) ++p;
902 argv = ptr =
ALLOC_N(
char *, argc);
905 while ((i = proc_options(argc, argv, opt, envopt)) > 1 && envopt && (argc -= i) > 0) {
923 name_match_p(
const char *name,
const char *str,
size_t len)
925 if (len == 0)
return 0;
927 while (
TOLOWER(*str) == *name) {
928 if (!--len || !*++str)
return 1;
931 if (*str !=
'-' && *str !=
'_')
return 0;
933 if (*name !=
'-' && *name !=
'_')
return 0;
939 #define NAME_MATCH_P(name, str, len) \
940 ((len) < (int)sizeof(name) && name_match_p((name), (str), (len)))
942 #define UNSET_WHEN(name, bit, str, len) \
943 if (NAME_MATCH_P((name), (str), (len))) { \
944 *(unsigned int *)arg &= ~(bit); \
948 #define SET_WHEN(name, bit, str, len) \
949 if (NAME_MATCH_P((name), (str), (len))) { \
950 *(unsigned int *)arg |= (bit); \
954 #define LITERAL_NAME_ELEMENT(name) #name
957 feature_option(
const char *str,
int len,
void *arg,
const unsigned int enable)
959 static const char list[] = EACH_FEATURES(LITERAL_NAME_ELEMENT,
", ");
961 unsigned int mask = ~0
U;
962 unsigned int set = 0
U;
963 #if AMBIGUOUS_FEATURE_NAMES
965 # define FEATURE_FOUND ++matched
967 # define FEATURE_FOUND goto found
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)) {
973 #if defined(MJIT_FORCE_ENABLE) || !YJIT_SUPPORTED_P
974 set |= mask = FEATURE_BIT(mjit);
976 set |= mask = FEATURE_BIT(yjit);
980 if (NAME_MATCH_P(
"all", str, len)) {
982 #if defined(MJIT_FORCE_ENABLE) || !YJIT_SUPPORTED_P
983 mask &= ~(FEATURE_BIT(yjit));
985 mask &= ~(FEATURE_BIT(mjit));
989 #if AMBIGUOUS_FEATURE_NAMES
990 if (matched == 1)
goto found;
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, ", "); \
998 EACH_FEATURES(ADD_FEATURE_NAME, ;);
1001 #undef ADD_FEATURE_NAME
1006 rb_warn(
"unknown argument for --%s: `%.*s'",
1007 enable ?
"enable" :
"disable", len, str);
1008 rb_warn(
"features are [%.*s].", (
int)strlen(list), list);
1012 FEATURE_SET_TO(*argp, mask, (mask & enable));
1017 enable_option(
const char *str,
int len,
void *arg)
1019 feature_option(str, len, arg, ~0
U);
1023 disable_option(
const char *str,
int len,
void *arg)
1025 feature_option(str, len, arg, 0
U);
1029 int ruby_env_debug_option(
const char *str,
int len,
void *arg);
1032 debug_option(
const char *str,
int len,
void *arg)
1034 static const char list[] = EACH_DEBUG_FEATURES(LITERAL_NAME_ELEMENT,
", ");
1036 #define SET_WHEN_DEBUG(bit) \
1037 if (NAME_MATCH_P(#bit, str, len)) { \
1038 FEATURE_SET(*argp, DEBUG_BIT(bit)); \
1041 EACH_DEBUG_FEATURES(SET_WHEN_DEBUG, ;);
1043 if (
ruby_patchlevel < 0 && ruby_env_debug_option(str, len, 0))
return;
1045 rb_warn(
"unknown argument for --debug: `%.*s'", len, str);
1046 rb_warn(
"debug features are [%.*s].", (
int)strlen(list), list);
1050 dump_option(
const char *str,
int len,
void *arg)
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);
1060 set_option_encoding_once(
const char *
type,
VALUE *name,
const char *e,
long elen)
1064 if (!elen) elen = strlen(e);
1070 "%s already set to %"PRIsVALUE,
type, *name);
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))
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))
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))
1100 const char prefix[] =
"yjit-";
1101 if (strncmp(prefix, s,
sizeof(prefix)-1) != 0) {
1104 s +=
sizeof(prefix)-1;
1105 const size_t l = strlen(s);
1110 if (yjit_opt_match_arg(s, l,
"exec-mem-size")) {
1111 yjit_opt->exec_mem_size = atoi(s + 1);
1113 else if (yjit_opt_match_arg(s, l,
"call-threshold")) {
1114 yjit_opt->call_threshold = atoi(s + 1);
1116 else if (yjit_opt_match_arg(s, l,
"max-versions")) {
1117 yjit_opt->max_versions = atoi(s + 1);
1119 else if (yjit_opt_match_noarg(s, l,
"greedy-versioning")) {
1120 yjit_opt->greedy_versioning =
true;
1122 else if (yjit_opt_match_noarg(s, l,
"no-type-prop")) {
1123 yjit_opt->no_type_prop =
true;
1125 else if (yjit_opt_match_noarg(s, l,
"stats")) {
1126 yjit_opt->gen_stats =
true;
1130 "invalid yjit option `%s' (--help will show valid yjit options)", s);
1137 setup_mjit_options(
const char *s,
struct mjit_options *mjit_opt)
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;
1145 else if (opt_match(s, l,
"debug")) {
1147 mjit_opt->debug_flags =
strdup(s + 1);
1149 mjit_opt->debug = 1;
1151 else if (opt_match_noarg(s, l,
"wait")) {
1154 else if (opt_match_noarg(s, l,
"save-temps")) {
1155 mjit_opt->save_temps = 1;
1157 else if (opt_match(s, l,
"verbose")) {
1158 mjit_opt->verbose = *s ? atoi(s + 1) : 1;
1160 else if (opt_match_arg(s, l,
"max-cache")) {
1161 mjit_opt->max_cache_size = atoi(s + 1);
1163 else if (opt_match_arg(s, l,
"min-calls")) {
1164 mjit_opt->min_calls = atoi(s + 1);
1168 "invalid MJIT option `%s' (--help will show valid MJIT options)", s);
1176 long n, argc0 = argc;
1178 int warning = opt->warning;
1180 if (argc <= 0 || !argv)
1183 for (argc--, argv++; argc > 0; argc--, argv++) {
1184 const char *
const arg = argv[0];
1185 if (!arg || arg[0] !=
'-' || !arg[1])
1192 if (envopt)
goto noenvopt;
1193 opt->do_split = TRUE;
1198 if (envopt)
goto noenvopt;
1199 opt->do_print = TRUE;
1202 if (envopt)
goto noenvopt;
1203 opt->do_loop = TRUE;
1214 if (envopt)
goto noenvopt;
1215 opt->dump |= DUMP_BIT(yydebug);
1224 opt->dump |= DUMP_BIT(version_v);
1227 if (!opt->warning) {
1231 FEATURE_SET(opt->warn, RB_WARN_CATEGORY_ALL_BITS);
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)) {
1245 else if (NAME_MATCH_P(
"experimental", s, len)) {
1249 rb_warn(
"unknown warning category: `%s'", s);
1251 if (bits) FEATURE_SET_TO(opt->warn, bits, enable ? bits : 0);
1264 if (!opt->warning) {
1280 FEATURE_SET_TO(opt->warn, RB_WARN_CATEGORY_ALL_BITS, 0);
1286 FEATURE_SET(opt->warn, RB_WARN_CATEGORY_ALL_BITS);
1293 if (envopt)
goto noenvopt;
1294 opt->dump |= DUMP_BIT(syntax);
1299 if (envopt)
goto noenvopt;
1301 if (!opt->sflag) opt->sflag = 1;
1306 if (envopt)
goto noenvopt;
1307 opt->dump |= DUMP_BIT(usage);
1311 if (envopt)
goto noenvopt;
1312 opt->do_line = TRUE;
1318 if (envopt)
goto noenvopt;
1320 opt->do_search = TRUE;
1325 if (envopt)
goto noenvopt;
1332 if (!opt->e_script) {
1334 if (opt->script == 0)
1344 add_modules(&opt->req_list, s);
1346 else if (argc > 1) {
1347 add_modules(&opt->req_list, argv[1]);
1353 if (envopt)
goto noenvopt;
1355 ruby_set_inplace_mode(s + 1);
1359 if (envopt)
goto noenvopt;
1363 if (*s && chdir(s) < 0) {
1370 if (envopt)
goto noenvopt;
1371 if (!*++s && (!--argc || !(s = *++argv) || !*s)) {
1380 if (envopt)
goto noenvopt;
1387 if (!*++s && (!--argc || !(s = *++argv))) {
1393 set_internal_encoding_once(opt,
"UTF-8", 0);
1399 const char *enc_name = 0;
1402 enc_name =
"EUC-JP";
1405 enc_name =
"Windows-31J";
1410 case 'N':
case 'n':
case 'A':
case 'a':
1411 enc_name =
"ASCII-8BIT";
1416 if (!opt->ext.enc.name)
1417 opt->ext.enc.name = opt->src.enc.name;
1426 ruby_incpush_expand(s);
1427 else if (argc > 1) {
1428 ruby_incpush_expand(argv[1]);
1434 if (envopt)
goto noenvopt;
1444 else if (v == 0 && numlen >= 2) {
1455 if (!s[1] || (s[1] ==
'\r' && !s[2])) {
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) \
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)
1477 if (strcmp(
"copyright", s) == 0) {
1478 if (envopt)
goto noenvopt_long;
1479 opt->dump |= DUMP_BIT(copyright);
1490 else if (is_option_with_arg(
"enable",
Qtrue,
Qtrue)) {
1493 else if (is_option_with_arg(
"disable",
Qtrue,
Qtrue)) {
1496 else if (is_option_with_arg(
"encoding",
Qfalse,
Qtrue)) {
1500 # define set_encoding_part(type) \
1501 if (!(p = strchr(s, ':'))) { \
1502 set_##type##_encoding_once(opt, s, 0); \
1506 set_##type##_encoding_once(opt, s, p-s); \
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;
1517 (arg[1] ==
'-' ?
"--encoding" :
"-E"), s);
1518 # undef set_encoding_part
1521 else if (is_option_with_arg(
"internal-encoding",
Qfalse,
Qtrue)) {
1522 set_internal_encoding_once(opt, s, 0);
1524 else if (is_option_with_arg(
"external-encoding",
Qfalse,
Qtrue)) {
1525 set_external_encoding_once(opt, s, 0);
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);
1532 else if (strcmp(
"version", s) == 0) {
1533 if (envopt)
goto noenvopt_long;
1534 opt->dump |= DUMP_BIT(version);
1536 else if (strcmp(
"verbose", s) == 0) {
1540 else if (strcmp(
"jit", s) == 0) {
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));
1546 FEATURE_SET(opt->features, FEATURE_BIT(yjit));
1549 else if (strncmp(
"mjit", s, 4) == 0) {
1551 FEATURE_SET(opt->features, FEATURE_BIT(mjit));
1552 setup_mjit_options(s + 4, &opt->mjit);
1554 rb_warn(
"MJIT support is disabled.");
1557 else if (strcmp(
"yjit", s) == 0 || setup_yjit_options(s, &opt->yjit)) {
1559 FEATURE_SET(opt->features, FEATURE_BIT(yjit));
1561 rb_warn(
"Ruby was built without JIT support");
1564 else if (strcmp(
"yydebug", s) == 0) {
1565 if (envopt)
goto noenvopt_long;
1566 opt->dump |= DUMP_BIT(yydebug);
1571 else if (strcmp(
"help", s) == 0) {
1572 if (envopt)
goto noenvopt_long;
1573 opt->dump |= DUMP_BIT(help);
1576 else if (is_option_with_arg(
"backtrace-limit",
Qfalse,
Qfalse)) {
1578 long n = strtol(s, &e, 10);
1580 rb_backtrace_length_limit = n;
1584 "invalid option --%s (-h will show valid options)", s);
1595 "invalid option -%c (-h will show valid options)",
1596 (
int)(
unsigned char)*s);
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
1620 if (warning) opt->warning = warning;
1621 return argc0 - argc;
1624 void Init_builtin_features(
void);
1627 ruby_init_prelude(
void)
1629 Init_builtin_features();
1633 void rb_call_builtin_inits(
void);
1638 if (opt->dump & dump_exit_bits)
return;
1640 if (opt->features.set & FEATURE_BIT(gems)) {
1642 if (opt->features.set & FEATURE_BIT(error_highlight)) {
1645 if (opt->features.set & FEATURE_BIT(did_you_mean)) {
1650 rb_warning_category_update(opt->warn.mask, opt->warn.set);
1653 rb_call_builtin_inits();
1654 ruby_init_prelude();
1657 require_libraries(&opt->req_list);
1661 opt_enc_index(
VALUE enc_name)
1675 #define rb_progname (GET_VM()->progname)
1676 #define rb_orig_progname (GET_VM()->orig_progname)
1692 #define rb_define_readonly_boolean(name, val) \
1693 rb_define_virtual_variable((name), (val) ? true_value : false_value, 0)
1784 setup_pager_env(
void)
1793 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
1795 if (!GetConsoleMode(h, &m))
return 0;
1796 # ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
1797 # define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
1799 if (!(m & ENABLE_VIRTUAL_TERMINAL_PROCESSING))
return 0;
1802 #elif !defined(HAVE_WORKING_FORK)
1803 # define tty_enabled() 0
1830 char fbuf[MAXPATHLEN];
1831 int i = (int)proc_options(argc, argv, opt, 0);
1832 unsigned int dump = opt->dump & dump_exit_bits;
1834 const long loaded_before_enc =
RARRAY_LEN(vm->loaded_features);
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] :
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);
1850 #ifdef HAVE_WORKING_FORK
1853 rb_pid_t pid = rb_fork();
1858 else if (pid == 0) {
1876 int oldout = dup(1);
1877 int olderr = dup(2);
1878 int fd =
RFILE(port)->fptr->fd;
1879 tty = tty_enabled();
1882 usage(progname, 1, tty, columns);
1892 usage(progname, (opt->dump & DUMP_BIT(help)), tty, columns);
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;
1906 opt->src.enc.name = opt->ext.enc.name = opt->intern.enc.name = 0;
1907 moreswitches(s, opt, 1);
1909 opt->src.enc.name = src_enc_name;
1911 opt->ext.enc.name = ext_enc_name;
1913 opt->intern.enc.name = int_enc_name;
1914 FEATURE_SET_RESTORE(opt->features, feat);
1915 FEATURE_SET_RESTORE(opt->warn, warn);
1918 if (opt->src.enc.name)
1922 rb_warning(
"-K is specified; it is for 1.8 compatibility and may cause odd behavior");
1925 if (opt->features.set & FEATURE_BIT(mjit)) {
1926 opt->mjit.on = TRUE;
1929 if (opt->features.set & FEATURE_BIT(yjit)) {
1932 rb_warn(
"MJIT and YJIT cannot both be enabled at the same time. Exiting");
1936 rb_yjit_init(&opt->yjit);
1938 if (opt->dump & (DUMP_BIT(version) | DUMP_BIT(version_v))) {
1940 mjit_opts.on = opt->mjit.on;
1943 if (opt->dump & DUMP_BIT(version))
return Qtrue;
1945 if (opt->dump & DUMP_BIT(copyright)) {
1950 if (!opt->e_script) {
1957 opt->script = argv[0];
1958 if (!opt->script || opt->script[0] ==
'\0') {
1961 else if (opt->do_search) {
1962 const char *path = getenv(
"RUBYPATH");
1966 opt->script = dln_find_file_r(argv[0], path, fbuf,
sizeof(fbuf));
1969 opt->script = dln_find_file_r(argv[0], getenv(
PATH_ENV), fbuf,
sizeof(fbuf));
1972 opt->script = argv[0];
1977 if (opt->script[0] ==
'-' && !opt->script[1]) {
1978 forbid_setid(
"program input from stdin");
1986 translit_char_bin(
RSTRING_PTR(opt->script_name),
'\\',
'/');
1987 #elif defined DOSISH
1988 translit_char(
RSTRING_PTR(opt->script_name),
'\\',
'/');
1991 ruby_gc_set_params();
1997 mjit_init(&opt->mjit);
2000 Init_ruby_description();
2005 parser = rb_parser_new();
2006 if (opt->dump & DUMP_BIT(yydebug)) {
2007 rb_parser_set_yydebug(parser,
Qtrue);
2009 if (opt->ext.enc.name != 0) {
2010 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2012 if (opt->intern.enc.name != 0) {
2013 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
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;
2019 if (opt->ext.enc.index >= 0) {
2023 enc = IF_UTF8_PATH(uenc, lenc);
2026 if (opt->intern.enc.index >= 0) {
2029 opt->intern.enc.index = -1;
2034 script_name = opt->script_name;
2038 opt->script_name = str_conv_enc(opt->script_name, uenc, lenc);
2043 if (IF_UTF8_PATH(uenc != lenc, 1)) {
2045 VALUE load_path = vm->load_path;
2046 const ID id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK;
2047 int modifiable = FALSE;
2049 rb_get_expanded_load_path();
2050 for (i = 0; i <
RARRAY_LEN(load_path); ++i) {
2052 int mark =
rb_attr_get(path, id_initial_load_path_mark) == path;
2055 if (newpath == path)
continue;
2058 if (!(path = copy_str(path, lenc, !mark)))
continue;
2060 if (mark)
rb_ivar_set(path, id_initial_load_path_mark, path);
2072 VALUE loaded_features = vm->loaded_features;
2073 bool modified =
false;
2074 for (
long i = loaded_before_enc; i <
RARRAY_LEN(loaded_features); ++i) {
2076 if (!(path = copy_str(path, IF_UTF8_PATH(uenc, lenc),
true)))
continue;
2085 if (opt->features.mask & COMPILATION_FEATURES) {
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);
2093 #undef SET_COMPILE_OPTION
2096 process_sflag(&opt->sflag);
2098 rb_parser_set_context(parser, 0, TRUE);
2100 if (opt->e_script) {
2101 VALUE progname = rb_progname;
2103 if (opt->src.enc.index >= 0) {
2109 if (ienc) eenc = ienc;
2114 opt->e_script = str_conv_enc(opt->e_script, uenc, eenc);
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);
2126 f = open_load_file(script_name, &opt->xflag);
2127 ast = load_file(parser, opt->script_name, f, 1, opt);
2130 if (dump & DUMP_BIT(yydebug)) {
2131 dump &= ~DUMP_BIT(yydebug);
2132 if (!dump)
return Qtrue;
2135 if (opt->ext.enc.index >= 0) {
2139 enc = IF_UTF8_PATH(uenc, lenc);
2142 if (opt->intern.enc.index >= 0) {
2150 rb_stdio_set_default_encoding();
2152 if (!ast->body.root) {
2153 rb_ast_dispose(ast);
2157 process_sflag(&opt->sflag);
2160 if (dump & DUMP_BIT(syntax)) {
2161 printf(
"Syntax OK\n");
2162 dump &= ~DUMP_BIT(syntax);
2163 if (!dump)
return Qtrue;
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);
2178 rb_ast_dispose(ast);
2185 if (!opt->e_script && strcmp(opt->script,
"-")) {
2186 path = rb_realpath_internal(
Qnil, script_name, 1);
2189 path = str_conv_enc(path, uenc, lenc);
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);
2205 if (dump & (DUMP_BIT(insns) | DUMP_BIT(insns_without_opt))) {
2208 dump &= ~DUMP_BIT(insns);
2209 if (!dump)
return Qtrue;
2211 if (opt->dump & dump_exit_bits)
return Qtrue;
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);
2217 rb_gvar_ractor_local(
"$-p");
2218 rb_gvar_ractor_local(
"$-l");
2219 rb_gvar_ractor_local(
"$-a");
2221 if ((rb_e_script = opt->e_script) != 0) {
2229 if (opt->e_script) {
2231 rb_exec_event_hook_script_compiled(ec, iseq, opt->e_script);
2235 rb_exec_event_hook_script_compiled(ec, iseq,
Qnil);
2243 warn_cr_in_shebang(
const char *str,
long len)
2245 if (str[len-1] ==
'\n' && str[len-2] ==
'\r') {
2246 rb_warn(
"shebang line ending with \\r may cause problems");
2250 #define warn_cr_in_shebang(str, len) (void)0
2262 load_file_internal(
VALUE argp_v)
2265 VALUE parser = argp->parser;
2266 VALUE orig_fname = argp->fname;
2267 int script = argp->script;
2275 CONST_ID(set_encoding,
"set_encoding");
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;
2294 if (len > 2 && str[0] ==
'#' && str[1] ==
'!') {
2295 if (line_start == 1) warn_cr_in_shebang(str, len);
2309 warn_cr_in_shebang(str, len);
2312 goto search_shebang;
2317 if (*str ==
'\n') *str-- =
'\0';
2318 if (*str ==
'\r') *str-- =
'\0';
2320 if ((p = strstr(p,
" -")) != 0) {
2322 moreswitches(p + 1, opt, 0);
2328 else if (!
NIL_P(c)) {
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;
2336 if (no_ext_enc && opt->ext.enc.name) {
2337 opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
2339 if (no_int_enc && opt->intern.enc.name) {
2340 opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
2343 else if (!
NIL_P(c)) {
2351 if (opt->src.enc.index >= 0) {
2360 rb_parser_set_options(parser, opt->do_print, opt->do_loop,
2361 opt->do_line, opt->do_split);
2365 return (
VALUE)rb_parser_compile_string_path(parser, orig_fname, f, line_start);
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)) {
2391 disable_nonblock(
int fd)
2393 #if defined(HAVE_FCNTL) && defined(F_SETFL)
2394 if (fcntl(fd, F_SETFL, 0) < 0) {
2395 const int e = errno;
2397 # if defined ENOTSUP
2398 if (e == ENOTSUP)
return 0;
2400 # if defined B_UNSUPPORTED
2401 if (e == B_UNSUPPORTED)
return 0;
2410 open_load_file(
VALUE fname_v,
int *xflag)
2418 if (flen == 1 && fname[0] ==
'-') {
2425 #if defined O_NONBLOCK && HAVE_FCNTL && !(O_NONBLOCK & O_ACCMODE)
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)
2431 # define MODE_TO_LOAD (O_RDONLY)
2433 int mode = MODE_TO_LOAD;
2434 #if defined DOSISH || defined __CYGWIN__
2435 # define isdirsep(x) ((x) == '/' || (x) == '\\')
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) {
2449 if (!rb_gc_for_fd(e)) {
2450 rb_load_fail(fname_v, strerror(e));
2453 rb_load_fail(fname_v, strerror(errno));
2458 if (MODE_TO_LOAD != O_RDONLY && (e = disable_nonblock(fd)) != 0) {
2460 rb_load_fail(fname_v, strerror(e));
2463 e = ruby_is_fd_loadable(fd);
2467 rb_load_fail(fname_v, strerror(e));
2483 restore_load_file(
VALUE arg)
2498 arg.parser = parser;
2500 arg.script = script;
2504 restore_load_file, (
VALUE)&arg);
2517 return rb_parser_load_file(rb_parser_new(), fname_v);
2521 rb_parser_load_file(
VALUE parser,
VALUE fname_v)
2524 VALUE f = open_load_file(fname_v, &cmdline_options_init(&opt)->xflag);
2525 return load_file(parser, fname_v, f, 0, &opt);
2540 proc_argv0(
VALUE process)
2542 return rb_orig_progname;
2565 proc_setproctitle(
VALUE process,
VALUE title)
2567 return ruby_setproctitle(title);
2571 ruby_setproctitle(
VALUE title)
2581 if (origarg.argv == 0)
2588 external_str_new_cstr(
const char *p)
2603 rb_orig_progname = rb_progname = external_str_new_cstr(name);
2604 rb_vm_set_progname(rb_progname);
2615 rb_orig_progname = rb_progname =
rb_str_dup(name);
2616 rb_vm_set_progname(rb_progname);
2622 rb_uid_t uid = getuid();
2623 rb_uid_t euid = geteuid();
2624 rb_gid_t gid = getgid();
2625 rb_gid_t egid = getegid();
2627 if (uid != euid) opt->setids |= 1;
2628 if (egid != gid) opt->setids |= 2;
2635 if (opt->setids & 1)
2637 if (opt->setids & 2)
2642 verbose_getter(
ID id,
VALUE *ptr)
2654 opt_W_getter(
ID id,
VALUE *dmy)
2671 debug_getter(
ID id,
VALUE *dmy)
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");
2721 for (i = 0; i < argc; i++) {
2722 VALUE arg = external_str_new_cstr(argv[i]);
2734 const char *script_name = (argc > 0 && argv[0]) ? argv[0] :
ruby_engine;
2736 if (!origarg.argv || origarg.argc <= 0) {
2737 origarg.argc = argc;
2738 origarg.argv = argv;
2743 iseq = process_options(argc, argv, cmdline_options_init(&opt));
2745 #ifndef HAVE_SETPROCTITLE
2746 ruby_init_setproctitle(argc, argv);
2749 return (
void*)(
struct RData*)iseq;
2753 fill_standard_fds(
void)
2755 int f0, f1, f2, fds[2];
2757 f0 = fstat(0, &buf) == -1 && errno == EBADF;
2758 f1 = fstat(1, &buf) == -1 && errno == EBADF;
2759 f2 = fstat(2, &buf) == -1 && errno == EBADF;
2761 if (pipe(fds) == 0) {
2770 if (pipe(fds) == 0) {
2772 if (f1 && fds[1] != 1)
2774 if (f2 && fds[1] != 2)
2776 if (fds[1] != 1 && fds[1] != 2)
2786 rb_w32_sysinit(argc, argv);
2788 if (*argc >= 0 && *argv) {
2789 origarg.argc = *argc;
2790 origarg.argv = *argv;
2792 fill_standard_fds();
#define RUBY_EXTERN
Declaration of externally visible global variables.
#define PATH_SEP_CHAR
Identical to PATH_SEP, except it is of type char.
VALUE rb_define_module(const char *name)
Defines a top-level module.
void rb_define_module_function(VALUE module, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a module function for a module.
void rb_define_global_function(const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a global function.
#define rb_str_new2
Old name of rb_str_new_cstr.
#define ISSPACE
Old name of rb_isspace.
#define T_STRING
Old name of RUBY_T_STRING.
#define INT2FIX
Old name of RB_INT2FIX.
#define OBJ_FREEZE_RAW
Old name of RB_OBJ_FREEZE_RAW.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
#define ECONV_UNDEF_REPLACE
Old name of RUBY_ECONV_UNDEF_REPLACE.
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
#define ECONV_INVALID_REPLACE
Old name of RUBY_ECONV_INVALID_REPLACE.
#define ASSUME
Old name of RBIMPL_ASSUME.
#define ALLOC_N
Old name of RB_ALLOC_N.
#define STRNCASECMP
Old name of st_locale_insensitive_strncasecmp.
#define TOLOWER
Old name of rb_tolower.
#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.
#define NIL_P
Old name of RB_NIL_P.
#define scan_oct(s, l, e)
Old name of ruby_scan_oct.
#define CONST_ID
Old name of RUBY_CONST_ID.
#define ISALNUM
Old name of rb_isalnum.
#define rb_str_new4
Old name of rb_str_new_frozen.
void ruby_script(const char *name)
Sets the current script name to this value.
void ruby_set_argv(int argc, char **argv)
Sets argv that ruby understands.
void ruby_set_script_name(VALUE name)
Sets the current script name to this value.
void ruby_init_loadpath(void)
Sets up $LOAD_PATH.
void * ruby_process_options(int argc, char **argv)
Identical to ruby_options(), except it raises ruby-level exceptions on failure.
void ruby_prog_init(void)
Defines built-in variables.
void ruby_incpush(const char *path)
Appends the given path to the end of the load path.
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
VALUE rb_eTypeError
TypeError exception.
void rb_fatal(const char *fmt,...)
Raises the unsung "fatal" exception.
VALUE rb_eNameError
NameError exception.
VALUE rb_eRuntimeError
RuntimeError exception.
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports always regardless of runtime -W flag.
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.
VALUE * rb_ruby_debug_ptr(void)
This is an implementation detail of ruby_debug.
void rb_loaderror(const char *fmt,...)
Raises an instance of rb_eLoadError.
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
VALUE * rb_ruby_verbose_ptr(void)
This is an implementation detail of ruby_verbose.
VALUE rb_eSecurityError
SecurityError exception.
void rb_warning(const char *fmt,...)
Issues a warning.
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
@ RB_WARN_CATEGORY_EXPERIMENTAL
Warning is for experimental features.
VALUE rb_mProcess
Process module.
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
VALUE rb_stdin
STDIN constant.
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
VALUE rb_stdout
STDOUT constant.
VALUE rb_cString
String class.
void ruby_show_copyright(void)
Prints the copyright notice of the CRuby interpreter to stdout.
void ruby_sysinit(int *argc, char ***argv)
Initializes the process for libruby.
void ruby_show_version(void)
Prints the version information of the CRuby interpreter to stdout.
rb_encoding * rb_locale_encoding(void)
Queries the encoding that represents the current locale.
rb_encoding * rb_default_external_encoding(void)
Queries the "default external" encoding.
int rb_enc_dummy_p(rb_encoding *enc)
Queries if the passed encoding is dummy.
VALUE rb_enc_associate(VALUE obj, rb_encoding *enc)
Identical to rb_enc_associate(), except it takes an encoding itself instead of its index.
void rb_enc_copy(VALUE dst, VALUE src)
Destructively copies the encoding of the latter object to that of former one.
rb_encoding * rb_default_internal_encoding(void)
Queries the "default internal" encoding.
rb_encoding * rb_ascii8bit_encoding(void)
Queries the encoding that represents ASCII-8BIT a.k.a.
void rb_enc_set_default_internal(VALUE encoding)
Destructively assigns the passed encoding as the default internal encoding.
VALUE rb_enc_from_encoding(rb_encoding *enc)
Queries the Ruby-level counterpart instance of rb_cEncoding that corresponds to the passed encoding.
rb_encoding * rb_utf8_encoding(void)
Queries the encoding that represents UTF-8.
rb_encoding * rb_enc_from_index(int idx)
Identical to rb_find_encoding(), except it takes an encoding index instead of a Ruby object.
void rb_enc_set_default_external(VALUE encoding)
Destructively assigns the passed encoding as the default external encoding.
int rb_enc_find_index(const char *name)
Queries the index of the encoding.
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
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.
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.
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.
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
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.
void rb_gc_register_address(VALUE *valptr)
Inform the garbage collector that valptr points to a live Ruby object that should not be moved.
void rb_gc_register_mark_object(VALUE object)
Inform the garbage collector that object is a live Ruby object that should not be moved.
VALUE rb_ary_shift(VALUE ary)
Destructively deletes an element from the beginning of the passed array and returns what was deleted.
void rb_ary_modify(VALUE ary)
Declares that the array is about to be modified.
VALUE rb_ary_replace(VALUE copy, VALUE orig)
Replaces the contents of the former object with the contents of the latter.
VALUE rb_ary_tmp_new(long capa)
Allocates a "temporary" array.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_str_encode_ospath(VALUE path)
Converts a string into an "OS Path" encoding, if any.
VALUE rb_file_expand_path(VALUE fname, VALUE dname)
Identical to rb_file_absolute_path(), except it additionally understands ~.
VALUE rb_hash_new(void)
Creates a new, empty hash object.
VALUE rb_io_gets(VALUE io)
Reads a "line" from the given IO.
VALUE rb_rs
The record separator character for inputs, or the $/.
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.
VALUE rb_io_getbyte(VALUE io)
Reads a byte from the given IO.
VALUE rb_io_fdopen(int fd, int flags, const char *path)
Creates an IO instance whose backend is the given file descriptor.
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
VALUE rb_io_write(VALUE io, VALUE str)
Writes the given string to the given IO.
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
VALUE rb_fs
The field separator character for inputs, or the $;.
VALUE rb_output_rs
The record separator character for outputs, or the $\.
VALUE rb_io_flush(VALUE io)
Flushes any buffered data within the passed IO to the underlying operating system.
int rb_pipe(int *pipes)
This is an rb_cloexec_pipe() + rb_update_max_fd() combo.
VALUE rb_io_close(VALUE io)
Closes the IO.
void rb_lastline_set(VALUE str)
Updates $_.
VALUE rb_lastline_get(void)
Queries the last line, or the $_.
rb_pid_t rb_waitpid(rb_pid_t pid, int *status, int flags)
Waits for a process, with releasing GVL.
VALUE rb_f_exec(int argc, const VALUE *argv)
Replaces the current process by running the given external command.
VALUE rb_reg_new(const char *src, long len, int opts)
Creates a new Regular expression.
VALUE rb_utf8_str_new(const char *ptr, long len)
Identical to rb_str_new(), except it generates a string of "UTF-8" encoding.
VALUE rb_utf8_str_new_cstr(const char *ptr)
Identical to rb_str_new_cstr(), except it generates a string of "UTF-8" encoding.
#define rb_str_new_lit(str)
Identical to rb_str_new_static(), except it cannot take string variables.
VALUE rb_str_tmp_new(long len)
Allocates a "temporary" string.
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...
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
VALUE rb_str_cat2(VALUE, const char *)
Just another name of rb_str_cat_cstr.
VALUE rb_str_dup(VALUE str)
Duplicates a string.
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
#define rb_strlen_lit(str)
Length of a string literal.
VALUE rb_str_freeze(VALUE str)
This is the implementation of String#freeze.
VALUE rb_str_new(const char *ptr, long len)
Allocates an instance of rb_cString.
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.
VALUE rb_str_resize(VALUE str, long len)
Overwrites the length of the string.
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
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.
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.
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
VALUE rb_attr_get(VALUE obj, ID name)
Identical to rb_ivar_get()
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.
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
VALUE rb_const_remove(VALUE space, ID name)
Identical to rb_mod_remove_const(), except it takes the name as ID instead of VALUE.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
void rb_define_global_const(const char *name, VALUE val)
Identical to rb_define_const(), except it defines that of "global", i.e.
rb_gvar_setter_t rb_gvar_readonly_setter
This function just raises rb_eNameError.
VALUE rb_gv_set(const char *name, VALUE val)
Assigns to a global variable.
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.
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.
@ RUBY_IO_READABLE
IO::READABLE
VALUE rb_io_wait(VALUE io, VALUE events, VALUE timeout)
Blocks until the passed IO is ready for the passed events.
void ruby_setenv(const char *key, const char *val)
Sets an environment variable.
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.
const char ruby_engine[]
This is just "ruby" for us.
const int ruby_patchlevel
This is a monotonic increasing integer that describes specific "patch" level.
#define RB_INT2NUM
Just another name of rb_int2num_inline.
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
VALUE type(ANYARGS)
ANYARGS-ed function type.
char * rb_enc_path_last_separator(const char *path, const char *end, rb_encoding *enc)
Returns the last path component.
#define RARRAY_LEN
Just another name of rb_array_len.
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
#define RARRAY_AREF(a, i)
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
#define RFILE(obj)
Convenient casting macro.
@ RSTRING_EMBED_LEN_MAX
Max possible number of characters that can be embedded.
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
static int RSTRING_LENINT(VALUE str)
Identical to RSTRING_LEN(), except it differs for the return type.
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
static long RSTRING_LEN(VALUE str)
Queries the length of the string.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
VALUE rb_argv0
The value of $0 at process bootup.
void * rb_load_file(const char *file)
Loads the given file.
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.
#define rb_argv
Just another name of rb_get_argv.
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
uintptr_t VALUE
Type that represents a Ruby object.
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
void ruby_xfree(void *ptr)
Deallocates a storage instance.