Ruby  2.5.0dev(2017-10-22revision60238)
ruby.c
Go to the documentation of this file.
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 #ifdef __CYGWIN__
15 #include <windows.h>
16 #include <sys/cygwin.h>
17 #endif
18 #include "internal.h"
19 #include "ruby/thread.h"
20 #include "eval_intern.h"
21 #include "dln.h"
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <ctype.h>
25 
26 #ifdef __hpux
27 #include <sys/pstat.h>
28 #endif
29 #if defined(LOAD_RELATIVE) && defined(HAVE_DLADDR)
30 #include <dlfcn.h>
31 #endif
32 
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #if defined(HAVE_FCNTL_H)
37 #include <fcntl.h>
38 #elif defined(HAVE_SYS_FCNTL_H)
39 #include <sys/fcntl.h>
40 #endif
41 #ifdef HAVE_SYS_PARAM_H
42 # include <sys/param.h>
43 #endif
44 #ifndef MAXPATHLEN
45 # define MAXPATHLEN 1024
46 #endif
47 #ifndef O_ACCMODE
48 # define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
49 #endif
50 
51 #include "ruby/util.h"
52 
53 #ifndef HAVE_STDLIB_H
54 char *getenv();
55 #endif
56 
57 #ifndef DISABLE_RUBYGEMS
58 # define DISABLE_RUBYGEMS 0
59 #endif
60 #if DISABLE_RUBYGEMS
61 #define DEFAULT_RUBYGEMS_ENABLED "disabled"
62 #else
63 #define DEFAULT_RUBYGEMS_ENABLED "enabled"
64 #endif
65 
66 #define COMMA ,
67 #define FEATURE_BIT(bit) (1U << feature_##bit)
68 #define EACH_FEATURES(X, SEP) \
69  X(gems) \
70  SEP \
71  X(did_you_mean) \
72  SEP \
73  X(rubyopt) \
74  SEP \
75  X(frozen_string_literal) \
76  /* END OF FEATURES */
77 #define EACH_DEBUG_FEATURES(X, SEP) \
78  X(frozen_string_literal) \
79  /* END OF DEBUG FEATURES */
80 #define AMBIGUOUS_FEATURE_NAMES 0 /* no ambiguous feature names now */
81 #define DEFINE_FEATURE(bit) feature_##bit
82 #define DEFINE_DEBUG_FEATURE(bit) feature_debug_##bit
89 };
90 
91 #define DEBUG_BIT(bit) (1U << feature_debug_##bit)
92 
93 #define DUMP_BIT(bit) (1U << dump_##bit)
94 #define DEFINE_DUMP(bit) dump_##bit
95 #define EACH_DUMPS(X, SEP) \
96  X(version) \
97  SEP \
98  X(copyright) \
99  SEP \
100  X(usage) \
101  SEP \
102  X(help) \
103  SEP \
104  X(yydebug) \
105  SEP \
106  X(syntax) \
107  SEP \
108  X(parsetree) \
109  SEP \
110  X(parsetree_with_comment) \
111  SEP \
112  X(insns) \
113  /* END OF DUMPS */
118  DUMP_BIT(parsetree) | DUMP_BIT(parsetree_with_comment) |
119  DUMP_BIT(insns))
120 };
121 
123 
125  const char *script;
128  struct {
129  struct {
131  int index;
132  } enc;
133  } src, ext, intern;
135  unsigned int features;
136  unsigned int dump;
138  int sflag, xflag;
139  unsigned int warning: 1;
140  unsigned int verbose: 1;
141  unsigned int do_loop: 1;
142  unsigned int do_print: 1;
143  unsigned int do_line: 1;
144  unsigned int do_split: 1;
145  unsigned int do_search: 1;
146  unsigned int setids: 2;
147 };
148 
149 static void init_ids(ruby_cmdline_options_t *);
150 
151 #define src_encoding_index GET_VM()->src_encoding_index
152 
153 enum {
155  0
156  | FEATURE_BIT(frozen_string_literal)
157  | FEATURE_BIT(debug_frozen_string_literal)
158  ),
160  (FEATURE_BIT(debug_flag_first)-1)
161 #if DISABLE_RUBYGEMS
162  & ~FEATURE_BIT(gems)
163 #endif
164  & ~FEATURE_BIT(frozen_string_literal)
165  )
166 };
167 
168 static ruby_cmdline_options_t *
169 cmdline_options_init(ruby_cmdline_options_t *opt)
170 {
171  MEMZERO(opt, *opt, 1);
172  init_ids(opt);
173  opt->src.enc.index = src_encoding_index;
174  opt->ext.enc.index = -1;
175  opt->intern.enc.index = -1;
176  opt->features = DEFAULT_FEATURES;
177  return opt;
178 }
179 
180 static NODE *load_file(VALUE parser, VALUE fname, VALUE f, int script,
182 static VALUE open_load_file(VALUE fname_v, int *xflag);
183 static void forbid_setid(const char *, const ruby_cmdline_options_t *);
184 #define forbid_setid(s) forbid_setid((s), opt)
185 
186 static struct {
187  int argc;
188  char **argv;
189 } origarg;
190 
191 static void
192 show_usage_line(const char *str, unsigned int namelen, unsigned int secondlen, int help)
193 {
194  const unsigned int w = 16;
195  const int wrap = help && namelen + secondlen - 2 > w;
196  printf(" %.*s%-*.*s%-*s%s\n", namelen-1, str,
197  (wrap ? 0 : w - namelen + 1),
198  (help ? secondlen-1 : 0), str + namelen,
199  (wrap ? w + 3 : 0), (wrap ? "\n" : ""),
200  str + namelen + secondlen);
201 }
202 
203 static void
204 usage(const char *name, int help)
205 {
206  /* This message really ought to be max 23 lines.
207  * Removed -h because the user already knows that option. Others? */
208 
209  struct message {
210  const char *str;
211  unsigned short namelen, secondlen;
212  };
213 #define M(shortopt, longopt, desc) { \
214  shortopt " " longopt " " desc, \
215  (unsigned short)sizeof(shortopt), \
216  (unsigned short)sizeof(longopt), \
217 }
218  static const struct message usage_msg[] = {
219  M("-0[octal]", "", "specify record separator (\\0, if no argument)"),
220  M("-a", "", "autosplit mode with -n or -p (splits $_ into $F)"),
221  M("-c", "", "check syntax only"),
222  M("-Cdirectory", "", "cd to directory before executing your script"),
223  M("-d", ", --debug", "set debugging flags (set $DEBUG to true)"),
224  M("-e 'command'", "", "one line of script. Several -e's allowed. Omit [programfile]"),
225  M("-Eex[:in]", ", --encoding=ex[:in]", "specify the default external and internal character encodings"),
226  M("-Fpattern", "", "split() pattern for autosplit (-a)"),
227  M("-i[extension]", "", "edit ARGV files in place (make backup if extension supplied)"),
228  M("-Idirectory", "", "specify $LOAD_PATH directory (may be used more than once)"),
229  M("-l", "", "enable line ending processing"),
230  M("-n", "", "assume 'while gets(); ... end' loop around your script"),
231  M("-p", "", "assume loop like -n but print line also like sed"),
232  M("-rlibrary", "", "require the library before executing your script"),
233  M("-s", "", "enable some switch parsing for switches after script name"),
234  M("-S", "", "look for the script using PATH environment variable"),
235  M("-T[level=1]", "", "turn on tainting checks"),
236  M("-v", ", --verbose", "print version number, then turn on verbose mode"),
237  M("-w", "", "turn warnings on for your script"),
238  M("-W[level=2]", "", "set warning level; 0=silence, 1=medium, 2=verbose"),
239  M("-x[directory]", "", "strip off text before #!ruby line and perhaps cd to directory"),
240  M("-h", "", "show this message, --help for more info"),
241  };
242  static const struct message help_msg[] = {
243  M("--copyright", "", "print the copyright"),
244  M("--dump={insns|parsetree|...}[,...]", "",
245  "dump debug information. see below for available dump list"),
246  M("--enable={gems|rubyopt|...}[,...]", ", --disable={gems|rubyopt|...}[,...]",
247  "enable or disable features. see below for available features"),
248  M("--external-encoding=encoding", ", --internal-encoding=encoding",
249  "specify the default external or internal character encoding"),
250  M("--version", "", "print the version"),
251  M("--help", "", "show this message, -h for short message"),
252  };
253  static const struct message dumps[] = {
254  M("insns", "", "instruction sequences"),
255  M("yydebug", "", "yydebug of yacc parser generator"),
256  M("parsetree", "", "AST"),
257  M("parsetree_with_comment", "", "AST with comments"),
258  };
259  static const struct message features[] = {
260  M("gems", "", "rubygems (default: "DEFAULT_RUBYGEMS_ENABLED")"),
261  M("did_you_mean", "", "did_you_mean (default: "DEFAULT_RUBYGEMS_ENABLED")"),
262  M("rubyopt", "", "RUBYOPT environment variable (default: enabled)"),
263  M("frozen-string-literal", "", "freeze all string literals (default: disabled)"),
264  };
265  int i;
266  const int num = numberof(usage_msg) - (help ? 1 : 0);
267 #define SHOW(m) show_usage_line((m).str, (m).namelen, (m).secondlen, help)
268 
269  printf("Usage: %s [switches] [--] [programfile] [arguments]\n", name);
270  for (i = 0; i < num; ++i)
271  SHOW(usage_msg[i]);
272 
273  if (!help) return;
274 
275  for (i = 0; i < numberof(help_msg); ++i)
276  SHOW(help_msg[i]);
277  puts("Dump List:");
278  for (i = 0; i < numberof(dumps); ++i)
279  SHOW(dumps[i]);
280  puts("Features:");
281  for (i = 0; i < numberof(features); ++i)
282  SHOW(features[i]);
283 }
284 
285 #define rubylib_path_new rb_str_new
286 
287 static void
288 push_include(const char *path, VALUE (*filter)(VALUE))
289 {
290  const char sep = PATH_SEP_CHAR;
291  const char *p, *s;
292  VALUE load_path = GET_VM()->load_path;
293 
294  p = path;
295  while (*p) {
296  while (*p == sep)
297  p++;
298  if (!*p) break;
299  for (s = p; *s && *s != sep; s = CharNext(s));
300  rb_ary_push(load_path, (*filter)(rubylib_path_new(p, s - p)));
301  p = s;
302  }
303 }
304 
305 #ifdef __CYGWIN__
306 static void
307 push_include_cygwin(const char *path, VALUE (*filter)(VALUE))
308 {
309  const char *p, *s;
310  char rubylib[FILENAME_MAX];
311  VALUE buf = 0;
312 
313  p = path;
314  while (*p) {
315  unsigned int len;
316  while (*p == ';')
317  p++;
318  if (!*p) break;
319  for (s = p; *s && *s != ';'; s = CharNext(s));
320  len = s - p;
321  if (*s) {
322  if (!buf) {
323  buf = rb_str_new(p, len);
324  p = RSTRING_PTR(buf);
325  }
326  else {
327  rb_str_resize(buf, len);
328  p = strncpy(RSTRING_PTR(buf), p, len);
329  }
330  }
331 #ifdef HAVE_CYGWIN_CONV_PATH
332 #define CONV_TO_POSIX_PATH(p, lib) \
333  cygwin_conv_path(CCP_WIN_A_TO_POSIX|CCP_RELATIVE, (p), (lib), sizeof(lib))
334 #else
335 # error no cygwin_conv_path
336 #endif
337  if (CONV_TO_POSIX_PATH(p, rubylib) == 0)
338  p = rubylib;
339  push_include(p, filter);
340  if (!*s) break;
341  p = s + 1;
342  }
343 }
344 
345 #define push_include push_include_cygwin
346 #endif
347 
348 void
349 ruby_push_include(const char *path, VALUE (*filter)(VALUE))
350 {
351  if (path == 0)
352  return;
353  push_include(path, filter);
354 }
355 
356 static VALUE
357 identical_path(VALUE path)
358 {
359  return path;
360 }
361 static VALUE
362 locale_path(VALUE path)
363 {
365  return path;
366 }
367 
368 void
369 ruby_incpush(const char *path)
370 {
371  ruby_push_include(path, locale_path);
372 }
373 
374 static VALUE
375 expand_include_path(VALUE path)
376 {
377  char *p = RSTRING_PTR(path);
378  if (!p)
379  return path;
380  if (*p == '.' && p[1] == '/')
381  return path;
382  return rb_file_expand_path(path, Qnil);
383 }
384 
385 void
386 ruby_incpush_expand(const char *path)
387 {
388  ruby_push_include(path, expand_include_path);
389 }
390 
391 #undef UTF8_PATH
392 #if defined _WIN32 || defined __CYGWIN__
393 static HMODULE libruby;
394 
395 BOOL WINAPI
396 DllMain(HINSTANCE dll, DWORD reason, LPVOID reserved)
397 {
398  if (reason == DLL_PROCESS_ATTACH)
399  libruby = dll;
400  return TRUE;
401 }
402 
403 HANDLE
404 rb_libruby_handle(void)
405 {
406  return libruby;
407 }
408 
409 static inline void
410 translit_char_bin(char *p, int from, int to)
411 {
412  while (*p) {
413  if ((unsigned char)*p == from)
414  *p = to;
415  p++;
416  }
417 }
418 #endif
419 
420 #ifdef _WIN32
421 # define UTF8_PATH 1
422 #endif
423 
424 #ifndef UTF8_PATH
425 # define UTF8_PATH 0
426 #endif
427 #if UTF8_PATH
428 # define IF_UTF8_PATH(t, f) t
429 #else
430 # define IF_UTF8_PATH(t, f) f
431 #endif
432 
433 #if UTF8_PATH
434 static VALUE
435 str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
436 {
437  return rb_str_conv_enc_opts(str, from, to,
439  Qnil);
440 }
441 #else
442 # define str_conv_enc(str, from, to) (str)
443 #endif
444 
446 
447 void
449 {
451 }
452 
453 #if defined(LOAD_RELATIVE) && defined(HAVE_DLADDR) && !defined(__CYGWIN__)
454 static VALUE
455 dladdr_path(const void* addr)
456 {
457  Dl_info dli;
458  VALUE fname, path;
459 
460  if (!dladdr(addr, &dli)) {
461  return rb_str_new(0, 0);
462  }
463 #ifdef __linux__
464  else if (origarg.argc > 0 && origarg.argv && dli.dli_fname == origarg.argv[0]) {
465  fname = rb_str_new_cstr("/proc/self/exe");
466  path = rb_readlink(fname, NULL);
467  }
468 #endif
469  else {
470  fname = rb_str_new_cstr(dli.dli_fname);
471  path = rb_realpath_internal(Qnil, fname, 1);
472  }
473  rb_str_resize(fname, 0);
474  return path;
475 }
476 #endif
477 
478 #define INITIAL_LOAD_PATH_MARK rb_intern_const("@gem_prelude_index")
479 
480 void
482 {
483  VALUE load_path;
484  ID id_initial_load_path_mark;
485  const char *paths = ruby_initial_load_paths;
486 #if defined LOAD_RELATIVE
487 # if defined HAVE_DLADDR || defined __CYGWIN__ || defined _WIN32
488 # define VARIABLE_LIBPATH 1
489 # else
490 # define VARIABLE_LIBPATH 0
491 # endif
492 # if VARIABLE_LIBPATH
493  char *libpath;
494  VALUE sopath;
495 # else
496  char libpath[MAXPATHLEN + 1];
497 # endif
498  size_t baselen;
499  char *p;
500 
501 #if defined _WIN32 || defined __CYGWIN__
502  {
503  DWORD len = RSTRING_EMBED_LEN_MAX, ret, i;
504  VALUE wsopath = rb_str_new(0, len*sizeof(WCHAR));
505  WCHAR *wlibpath;
506  while (wlibpath = (WCHAR *)RSTRING_PTR(wsopath),
507  ret = GetModuleFileNameW(libruby, wlibpath, len),
508  (ret == len))
509  {
510  rb_str_modify_expand(wsopath, len*sizeof(WCHAR));
511  rb_str_set_len(wsopath, (len += len)*sizeof(WCHAR));
512  }
513  if (!ret || ret > len) rb_fatal("failed to get module file name");
514  for (len = ret, i = 0; i < len; ++i) {
515  if (wlibpath[i] == L'\\') {
516  wlibpath[i] = L'/';
517  ret = i+1; /* chop after the last separator */
518  }
519  }
520  len = WideCharToMultiByte(CP_UTF8, 0, wlibpath, ret, NULL, 0, NULL, NULL);
521  sopath = rb_utf8_str_new(0, len);
522  libpath = RSTRING_PTR(sopath);
523  WideCharToMultiByte(CP_UTF8, 0, wlibpath, ret, libpath, len, NULL, NULL);
524  rb_str_resize(wsopath, 0);
525  }
526 #elif defined(HAVE_DLADDR)
527  sopath = dladdr_path((void *)(VALUE)expand_include_path);
528  libpath = RSTRING_PTR(sopath);
529 #endif
530 
531 #if !VARIABLE_LIBPATH
532  libpath[sizeof(libpath) - 1] = '\0';
533 #endif
534 #if defined DOSISH && !defined _WIN32
535  translit_char(libpath, '\\', '/');
536 #elif defined __CYGWIN__
537  {
538  const int win_to_posix = CCP_WIN_A_TO_POSIX | CCP_RELATIVE;
539  size_t newsize = cygwin_conv_path(win_to_posix, libpath, 0, 0);
540  if (newsize > 0) {
541  VALUE rubylib = rb_str_new(0, newsize);
542  p = RSTRING_PTR(rubylib);
543  if (cygwin_conv_path(win_to_posix, libpath, p, newsize) == 0) {
544  rb_str_resize(sopath, 0);
545  sopath = rubylib;
546  libpath = p;
547  }
548  }
549  }
550 #endif
551  p = strrchr(libpath, '/');
552  if (p) {
553  static const char bindir[] = "/bin";
554 #ifdef LIBDIR_BASENAME
555  static const char libdir[] = "/"LIBDIR_BASENAME;
556 #else
557  static const char libdir[] = "/lib";
558 #endif
559  const ptrdiff_t bindir_len = (ptrdiff_t)sizeof(bindir) - 1;
560  const ptrdiff_t libdir_len = (ptrdiff_t)sizeof(libdir) - 1;
561 
562 #ifdef ENABLE_MULTIARCH
563  char *p2 = NULL;
564 
565  multiarch:
566 #endif
567  if (p - libpath >= bindir_len && !STRNCASECMP(p - bindir_len, bindir, bindir_len)) {
568  p -= bindir_len;
569  }
570  else if (p - libpath >= libdir_len && !strncmp(p - libdir_len, libdir, libdir_len)) {
571  p -= libdir_len;
572  }
573 #ifdef ENABLE_MULTIARCH
574  else if (p2) {
575  p = p2;
576  }
577  else {
578  p2 = p;
580  if (p) goto multiarch;
581  p = p2;
582  }
583 #endif
584 #if !VARIABLE_LIBPATH
585  *p = 0;
586 #endif
587  }
588 #if !VARIABLE_LIBPATH
589  else {
590  strlcpy(libpath, ".", sizeof(libpath));
591  p = libpath + 1;
592  }
593  baselen = p - libpath;
594 #define PREFIX_PATH() rb_str_new(libpath, baselen)
595 #else
596  baselen = p - libpath;
597  rb_str_resize(sopath, baselen);
598  libpath = RSTRING_PTR(sopath);
599 #define PREFIX_PATH() sopath
600 #endif
601 
602 #define BASEPATH() rb_str_buf_cat(rb_str_buf_new(baselen+len), libpath, baselen)
603 
604 #define RUBY_RELATIVE(path, len) rb_str_buf_cat(BASEPATH(), (path), (len))
605 #else
606  const size_t exec_prefix_len = strlen(ruby_exec_prefix);
607 #define RUBY_RELATIVE(path, len) rubylib_path_new((path), (len))
608 #define PREFIX_PATH() RUBY_RELATIVE(ruby_exec_prefix, exec_prefix_len)
609 #endif
610  load_path = GET_VM()->load_path;
611 
612  if (safe_level == 0) {
613  ruby_push_include(getenv("RUBYLIB"), identical_path);
614  }
615 
616  id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK;
617  while (*paths) {
618  size_t len = strlen(paths);
619  VALUE path = RUBY_RELATIVE(paths, len);
620  rb_ivar_set(path, id_initial_load_path_mark, path);
621  rb_ary_push(load_path, path);
622  paths += len + 1;
623  }
624 
626 }
627 
628 
629 static void
630 add_modules(VALUE *req_list, const char *mod)
631 {
632  VALUE list = *req_list;
633  VALUE feature;
634 
635  if (!list) {
636  *req_list = list = rb_ary_new();
637  RBASIC_CLEAR_CLASS(list);
638  }
639  feature = rb_str_new2(mod);
640  RBASIC_CLEAR_CLASS(feature);
641  rb_ary_push(list, feature);
642 }
643 
644 static void
645 require_libraries(VALUE *req_list)
646 {
647  VALUE list = *req_list;
648  VALUE self = rb_vm_top_self();
649  ID require;
651 
652  CONST_ID(require, "require");
653  while (list && RARRAY_LEN(list) > 0) {
654  VALUE feature = rb_ary_shift(list);
655  rb_enc_associate(feature, extenc);
657  OBJ_FREEZE(feature);
658  rb_funcallv(self, require, 1, &feature);
659  }
660  *req_list = 0;
661 }
662 
663 static const struct rb_block*
664 toplevel_context(rb_binding_t *bind)
665 {
666  return &bind->block;
667 }
668 
669 static void
670 process_sflag(int *sflag)
671 {
672  if (*sflag > 0) {
673  long n;
674  const VALUE *args;
675  VALUE argv = rb_argv;
676 
677  n = RARRAY_LEN(argv);
678  args = RARRAY_CONST_PTR(argv);
679  while (n > 0) {
680  VALUE v = *args++;
681  char *s = StringValuePtr(v);
682  char *p;
683  int hyphen = FALSE;
684 
685  if (s[0] != '-')
686  break;
687  n--;
688  if (s[1] == '-' && s[2] == '\0')
689  break;
690 
691  v = Qtrue;
692  /* check if valid name before replacing - with _ */
693  for (p = s + 1; *p; p++) {
694  if (*p == '=') {
695  *p++ = '\0';
696  v = rb_str_new2(p);
697  break;
698  }
699  if (*p == '-') {
700  hyphen = TRUE;
701  }
702  else if (*p != '_' && !ISALNUM(*p)) {
703  VALUE name_error[2];
704  name_error[0] =
705  rb_str_new2("invalid name for global variable - ");
706  if (!(p = strchr(p, '='))) {
707  rb_str_cat2(name_error[0], s);
708  }
709  else {
710  rb_str_cat(name_error[0], s, p - s);
711  }
712  name_error[1] = args[-1];
714  }
715  }
716  s[0] = '$';
717  if (hyphen) {
718  for (p = s + 1; *p; ++p) {
719  if (*p == '-')
720  *p = '_';
721  }
722  }
723  rb_gv_set(s, v);
724  }
725  n = RARRAY_LEN(argv) - n;
726  while (n--) {
727  rb_ary_shift(argv);
728  }
729  *sflag = -1;
730  }
731 }
732 
733 static long proc_options(long argc, char **argv, ruby_cmdline_options_t *opt, int envopt);
734 
735 static void
736 moreswitches(const char *s, ruby_cmdline_options_t *opt, int envopt)
737 {
738  long argc, i, len;
739  char **argv, *p;
740  const char *ap = 0;
741  VALUE argstr, argary;
742 
743  while (ISSPACE(*s)) s++;
744  if (!*s) return;
745  argstr = rb_str_tmp_new((len = strlen(s)) + (envopt!=0));
746  argary = rb_str_tmp_new(0);
747 
748  p = RSTRING_PTR(argstr);
749  if (envopt) *p++ = ' ';
750  memcpy(p, s, len + 1);
751  ap = 0;
752  rb_str_cat(argary, (char *)&ap, sizeof(ap));
753  while (*p) {
754  ap = p;
755  rb_str_cat(argary, (char *)&ap, sizeof(ap));
756  while (*p && !ISSPACE(*p)) ++p;
757  if (!*p) break;
758  *p++ = '\0';
759  while (ISSPACE(*p)) ++p;
760  }
761  argc = RSTRING_LEN(argary) / sizeof(ap);
762  ap = 0;
763  rb_str_cat(argary, (char *)&ap, sizeof(ap));
764  argv = (char **)RSTRING_PTR(argary);
765 
766  while ((i = proc_options(argc, argv, opt, envopt)) > 1 && envopt && (argc -= i) > 0) {
767  argv += i;
768  if (**argv != '-') {
769  *--*argv = '-';
770  }
771  if ((*argv)[1]) {
772  ++argc;
773  --argv;
774  }
775  }
776 
777  /* get rid of GC */
778  rb_str_resize(argary, 0);
779  rb_str_resize(argstr, 0);
780 }
781 
782 static int
783 name_match_p(const char *name, const char *str, size_t len)
784 {
785  if (len == 0) return 0;
786  do {
787  while (TOLOWER(*str) == *name) {
788  if (!--len || !*++str) return 1;
789  ++name;
790  }
791  if (*str != '-' && *str != '_') return 0;
792  while (ISALNUM(*name)) name++;
793  if (*name != '-' && *name != '_') return 0;
794  ++name;
795  ++str;
796  } while (len > 0);
797  return !*name;
798 }
799 
800 #define NAME_MATCH_P(name, str, len) \
801  ((len) < (int)sizeof(name) && name_match_p((name), (str), (len)))
802 
803 #define UNSET_WHEN(name, bit, str, len) \
804  if (NAME_MATCH_P((name), (str), (len))) { \
805  *(unsigned int *)arg &= ~(bit); \
806  return; \
807  }
808 
809 #define SET_WHEN(name, bit, str, len) \
810  if (NAME_MATCH_P((name), (str), (len))) { \
811  *(unsigned int *)arg |= (bit); \
812  return; \
813  }
814 
815 #define LITERAL_NAME_ELEMENT(name) #name
816 
817 static void
818 feature_option(const char *str, int len, void *arg, const unsigned int enable)
819 {
820  static const char list[] = EACH_FEATURES(LITERAL_NAME_ELEMENT, ", ");
821  unsigned int *argp = arg;
822  unsigned int mask = ~0U;
823 #if AMBIGUOUS_FEATURE_NAMES
824  unsigned int set = 0U;
825  int matched = 0;
826 #define SET_FEATURE(bit) \
827  if (NAME_MATCH_P(#bit, str, len)) {set |= mask = FEATURE_BIT(bit); ++matched;}
828 #else
829 #define SET_FEATURE(bit) \
830  if (NAME_MATCH_P(#bit, str, len)) {mask = FEATURE_BIT(bit); goto found;}
831 #endif
833  if (NAME_MATCH_P("all", str, len)) {
834  found:
835  *argp = (*argp & ~mask) | (mask & enable);
836  return;
837  }
838 #if AMBIGUOUS_FEATURE_NAMES
839  if (matched == 1) goto found;
840  if (matched > 1) {
841  VALUE mesg = rb_sprintf("ambiguous feature: `%.*s' (", len, str);
842 #define ADD_FEATURE_NAME(bit) \
843  if (FEATURE_BIT(bit) & set) { \
844  rb_str_cat_cstr(mesg, #bit); \
845  if (--matched) rb_str_cat_cstr(mesg, ", "); \
846  }
847  EACH_FEATURES(ADD_FEATURE_NAME, ;);
848  rb_str_cat_cstr(mesg, ")");
850 #undef ADD_FEATURE_NAME
851  }
852 #endif
853  rb_warn("unknown argument for --%s: `%.*s'",
854  enable ? "enable" : "disable", len, str);
855  rb_warn("features are [%.*s].", (int)strlen(list), list);
856 }
857 
858 static void
859 enable_option(const char *str, int len, void *arg)
860 {
861  feature_option(str, len, arg, ~0U);
862 }
863 
864 static void
865 disable_option(const char *str, int len, void *arg)
866 {
867  feature_option(str, len, arg, 0U);
868 }
869 
871 int ruby_env_debug_option(const char *str, int len, void *arg);
872 
873 static void
874 debug_option(const char *str, int len, void *arg)
875 {
876  static const char list[] = EACH_DEBUG_FEATURES(LITERAL_NAME_ELEMENT, ", ");
877 #define SET_WHEN_DEBUG(bit) SET_WHEN(#bit, DEBUG_BIT(bit), str, len)
879 #ifdef RUBY_DEVEL
880  if (ruby_patchlevel < 0 && ruby_env_debug_option(str, len, 0)) return;
881 #endif
882  rb_warn("unknown argument for --debug: `%.*s'", len, str);
883  rb_warn("debug features are [%.*s].", (int)strlen(list), list);
884 }
885 
886 static void
887 dump_option(const char *str, int len, void *arg)
888 {
889  static const char list[] = EACH_DUMPS(LITERAL_NAME_ELEMENT, ", ");
890 #define SET_WHEN_DUMP(bit) SET_WHEN(#bit, DUMP_BIT(bit), str, len)
892  rb_warn("don't know how to dump `%.*s',", len, str);
893  rb_warn("but only [%.*s].", (int)strlen(list), list);
894 }
895 
896 static void
897 set_option_encoding_once(const char *type, VALUE *name, const char *e, long elen)
898 {
899  VALUE ename;
900 
901  if (!elen) elen = strlen(e);
902  ename = rb_str_new(e, elen);
903 
904  if (*name &&
905  rb_funcall(ename, rb_intern("casecmp"), 1, *name) != INT2FIX(0)) {
907  "%s already set to %"PRIsVALUE, type, *name);
908  }
909  *name = ename;
910 }
911 
912 #define set_internal_encoding_once(opt, e, elen) \
913  set_option_encoding_once("default_internal", &(opt)->intern.enc.name, (e), (elen))
914 #define set_external_encoding_once(opt, e, elen) \
915  set_option_encoding_once("default_external", &(opt)->ext.enc.name, (e), (elen))
916 #define set_source_encoding_once(opt, e, elen) \
917  set_option_encoding_once("source", &(opt)->src.enc.name, (e), (elen))
918 
919 static long
920 proc_options(long argc, char **argv, ruby_cmdline_options_t *opt, int envopt)
921 {
922  long n, argc0 = argc;
923  const char *s;
924  int warning = opt->warning;
925 
926  if (argc <= 0 || !argv)
927  return 0;
928 
929  for (argc--, argv++; argc > 0; argc--, argv++) {
930  const char *const arg = argv[0];
931  if (!arg || arg[0] != '-' || !arg[1])
932  break;
933 
934  s = arg + 1;
935  reswitch:
936  switch (*s) {
937  case 'a':
938  if (envopt) goto noenvopt;
939  opt->do_split = TRUE;
940  s++;
941  goto reswitch;
942 
943  case 'p':
944  if (envopt) goto noenvopt;
945  opt->do_print = TRUE;
946  /* through */
947  case 'n':
948  if (envopt) goto noenvopt;
949  opt->do_loop = TRUE;
950  s++;
951  goto reswitch;
952 
953  case 'd':
954  ruby_debug = Qtrue;
956  s++;
957  goto reswitch;
958 
959  case 'y':
960  if (envopt) goto noenvopt;
961  opt->dump |= DUMP_BIT(yydebug);
962  s++;
963  goto reswitch;
964 
965  case 'v':
966  if (opt->verbose) {
967  s++;
968  goto reswitch;
969  }
970  opt->dump |= DUMP_BIT(version_v);
971  opt->verbose = 1;
972  case 'w':
973  if (!opt->warning) {
974  warning = 1;
976  }
977  s++;
978  goto reswitch;
979 
980  case 'W':
981  {
982  size_t numlen;
983  int v = 2; /* -W as -W2 */
984 
985  if (*++s) {
986  v = scan_oct(s, 1, &numlen);
987  if (numlen == 0)
988  v = 1;
989  s += numlen;
990  }
991  if (!opt->warning) {
992  switch (v) {
993  case 0:
994  ruby_verbose = Qnil;
995  break;
996  case 1:
998  break;
999  default:
1000  ruby_verbose = Qtrue;
1001  break;
1002  }
1003  }
1004  warning = 1;
1005  }
1006  goto reswitch;
1007 
1008  case 'c':
1009  if (envopt) goto noenvopt;
1010  opt->dump |= DUMP_BIT(syntax);
1011  s++;
1012  goto reswitch;
1013 
1014  case 's':
1015  if (envopt) goto noenvopt;
1016  forbid_setid("-s");
1017  if (!opt->sflag) opt->sflag = 1;
1018  s++;
1019  goto reswitch;
1020 
1021  case 'h':
1022  if (envopt) goto noenvopt;
1023  opt->dump |= DUMP_BIT(usage);
1024  goto switch_end;
1025 
1026  case 'l':
1027  if (envopt) goto noenvopt;
1028  opt->do_line = TRUE;
1029  rb_output_rs = rb_rs;
1030  s++;
1031  goto reswitch;
1032 
1033  case 'S':
1034  if (envopt) goto noenvopt;
1035  forbid_setid("-S");
1036  opt->do_search = TRUE;
1037  s++;
1038  goto reswitch;
1039 
1040  case 'e':
1041  if (envopt) goto noenvopt;
1042  forbid_setid("-e");
1043  if (!*++s) {
1044  if (!--argc)
1045  rb_raise(rb_eRuntimeError, "no code specified for -e");
1046  s = *++argv;
1047  }
1048  if (!opt->e_script) {
1049  opt->e_script = rb_str_new(0, 0);
1050  if (opt->script == 0)
1051  opt->script = "-e";
1052  }
1053  rb_str_cat2(opt->e_script, s);
1054  rb_str_cat2(opt->e_script, "\n");
1055  break;
1056 
1057  case 'r':
1058  forbid_setid("-r");
1059  if (*++s) {
1060  add_modules(&opt->req_list, s);
1061  }
1062  else if (argc > 1) {
1063  add_modules(&opt->req_list, argv[1]);
1064  argc--, argv++;
1065  }
1066  break;
1067 
1068  case 'i':
1069  if (envopt) goto noenvopt;
1070  forbid_setid("-i");
1071  ruby_set_inplace_mode(s + 1);
1072  break;
1073 
1074  case 'x':
1075  if (envopt) goto noenvopt;
1076  forbid_setid("-x");
1077  opt->xflag = TRUE;
1078  s++;
1079  if (*s && chdir(s) < 0) {
1080  rb_fatal("Can't chdir to %s", s);
1081  }
1082  break;
1083 
1084  case 'C':
1085  case 'X':
1086  if (envopt) goto noenvopt;
1087  if (!*++s && (!--argc || !(s = *++argv) || !*s)) {
1088  rb_fatal("Can't chdir");
1089  }
1090  if (chdir(s) < 0) {
1091  rb_fatal("Can't chdir to %s", s);
1092  }
1093  break;
1094 
1095  case 'F':
1096  if (envopt) goto noenvopt;
1097  if (*++s) {
1098  rb_fs = rb_reg_new(s, strlen(s), 0);
1099  }
1100  break;
1101 
1102  case 'E':
1103  if (!*++s && (!--argc || !(s = *++argv))) {
1104  rb_raise(rb_eRuntimeError, "missing argument for -E");
1105  }
1106  goto encoding;
1107 
1108  case 'U':
1109  set_internal_encoding_once(opt, "UTF-8", 0);
1110  ++s;
1111  goto reswitch;
1112 
1113  case 'K':
1114  if (*++s) {
1115  const char *enc_name = 0;
1116  switch (*s) {
1117  case 'E': case 'e':
1118  enc_name = "EUC-JP";
1119  break;
1120  case 'S': case 's':
1121  enc_name = "Windows-31J";
1122  break;
1123  case 'U': case 'u':
1124  enc_name = "UTF-8";
1125  break;
1126  case 'N': case 'n': case 'A': case 'a':
1127  enc_name = "ASCII-8BIT";
1128  break;
1129  }
1130  if (enc_name) {
1131  opt->src.enc.name = rb_str_new2(enc_name);
1132  if (!opt->ext.enc.name)
1133  opt->ext.enc.name = opt->src.enc.name;
1134  }
1135  s++;
1136  }
1137  goto reswitch;
1138 
1139  case 'T':
1140  {
1141  size_t numlen;
1142  int v = 1;
1143 
1144  if (*++s) {
1145  v = scan_oct(s, 2, &numlen);
1146  if (numlen == 0)
1147  v = 1;
1148  s += numlen;
1149  }
1150  if (v > opt->safe_level) opt->safe_level = v;
1151  }
1152  goto reswitch;
1153 
1154  case 'I':
1155  forbid_setid("-I");
1156  if (*++s)
1158  else if (argc > 1) {
1159  ruby_incpush_expand(argv[1]);
1160  argc--, argv++;
1161  }
1162  break;
1163 
1164  case '0':
1165  if (envopt) goto noenvopt;
1166  {
1167  size_t numlen;
1168  int v;
1169  char c;
1170 
1171  v = scan_oct(s, 4, &numlen);
1172  s += numlen;
1173  if (v > 0377)
1174  rb_rs = Qnil;
1175  else if (v == 0 && numlen >= 2) {
1176  rb_rs = rb_str_new2("");
1177  }
1178  else {
1179  c = v & 0xff;
1180  rb_rs = rb_str_new(&c, 1);
1181  }
1182  }
1183  goto reswitch;
1184 
1185  case '-':
1186  if (!s[1] || (s[1] == '\r' && !s[2])) {
1187  argc--, argv++;
1188  goto switch_end;
1189  }
1190  s++;
1191 
1192 # define is_option_end(c, allow_hyphen) \
1193  (!(c) || ((allow_hyphen) && (c) == '-') || (c) == '=')
1194 # define check_envopt(name, allow_envopt) \
1195  (((allow_envopt) || !envopt) ? (void)0 : \
1196  rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --" name))
1197 # define need_argument(name, s, needs_arg, next_arg) \
1198  ((*(s) ? !*++(s) : (next_arg) && (!argc || !((s) = argv[1]) || (--argc, ++argv, 0))) && (needs_arg) ? \
1199  rb_raise(rb_eRuntimeError, "missing argument for --" name) \
1200  : (void)0)
1201 # define is_option_with_arg(name, allow_hyphen, allow_envopt) \
1202  is_option_with_optarg(name, allow_hyphen, allow_envopt, Qtrue, Qtrue)
1203 # define is_option_with_optarg(name, allow_hyphen, allow_envopt, needs_arg, next_arg) \
1204  (strncmp((name), s, n = sizeof(name) - 1) == 0 && is_option_end(s[n], (allow_hyphen)) ? \
1205  (check_envopt(name, (allow_envopt)), s += n, \
1206  need_argument(name, s, needs_arg, next_arg), 1) : 0)
1207 
1208  if (strcmp("copyright", s) == 0) {
1209  if (envopt) goto noenvopt_long;
1210  opt->dump |= DUMP_BIT(copyright);
1211  }
1212  else if (is_option_with_optarg("debug", Qtrue, Qtrue, Qfalse, Qfalse)) {
1213  if (s && *s) {
1214  ruby_each_words(s, debug_option, &opt->features);
1215  }
1216  else {
1217  ruby_debug = Qtrue;
1218  ruby_verbose = Qtrue;
1219  }
1220  }
1221  else if (is_option_with_arg("enable", Qtrue, Qtrue)) {
1222  ruby_each_words(s, enable_option, &opt->features);
1223  }
1224  else if (is_option_with_arg("disable", Qtrue, Qtrue)) {
1225  ruby_each_words(s, disable_option, &opt->features);
1226  }
1227  else if (is_option_with_arg("encoding", Qfalse, Qtrue)) {
1228  char *p;
1229  encoding:
1230  do {
1231 # define set_encoding_part(type) \
1232  if (!(p = strchr(s, ':'))) { \
1233  set_##type##_encoding_once(opt, s, 0); \
1234  break; \
1235  } \
1236  else if (p > s) { \
1237  set_##type##_encoding_once(opt, s, p-s); \
1238  }
1239  set_encoding_part(external);
1240  if (!*(s = ++p)) break;
1241  set_encoding_part(internal);
1242  if (!*(s = ++p)) break;
1243 #if defined ALLOW_DEFAULT_SOURCE_ENCODING && ALLOW_DEFAULT_SOURCE_ENCODING
1244  set_encoding_part(source);
1245  if (!*(s = ++p)) break;
1246 #endif
1247  rb_raise(rb_eRuntimeError, "extra argument for %s: %s",
1248  (arg[1] == '-' ? "--encoding" : "-E"), s);
1249 # undef set_encoding_part
1250  } while (0);
1251  }
1252  else if (is_option_with_arg("internal-encoding", Qfalse, Qtrue)) {
1253  set_internal_encoding_once(opt, s, 0);
1254  }
1255  else if (is_option_with_arg("external-encoding", Qfalse, Qtrue)) {
1256  set_external_encoding_once(opt, s, 0);
1257  }
1258 #if defined ALLOW_DEFAULT_SOURCE_ENCODING && ALLOW_DEFAULT_SOURCE_ENCODING
1259  else if (is_option_with_arg("source-encoding", Qfalse, Qtrue)) {
1260  set_source_encoding_once(opt, s, 0);
1261  }
1262 #endif
1263  else if (strcmp("version", s) == 0) {
1264  if (envopt) goto noenvopt_long;
1265  opt->dump |= DUMP_BIT(version);
1266  }
1267  else if (strcmp("verbose", s) == 0) {
1268  opt->verbose = 1;
1269  ruby_verbose = Qtrue;
1270  }
1271  else if (strcmp("yydebug", s) == 0) {
1272  if (envopt) goto noenvopt_long;
1273  opt->dump |= DUMP_BIT(yydebug);
1274  }
1275  else if (is_option_with_arg("dump", Qfalse, Qfalse)) {
1276  ruby_each_words(s, dump_option, &opt->dump);
1277  }
1278  else if (strcmp("help", s) == 0) {
1279  if (envopt) goto noenvopt_long;
1280  opt->dump |= DUMP_BIT(help);
1281  goto switch_end;
1282  }
1283  else {
1285  "invalid option --%s (-h will show valid options)", s);
1286  }
1287  break;
1288 
1289  case '\r':
1290  if (!s[1])
1291  break;
1292 
1293  default:
1294  {
1295  if (ISPRINT(*s)) {
1297  "invalid option -%c (-h will show valid options)",
1298  (int)(unsigned char)*s);
1299  }
1300  else {
1302  "invalid option -\\x%02X (-h will show valid options)",
1303  (int)(unsigned char)*s);
1304  }
1305  }
1306  goto switch_end;
1307 
1308  noenvopt:
1309  /* "EIdvwWrKU" only */
1310  rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: -%c", *s);
1311  break;
1312 
1313  noenvopt_long:
1314  rb_raise(rb_eRuntimeError, "invalid switch in RUBYOPT: --%s", s);
1315  break;
1316 
1317  case 0:
1318  break;
1319 # undef is_option_end
1320 # undef check_envopt
1321 # undef need_argument
1322 # undef is_option_with_arg
1323 # undef is_option_with_optarg
1324  }
1325  }
1326 
1327  switch_end:
1328  if (warning) opt->warning = warning;
1329  return argc0 - argc;
1330 }
1331 
1332 static void
1333 ruby_init_prelude(void)
1334 {
1335  Init_prelude();
1336  rb_const_remove(rb_cObject, rb_intern_const("TMP_RUBY_PREFIX"));
1337 }
1338 
1339 static int
1340 opt_enc_index(VALUE enc_name)
1341 {
1342  const char *s = RSTRING_PTR(enc_name);
1343  int i = rb_enc_find_index(s);
1344 
1345  if (i < 0) {
1346  rb_raise(rb_eRuntimeError, "unknown encoding name - %s", s);
1347  }
1348  else if (rb_enc_dummy_p(rb_enc_from_index(i))) {
1349  rb_raise(rb_eRuntimeError, "dummy encoding is not acceptable - %s ", s);
1350  }
1351  return i;
1352 }
1353 
1354 #define rb_progname (GET_VM()->progname)
1355 #define rb_orig_progname (GET_VM()->orig_progname)
1357 
1358 static VALUE
1359 false_value(void)
1360 {
1361  return Qfalse;
1362 }
1363 
1364 static VALUE
1365 true_value(void)
1366 {
1367  return Qtrue;
1368 }
1369 
1370 #define rb_define_readonly_boolean(name, val) \
1371  rb_define_virtual_variable((name), (val) ? true_value : false_value, 0)
1372 
1373 static VALUE
1374 uscore_get(void)
1375 {
1376  VALUE line;
1377 
1378  line = rb_lastline_get();
1379  if (!RB_TYPE_P(line, T_STRING)) {
1380  rb_raise(rb_eTypeError, "$_ value need to be String (%s given)",
1381  NIL_P(line) ? "nil" : rb_obj_classname(line));
1382  }
1383  return line;
1384 }
1385 
1386 /*
1387  * call-seq:
1388  * sub(pattern, replacement) -> $_
1389  * sub(pattern) {|...| block } -> $_
1390  *
1391  * Equivalent to <code>$_.sub(<i>args</i>)</code>, except that
1392  * <code>$_</code> will be updated if substitution occurs.
1393  * Available only when -p/-n command line option specified.
1394  */
1395 
1396 static VALUE
1397 rb_f_sub(int argc, VALUE *argv)
1398 {
1399  VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("sub"), argc, argv);
1400  rb_lastline_set(str);
1401  return str;
1402 }
1403 
1404 /*
1405  * call-seq:
1406  * gsub(pattern, replacement) -> $_
1407  * gsub(pattern) {|...| block } -> $_
1408  *
1409  * Equivalent to <code>$_.gsub...</code>, except that <code>$_</code>
1410  * will be updated if substitution occurs.
1411  * Available only when -p/-n command line option specified.
1412  *
1413  */
1414 
1415 static VALUE
1416 rb_f_gsub(int argc, VALUE *argv)
1417 {
1418  VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("gsub"), argc, argv);
1419  rb_lastline_set(str);
1420  return str;
1421 }
1422 
1423 /*
1424  * call-seq:
1425  * chop -> $_
1426  *
1427  * Equivalent to <code>($_.dup).chop!</code>, except <code>nil</code>
1428  * is never returned. See <code>String#chop!</code>.
1429  * Available only when -p/-n command line option specified.
1430  *
1431  */
1432 
1433 static VALUE
1434 rb_f_chop(void)
1435 {
1436  VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("chop"), 0, 0);
1437  rb_lastline_set(str);
1438  return str;
1439 }
1440 
1441 
1442 /*
1443  * call-seq:
1444  * chomp -> $_
1445  * chomp(string) -> $_
1446  *
1447  * Equivalent to <code>$_ = $_.chomp(<em>string</em>)</code>. See
1448  * <code>String#chomp</code>.
1449  * Available only when -p/-n command line option specified.
1450  *
1451  */
1452 
1453 static VALUE
1454 rb_f_chomp(int argc, VALUE *argv)
1455 {
1456  VALUE str = rb_funcall_passing_block(uscore_get(), rb_intern("chomp"), argc, argv);
1457  rb_lastline_set(str);
1458  return str;
1459 }
1460 
1461 static VALUE
1462 process_options(int argc, char **argv, ruby_cmdline_options_t *opt)
1463 {
1464  NODE *tree = 0;
1465  VALUE parser;
1467  const rb_iseq_t *iseq;
1468  rb_encoding *enc, *lenc;
1469 #if UTF8_PATH
1470  rb_encoding *uenc, *ienc = 0;
1471 #endif
1472  const char *s;
1473  char fbuf[MAXPATHLEN];
1474  int i = (int)proc_options(argc, argv, opt, 0);
1475  rb_binding_t *toplevel_binding;
1476  const struct rb_block *base_block;
1477  unsigned int dump = opt->dump & dump_exit_bits;
1478 
1479  if (opt->dump & (DUMP_BIT(usage)|DUMP_BIT(help))) {
1480  const char *const progname =
1481  (argc > 0 && argv && argv[0] ? argv[0] :
1482  origarg.argc > 0 && origarg.argv && origarg.argv[0] ? origarg.argv[0] :
1483  ruby_engine);
1484  usage(progname, (opt->dump & DUMP_BIT(help)));
1485  return Qtrue;
1486  }
1487 
1488  argc -= i;
1489  argv += i;
1490 
1491  if ((opt->features & FEATURE_BIT(rubyopt)) &&
1492  opt->safe_level == 0 && (s = getenv("RUBYOPT"))) {
1493  VALUE src_enc_name = opt->src.enc.name;
1494  VALUE ext_enc_name = opt->ext.enc.name;
1495  VALUE int_enc_name = opt->intern.enc.name;
1496 
1497  opt->src.enc.name = opt->ext.enc.name = opt->intern.enc.name = 0;
1498  moreswitches(s, opt, 1);
1499  if (src_enc_name)
1500  opt->src.enc.name = src_enc_name;
1501  if (ext_enc_name)
1502  opt->ext.enc.name = ext_enc_name;
1503  if (int_enc_name)
1504  opt->intern.enc.name = int_enc_name;
1505  }
1506 
1507  if (opt->src.enc.name)
1508  rb_warning("-K is specified; it is for 1.8 compatibility and may cause odd behavior");
1509 
1510  if (opt->dump & (DUMP_BIT(version) | DUMP_BIT(version_v))) {
1512  if (opt->dump & DUMP_BIT(version)) return Qtrue;
1513  }
1514  if (opt->dump & DUMP_BIT(copyright)) {
1516  return Qtrue;
1517  }
1518 
1519  if (!opt->e_script) {
1520  if (argc <= 0) { /* no more args */
1521  if (opt->verbose)
1522  return Qtrue;
1523  opt->script = "-";
1524  }
1525  else {
1526  opt->script = argv[0];
1527  if (!opt->script || opt->script[0] == '\0') {
1528  opt->script = "-";
1529  }
1530  else if (opt->do_search) {
1531  char *path = getenv("RUBYPATH");
1532 
1533  opt->script = 0;
1534  if (path) {
1535  opt->script = dln_find_file_r(argv[0], path, fbuf, sizeof(fbuf));
1536  }
1537  if (!opt->script) {
1538  opt->script = dln_find_file_r(argv[0], getenv(PATH_ENV), fbuf, sizeof(fbuf));
1539  }
1540  if (!opt->script)
1541  opt->script = argv[0];
1542  }
1543  argc--;
1544  argv++;
1545  }
1546  if (opt->script[0] == '-' && !opt->script[1]) {
1547  forbid_setid("program input from stdin");
1548  }
1549  }
1550 
1551  opt->script_name = rb_str_new_cstr(opt->script);
1552  opt->script = RSTRING_PTR(opt->script_name);
1553 
1554 #if _WIN32
1555  translit_char_bin(RSTRING_PTR(opt->script_name), '\\', '/');
1556 #elif defined DOSISH
1557  translit_char(RSTRING_PTR(opt->script_name), '\\', '/');
1558 #endif
1559 
1562  Init_enc();
1563  lenc = rb_locale_encoding();
1566  parser = rb_parser_new();
1567  if (opt->dump & DUMP_BIT(yydebug)) {
1568  rb_parser_set_yydebug(parser, Qtrue);
1569  }
1570  if (opt->ext.enc.name != 0) {
1571  opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
1572  }
1573  if (opt->intern.enc.name != 0) {
1574  opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
1575  }
1576  if (opt->src.enc.name != 0) {
1577  opt->src.enc.index = opt_enc_index(opt->src.enc.name);
1578  src_encoding_index = opt->src.enc.index;
1579  }
1580  if (opt->ext.enc.index >= 0) {
1581  enc = rb_enc_from_index(opt->ext.enc.index);
1582  }
1583  else {
1584  enc = lenc;
1585  }
1587  if (opt->intern.enc.index >= 0) {
1588  enc = rb_enc_from_index(opt->intern.enc.index);
1590  opt->intern.enc.index = -1;
1591 #if UTF8_PATH
1592  ienc = enc;
1593 #endif
1594  }
1595  script_name = opt->script_name;
1597  IF_UTF8_PATH(uenc = rb_utf8_encoding(), lenc));
1598 #if UTF8_PATH
1599  if (uenc != lenc) {
1600  opt->script_name = str_conv_enc(opt->script_name, uenc, lenc);
1601  opt->script = RSTRING_PTR(opt->script_name);
1602  }
1603 #endif
1604  rb_obj_freeze(opt->script_name);
1605  if (IF_UTF8_PATH(uenc != lenc, 1)) {
1606  long i;
1607  VALUE load_path = GET_VM()->load_path;
1608  const ID id_initial_load_path_mark = INITIAL_LOAD_PATH_MARK;
1609  for (i = 0; i < RARRAY_LEN(load_path); ++i) {
1610  VALUE path = RARRAY_AREF(load_path, i);
1611  int mark = rb_attr_get(path, id_initial_load_path_mark) == path;
1612 #if UTF8_PATH
1613  VALUE newpath = rb_str_conv_enc(path, uenc, lenc);
1614  if (newpath == path) continue;
1615  path = newpath;
1616 #else
1617  path = rb_enc_associate(rb_str_dup(path), lenc);
1618 #endif
1619  if (mark) rb_ivar_set(path, id_initial_load_path_mark, path);
1620  RARRAY_ASET(load_path, i, path);
1621  }
1622  }
1623  Init_ext(); /* load statically linked extensions before rubygems */
1624  if (opt->features & FEATURE_BIT(gems)) {
1625  rb_define_module("Gem");
1626  }
1627  if (opt->features & FEATURE_BIT(did_you_mean)) {
1628  rb_define_module("DidYouMean");
1629  }
1630  ruby_init_prelude();
1632  VALUE option = rb_hash_new();
1633 #define SET_COMPILE_OPTION(h, o, name) \
1634  rb_hash_aset((h), ID2SYM(rb_intern_const(#name)), \
1635  ((o)->features & FEATURE_BIT(name) ? Qtrue : Qfalse));
1636  SET_COMPILE_OPTION(option, opt, frozen_string_literal);
1637  SET_COMPILE_OPTION(option, opt, debug_frozen_string_literal);
1638  rb_funcallv(rb_cISeq, rb_intern_const("compile_option="), 1, &option);
1639 #undef SET_COMPILE_OPTION
1640  }
1641  ruby_set_argv(argc, argv);
1642  process_sflag(&opt->sflag);
1643 
1644  GetBindingPtr(rb_const_get(rb_cObject, rb_intern("TOPLEVEL_BINDING")),
1645  toplevel_binding);
1646  /* need to acquire env from toplevel_binding each time, since it
1647  * may update after eval() */
1648 
1649  if (opt->e_script) {
1650  VALUE progname = rb_progname;
1651  rb_encoding *eenc;
1652  if (opt->src.enc.index >= 0) {
1653  eenc = rb_enc_from_index(opt->src.enc.index);
1654  }
1655  else {
1656  eenc = lenc;
1657 #if UTF8_PATH
1658  if (ienc) eenc = ienc;
1659 #endif
1660  }
1661 #if UTF8_PATH
1662  if (eenc != uenc) {
1663  opt->e_script = str_conv_enc(opt->e_script, uenc, eenc);
1664  }
1665 #endif
1666  rb_enc_associate(opt->e_script, eenc);
1667  if (!(opt->dump & ~DUMP_BIT(version_v))) {
1669  require_libraries(&opt->req_list);
1670  }
1671  ruby_set_script_name(progname);
1672 
1673  base_block = toplevel_context(toplevel_binding);
1674  rb_parser_set_context(parser, base_block, TRUE);
1675  tree = rb_parser_compile_string(parser, opt->script, opt->e_script, 1);
1676  }
1677  else {
1678  VALUE f;
1679  base_block = toplevel_context(toplevel_binding);
1680  rb_parser_set_context(parser, base_block, TRUE);
1681  f = open_load_file(script_name, &opt->xflag);
1682  tree = load_file(parser, opt->script_name, f, 1, opt);
1683  }
1685  if (dump & DUMP_BIT(yydebug)) {
1686  dump &= ~DUMP_BIT(yydebug);
1687  if (!dump) return Qtrue;
1688  }
1689 
1690  if (opt->ext.enc.index >= 0) {
1691  enc = rb_enc_from_index(opt->ext.enc.index);
1692  }
1693  else {
1694  enc = lenc;
1695  }
1697  if (opt->intern.enc.index >= 0) {
1698  /* Set in the shebang line */
1699  enc = rb_enc_from_index(opt->intern.enc.index);
1701  }
1702  else if (!rb_default_internal_encoding())
1703  /* Freeze default_internal */
1706 
1707  if (!tree) return Qfalse;
1708 
1709  process_sflag(&opt->sflag);
1710  opt->xflag = 0;
1711 
1712  if (dump & DUMP_BIT(syntax)) {
1713  printf("Syntax OK\n");
1714  dump &= ~DUMP_BIT(syntax);
1715  if (!dump) return Qtrue;
1716  }
1717 
1718  if (opt->do_print) {
1719  tree = rb_parser_append_print(parser, tree);
1720  }
1721  if (opt->do_loop) {
1722  tree = rb_parser_while_loop(parser, tree, opt->do_line, opt->do_split);
1723  rb_define_global_function("sub", rb_f_sub, -1);
1724  rb_define_global_function("gsub", rb_f_gsub, -1);
1725  rb_define_global_function("chop", rb_f_chop, 0);
1726  rb_define_global_function("chomp", rb_f_chomp, -1);
1727  }
1728 
1729  if (dump & (DUMP_BIT(parsetree)|DUMP_BIT(parsetree_with_comment))) {
1730  rb_io_write(rb_stdout, rb_parser_dump_tree(tree, dump & DUMP_BIT(parsetree_with_comment)));
1732  dump &= ~DUMP_BIT(parsetree)&~DUMP_BIT(parsetree_with_comment);
1733  if (!dump) return Qtrue;
1734  }
1735 
1736  {
1737  VALUE path = Qnil;
1738  if (!opt->e_script && strcmp(opt->script, "-")) {
1739  path = rb_realpath_internal(Qnil, script_name, 1);
1740 #if UTF8_PATH
1741  if (uenc != lenc) {
1742  path = str_conv_enc(path, uenc, lenc);
1743  }
1744 #endif
1745  }
1746  base_block = toplevel_context(toplevel_binding);
1747  iseq = rb_iseq_new_main(tree, opt->script_name, path, vm_block_iseq(base_block));
1748  }
1749 
1750  if (dump & DUMP_BIT(insns)) {
1751  rb_io_write(rb_stdout, rb_iseq_disasm((const rb_iseq_t *)iseq));
1753  dump &= ~DUMP_BIT(insns);
1754  if (!dump) return Qtrue;
1755  }
1756  if (opt->dump & dump_exit_bits) return Qtrue;
1757 
1758  rb_define_readonly_boolean("$-p", opt->do_print);
1759  rb_define_readonly_boolean("$-l", opt->do_line);
1760  rb_define_readonly_boolean("$-a", opt->do_split);
1761 
1763 
1764  return (VALUE)iseq;
1765 }
1766 
1767 #ifndef DOSISH
1768 static void
1769 warn_cr_in_shebang(const char *str, long len)
1770 {
1771  if (str[len-1] == '\n' && str[len-2] == '\r') {
1772  rb_warn("shebang line ending with \\r may cause problems");
1773  }
1774 }
1775 #else
1776 #define warn_cr_in_shebang(str, len) (void)0
1777 #endif
1778 
1782  int script;
1785 };
1786 
1787 static VALUE
1788 load_file_internal(VALUE argp_v)
1789 {
1790  struct load_file_arg *argp = (struct load_file_arg *)argp_v;
1791  VALUE parser = argp->parser;
1792  VALUE orig_fname = argp->fname;
1793  int script = argp->script;
1794  ruby_cmdline_options_t *opt = argp->opt;
1795  VALUE f = argp->f;
1796  int line_start = 1;
1797  NODE *tree = 0;
1798  rb_encoding *enc;
1799  ID set_encoding;
1800 
1801  CONST_ID(set_encoding, "set_encoding");
1802  if (script) {
1803  VALUE c = 1; /* something not nil */
1804  VALUE line;
1805  char *p, *str;
1806  long len;
1807  int no_src_enc = !opt->src.enc.name;
1808  int no_ext_enc = !opt->ext.enc.name;
1809  int no_int_enc = !opt->intern.enc.name;
1810 
1811  enc = rb_ascii8bit_encoding();
1812  rb_funcall(f, set_encoding, 1, rb_enc_from_encoding(enc));
1813 
1814  if (opt->xflag) {
1815  line_start--;
1816  search_shebang:
1817  while (!NIL_P(line = rb_io_gets(f))) {
1818  line_start++;
1819  RSTRING_GETMEM(line, str, len);
1820  if (len > 2 && str[0] == '#' && str[1] == '!') {
1821  if (line_start == 1) warn_cr_in_shebang(str, len);
1822  if ((p = strstr(str+2, ruby_engine)) != 0) {
1823  goto start_read;
1824  }
1825  }
1826  }
1827  rb_loaderror("no Ruby script found in input");
1828  }
1829 
1830  c = rb_io_getbyte(f);
1831  if (c == INT2FIX('#')) {
1832  c = rb_io_getbyte(f);
1833  if (c == INT2FIX('!')) {
1834  line = rb_io_gets(f);
1835  if (NIL_P(line))
1836  return 0;
1837 
1838  RSTRING_GETMEM(line, str, len);
1839  warn_cr_in_shebang(str, len);
1840  if ((p = strstr(str, ruby_engine)) == 0) {
1841  /* not ruby script, assume -x flag */
1842  goto search_shebang;
1843  }
1844 
1845  start_read:
1846  str += len - 1;
1847  if (*str == '\n') *str-- = '\0';
1848  if (*str == '\r') *str-- = '\0';
1849  /* ruby_engine should not contain a space */
1850  if ((p = strstr(p, " -")) != 0) {
1851  opt->warning = 0;
1852  moreswitches(p + 1, opt, 0);
1853  }
1854 
1855  /* push back shebang for pragma may exist in next line */
1856  rb_io_ungetbyte(f, rb_str_new2("!\n"));
1857  }
1858  else if (!NIL_P(c)) {
1859  rb_io_ungetbyte(f, c);
1860  }
1861  rb_io_ungetbyte(f, INT2FIX('#'));
1862  if (no_src_enc && opt->src.enc.name) {
1863  opt->src.enc.index = opt_enc_index(opt->src.enc.name);
1864  src_encoding_index = opt->src.enc.index;
1865  }
1866  if (no_ext_enc && opt->ext.enc.name) {
1867  opt->ext.enc.index = opt_enc_index(opt->ext.enc.name);
1868  }
1869  if (no_int_enc && opt->intern.enc.name) {
1870  opt->intern.enc.index = opt_enc_index(opt->intern.enc.name);
1871  }
1872  }
1873  else if (!NIL_P(c)) {
1874  rb_io_ungetbyte(f, c);
1875  }
1876  else {
1877  argp->f = f = Qnil;
1878  }
1879  if (!(opt->dump & ~DUMP_BIT(version_v))) {
1881  require_libraries(&opt->req_list); /* Why here? unnatural */
1882  }
1883  }
1884  if (opt->src.enc.index >= 0) {
1885  enc = rb_enc_from_index(opt->src.enc.index);
1886  }
1887  else if (f == rb_stdin) {
1888  enc = rb_locale_encoding();
1889  }
1890  else {
1891  enc = rb_utf8_encoding();
1892  }
1893  if (NIL_P(f)) {
1894  f = rb_str_new(0, 0);
1895  rb_enc_associate(f, enc);
1896  return (VALUE)rb_parser_compile_string_path(parser, orig_fname, f, line_start);
1897  }
1898  rb_funcall(f, set_encoding, 2, rb_enc_from_encoding(enc), rb_str_new_cstr("-"));
1899  tree = rb_parser_compile_file_path(parser, orig_fname, f, line_start);
1900  rb_funcall(f, set_encoding, 1, rb_parser_encoding(parser));
1901  if (script && rb_parser_end_seen_p(parser)) {
1902  /*
1903  * DATA is a File that contains the data section of the executed file.
1904  * To create a data section use <tt>__END__</tt>:
1905  *
1906  * $ cat t.rb
1907  * puts DATA.gets
1908  * __END__
1909  * hello world!
1910  *
1911  * $ ruby t.rb
1912  * hello world!
1913  */
1914  rb_define_global_const("DATA", f);
1915  argp->f = Qnil;
1916  }
1917  return (VALUE)tree;
1918 }
1919 
1920 static VALUE
1921 open_load_file(VALUE fname_v, int *xflag)
1922 {
1923  const char *fname = (fname_v = rb_str_encode_ospath(fname_v),
1924  StringValueCStr(fname_v));
1925  long flen = RSTRING_LEN(fname_v);
1926  VALUE f;
1927  int e;
1928 
1929  if (flen == 1 && fname[0] == '-') {
1930  f = rb_stdin;
1931  }
1932  else {
1933  int fd;
1934  /* open(2) may block if fname is point to FIFO and it's empty. Let's
1935  use O_NONBLOCK. */
1936 #if defined O_NONBLOCK && HAVE_FCNTL && !(O_NONBLOCK & O_ACCMODE)
1937  /* TODO: fix conflicting O_NONBLOCK in ruby/win32.h */
1938 # define MODE_TO_LOAD (O_RDONLY | O_NONBLOCK)
1939 #elif defined O_NDELAY && HAVE_FCNTL && !(O_NDELAY & O_ACCMODE)
1940 # define MODE_TO_LOAD (O_RDONLY | O_NDELAY)
1941 #else
1942 # define MODE_TO_LOAD (O_RDONLY)
1943 #endif
1944  int mode = MODE_TO_LOAD;
1945 #if defined DOSISH || defined __CYGWIN__
1946 # define isdirsep(x) ((x) == '/' || (x) == '\\')
1947  {
1948  static const char exeext[] = ".exe";
1949  enum {extlen = sizeof(exeext)-1};
1950  if (flen > extlen && !isdirsep(fname[flen-extlen-1]) &&
1951  STRNCASECMP(fname+flen-extlen, exeext, extlen) == 0) {
1952  mode |= O_BINARY;
1953  *xflag = 1;
1954  }
1955  }
1956 #endif
1957 
1958  if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) {
1959  int e = errno;
1960  if (!rb_gc_for_fd(e)) {
1961  rb_load_fail(fname_v, strerror(e));
1962  }
1963  if ((fd = rb_cloexec_open(fname, mode, 0)) < 0) {
1964  rb_load_fail(fname_v, strerror(errno));
1965  }
1966  }
1967  rb_update_max_fd(fd);
1968 
1969 #if defined HAVE_FCNTL && MODE_TO_LOAD != O_RDONLY
1970  /* disabling O_NONBLOCK */
1971  if (fcntl(fd, F_SETFL, 0) < 0) {
1972  e = errno;
1973  (void)close(fd);
1974  rb_load_fail(fname_v, strerror(e));
1975  }
1976 #endif
1977 
1978  e = ruby_is_fd_loadable(fd);
1979  if (!e) {
1980  e = errno;
1981  (void)close(fd);
1982  rb_load_fail(fname_v, strerror(e));
1983  }
1984 
1985  f = rb_io_fdopen(fd, mode, fname);
1986  if (e < 0) {
1987  /*
1988  We need to wait if FIFO is empty. It's FIFO's semantics.
1989  rb_thread_wait_fd() release GVL. So, it's safe.
1990  */
1991  rb_thread_wait_fd(fd);
1992  }
1993  }
1994  return f;
1995 }
1996 
1997 static VALUE
1998 restore_load_file(VALUE arg)
1999 {
2000  struct load_file_arg *argp = (struct load_file_arg *)arg;
2001  VALUE f = argp->f;
2002 
2003  if (!NIL_P(f) && f != rb_stdin) {
2004  rb_io_close(f);
2005  }
2006  return Qnil;
2007 }
2008 
2009 static NODE *
2010 load_file(VALUE parser, VALUE fname, VALUE f, int script, ruby_cmdline_options_t *opt)
2011 {
2012  struct load_file_arg arg;
2013  arg.parser = parser;
2014  arg.fname = fname;
2015  arg.script = script;
2016  arg.opt = opt;
2017  arg.f = f;
2018  return (NODE *)rb_ensure(load_file_internal, (VALUE)&arg,
2019  restore_load_file, (VALUE)&arg);
2020 }
2021 
2022 void *
2023 rb_load_file(const char *fname)
2024 {
2025  VALUE fname_v = rb_str_new_cstr(fname);
2026  return rb_load_file_str(fname_v);
2027 }
2028 
2029 void *
2031 {
2032  return rb_parser_load_file(rb_parser_new(), fname_v);
2033 }
2034 
2035 void *
2037 {
2039  VALUE f = open_load_file(fname_v, &cmdline_options_init(&opt)->xflag);
2040  return load_file(parser, fname_v, f, 0, &opt);
2041 }
2042 
2043 /*
2044  * call-seq:
2045  * Process.argv0 -> frozen_string
2046  *
2047  * Returns the name of the script being executed. The value is not
2048  * affected by assigning a new value to $0.
2049  *
2050  * This method first appeared in Ruby 2.1 to serve as a global
2051  * variable free means to get the script name.
2052  */
2053 
2054 static VALUE
2055 proc_argv0(VALUE process)
2056 {
2057  return rb_orig_progname;
2058 }
2059 
2060 static VALUE ruby_setproctitle(VALUE title);
2061 
2062 /*
2063  * call-seq:
2064  * Process.setproctitle(string) -> string
2065  *
2066  * Sets the process title that appears on the ps(1) command. Not
2067  * necessarily effective on all platforms. No exception will be
2068  * raised regardless of the result, nor will NotImplementedError be
2069  * raised even if the platform does not support the feature.
2070  *
2071  * Calling this method does not affect the value of $0.
2072  *
2073  * Process.setproctitle('myapp: worker #%d' % worker_id)
2074  *
2075  * This method first appeared in Ruby 2.1 to serve as a global
2076  * variable free means to change the process title.
2077  */
2078 
2079 static VALUE
2080 proc_setproctitle(VALUE process, VALUE title)
2081 {
2082  return ruby_setproctitle(title);
2083 }
2084 
2085 static VALUE
2086 ruby_setproctitle(VALUE title)
2087 {
2088  const char *ptr = StringValueCStr(title);
2089  setproctitle("%.*s", RSTRING_LENINT(title), ptr);
2090  return title;
2091 }
2092 
2093 static void
2094 set_arg0(VALUE val, ID id)
2095 {
2096  if (origarg.argv == 0)
2097  rb_raise(rb_eRuntimeError, "$0 not initialized");
2098 
2099  rb_progname = rb_str_new_frozen(ruby_setproctitle(val));
2100 }
2101 
2102 static inline VALUE
2103 external_str_new_cstr(const char *p)
2104 {
2105 #if UTF8_PATH
2106  VALUE str = rb_utf8_str_new_cstr(p);
2108 #else
2109  return rb_external_str_new_cstr(p);
2110 #endif
2111 }
2112 
2118 void
2119 ruby_script(const char *name)
2120 {
2121  if (name) {
2122  rb_orig_progname = rb_progname = external_str_new_cstr(name);
2124  }
2125 }
2126 
2131 void
2133 {
2136 }
2137 
2138 static void
2139 init_ids(ruby_cmdline_options_t *opt)
2140 {
2141  rb_uid_t uid = getuid();
2142  rb_uid_t euid = geteuid();
2143  rb_gid_t gid = getgid();
2144  rb_gid_t egid = getegid();
2145 
2146  if (uid != euid) opt->setids |= 1;
2147  if (egid != gid) opt->setids |= 2;
2148  if (uid && opt->setids) {
2149  if (opt->safe_level < 1) opt->safe_level = 1;
2150  }
2151 }
2152 
2153 #undef forbid_setid
2154 static void
2155 forbid_setid(const char *s, const ruby_cmdline_options_t *opt)
2156 {
2157  if (opt->setids & 1)
2158  rb_raise(rb_eSecurityError, "no %s allowed while running setuid", s);
2159  if (opt->setids & 2)
2160  rb_raise(rb_eSecurityError, "no %s allowed while running setgid", s);
2161  if (opt->safe_level > 0)
2162  rb_raise(rb_eSecurityError, "no %s allowed in tainted mode", s);
2163 }
2164 
2165 static void
2166 verbose_setter(VALUE val, ID id, void *data)
2167 {
2168  VALUE *variable = data;
2169  *variable = RTEST(val) ? Qtrue : val;
2170 }
2171 
2172 static VALUE
2173 opt_W_getter(ID id, void *data)
2174 {
2175  VALUE *variable = data;
2176  switch (*variable) {
2177  case Qnil:
2178  return INT2FIX(0);
2179  case Qfalse:
2180  return INT2FIX(1);
2181  case Qtrue:
2182  return INT2FIX(2);
2183  default:
2184  return Qnil;
2185  }
2186 }
2187 
2189 void
2191 {
2192  rb_define_hooked_variable("$VERBOSE", &ruby_verbose, 0, verbose_setter);
2193  rb_define_hooked_variable("$-v", &ruby_verbose, 0, verbose_setter);
2194  rb_define_hooked_variable("$-w", &ruby_verbose, 0, verbose_setter);
2196  rb_define_variable("$DEBUG", &ruby_debug);
2197  rb_define_variable("$-d", &ruby_debug);
2198 
2199  rb_define_hooked_variable("$0", &rb_progname, 0, set_arg0);
2200  rb_define_hooked_variable("$PROGRAM_NAME", &rb_progname, 0, set_arg0);
2201 
2202  rb_define_module_function(rb_mProcess, "argv0", proc_argv0, 0);
2203  rb_define_module_function(rb_mProcess, "setproctitle", proc_setproctitle, 1);
2204 
2205  /*
2206  * ARGV contains the command line arguments used to run ruby.
2207  *
2208  * A library like OptionParser can be used to process command-line
2209  * arguments.
2210  */
2212 }
2213 
2214 void
2215 ruby_set_argv(int argc, char **argv)
2216 {
2217  int i;
2218  VALUE av = rb_argv;
2219 
2220 #if defined(USE_DLN_A_OUT)
2221  if (origarg.argc > 0 && origarg.argv)
2222  dln_argv0 = origarg.argv[0];
2223  else if (argc > 0 && argv)
2224  dln_argv0 = argv[0];
2225 #endif
2226  rb_ary_clear(av);
2227  for (i = 0; i < argc; i++) {
2228  VALUE arg = external_str_new_cstr(argv[i]);
2229 
2230  OBJ_FREEZE(arg);
2231  rb_ary_push(av, arg);
2232  }
2233 }
2234 
2235 void *
2236 ruby_process_options(int argc, char **argv)
2237 {
2239  VALUE iseq;
2240  const char *script_name = (argc > 0 && argv[0]) ? argv[0] : ruby_engine;
2241 
2242  if (!origarg.argv || origarg.argc <= 0) {
2243  origarg.argc = argc;
2244  origarg.argv = argv;
2245  }
2246  ruby_script(script_name); /* for the time being */
2247  rb_argv0 = rb_str_new4(rb_progname);
2248  rb_gc_register_mark_object(rb_argv0);
2249  iseq = process_options(argc, argv, cmdline_options_init(&opt));
2250 
2251 #ifndef HAVE_SETPROCTITLE
2252  ruby_init_setproctitle(argc, argv);
2253 #endif
2254 
2255  return (void*)(struct RData*)iseq;
2256 }
2257 
2258 static void
2259 fill_standard_fds(void)
2260 {
2261  int f0, f1, f2, fds[2];
2262  struct stat buf;
2263  f0 = fstat(0, &buf) == -1 && errno == EBADF;
2264  f1 = fstat(1, &buf) == -1 && errno == EBADF;
2265  f2 = fstat(2, &buf) == -1 && errno == EBADF;
2266  if (f0) {
2267  if (pipe(fds) == 0) {
2268  close(fds[1]);
2269  if (fds[0] != 0) {
2270  dup2(fds[0], 0);
2271  close(fds[0]);
2272  }
2273  }
2274  }
2275  if (f1 || f2) {
2276  if (pipe(fds) == 0) {
2277  close(fds[0]);
2278  if (f1 && fds[1] != 1)
2279  dup2(fds[1], 1);
2280  if (f2 && fds[1] != 2)
2281  dup2(fds[1], 2);
2282  if (fds[1] != 1 && fds[1] != 2)
2283  close(fds[1]);
2284  }
2285  }
2286 }
2287 
2295 void
2296 ruby_sysinit(int *argc, char ***argv)
2297 {
2298 #if defined(_WIN32)
2299  rb_w32_sysinit(argc, argv);
2300 #endif
2301  if (*argc >= 0 && *argv) {
2302  origarg.argc = *argc;
2303  origarg.argv = *argv;
2304 #if defined(USE_DLN_A_OUT)
2305  dln_argv0 = origarg.argv[0];
2306 #endif
2307  }
2308  fill_standard_fds();
2309 }
#define STRNCASECMP(s1, s2, n)
Definition: ruby.h:2159
RUBY_EXTERN VALUE rb_cString
Definition: ruby.h:1927
void rb_define_global_const(const char *, VALUE)
Definition: variable.c:2702
#define RBASIC_CLEAR_CLASS(obj)
Definition: internal.h:1469
void rb_fatal(const char *fmt,...)
Definition: error.c:2338
RUBY_EXTERN VALUE rb_mProcess
Definition: ruby.h:1888
VALUE rb_parser_dump_tree(NODE *node, int comment)
Definition: node.c:1049
unsigned int do_split
Definition: ruby.c:144
void rb_warn(const char *fmt,...)
Definition: error.c:246
#define rb_str_new4
Definition: intern.h:837
VALUE script_name
Definition: ruby.c:126
#define yydebug
Definition: ripper.c:607
#define RARRAY_LEN(a)
Definition: ruby.h:1019
unsigned int dump
Definition: ruby.c:136
VALUE rb_eNameError
Definition: error.c:806
#define FALSE
Definition: nkf.h:174
NODE * rb_parser_compile_string_path(VALUE vparser, VALUE f, VALUE s, int line)
Definition: ripper.c:11540
size_t strlen(const char *)
#define CharNext(p)
Definition: eval_intern.h:325
void rb_update_max_fd(int fd)
Definition: io.c:191
#define scan_oct(s, l, e)
Definition: util.h:53
#define rb_orig_progname
Definition: ruby.c:1355
const char ruby_exec_prefix[]
Definition: loadpath.c:59
rb_uid_t getuid(void)
Definition: win32.c:2710
void Init_enc(void)
Definition: dmyenc.c:5
void * rb_parser_load_file(VALUE parser, VALUE fname_v)
Definition: ruby.c:2036
int script
Definition: ruby.c:1782
void ruby_set_inplace_mode(const char *)
Definition: io.c:12381
#define MAXPATHLEN
Definition: ruby.c:45
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Definition: io.c:257
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2284
VALUE rb_str_cat(VALUE, const char *, long)
Definition: string.c:2746
#define INITIAL_LOAD_PATH_MARK
Definition: ruby.c:478
void ruby_each_words(const char *, void(*)(const char *, int, void *), void *)
Definition: util.c:3822
#define Qtrue
Definition: ruby.h:437
void ruby_show_version(void)
Prints the version information of the CRuby interpreter to stdout.
Definition: version.c:87
NODE * rb_parser_compile_file_path(VALUE vparser, VALUE fname, VALUE file, int start)
Definition: ripper.c:11583
VALUE rb_io_flush(VALUE)
Definition: io.c:1592
VALUE rb_ary_shift(VALUE ary)
Definition: array.c:1019
VALUE rb_parser_end_seen_p(VALUE vparser)
Definition: ripper.c:17412
#define OBJ_FREEZE(x)
Definition: ruby.h:1306
#define SET_WHEN_DEBUG(bit)
int rb_enc_dummy_p(rb_encoding *enc)
Definition: encoding.c:132
struct ruby_cmdline_options::@112 ext
VALUE rb_enc_from_encoding(rb_encoding *encoding)
Definition: encoding.c:117
#define DEFINE_DEBUG_FEATURE(bit)
Definition: ruby.c:82
#define SET_FEATURE(bit)
RUBY_EXTERN VALUE rb_stdin
Definition: ruby.h:1971
rb_encoding * rb_default_internal_encoding(void)
Definition: encoding.c:1510
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:924
#define rubylib_path_new
Definition: ruby.c:285
unsigned int setids
Definition: ruby.c:146
int fcntl(int, int,...)
Definition: win32.c:4297
#define DEFINE_DUMP(bit)
Definition: ruby.c:94
RUBY_EXTERN const int ruby_patchlevel
Definition: ruby.c:870
rb_iseq_t * rb_iseq_new_main(NODE *node, VALUE path, VALUE realpath, const rb_iseq_t *parent)
Definition: iseq.c:473
VALUE rb_funcall(VALUE, ID, int,...)
Calls a method.
Definition: vm_eval.c:774
void rb_str_set_len(VALUE, long)
Definition: string.c:2627
int rb_gc_for_fd(int err)
Definition: io.c:878
void ruby_init_loadpath_safe(int safe_level)
Definition: ruby.c:481
struct ruby_cmdline_options::@112 intern
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Definition: ruby.h:984
void rb_enc_set_default_external(VALUE encoding)
Definition: encoding.c:1477
VALUE rb_enc_associate(VALUE obj, rb_encoding *enc)
Definition: encoding.c:854
VALUE rb_io_getbyte(VALUE)
Definition: io.c:3921
VALUE rb_ary_clear(VALUE ary)
Definition: array.c:3501
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Definition: error.c:848
dump_flag_bits
Definition: ruby.c:114
#define dln_find_file_r
Definition: win32.c:83
#define SHOW(m)
VALUE rb_readlink(VALUE path, rb_encoding *resultenc)
Definition: file.c:599
#define M(shortopt, longopt, desc)
void Init_ext(void)
Definition: dmyext.c:2
unsigned int features
Definition: ruby.c:135
#define str_conv_enc(str, from, to)
Definition: ruby.c:442
VALUE rb_io_write(VALUE, VALUE)
Definition: io.c:1510
void rb_define_global_function(const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a global function.
Definition: class.c:1745
VALUE rb_ensure(VALUE(*b_proc)(ANYARGS), VALUE data1, VALUE(*e_proc)(ANYARGS), VALUE data2)
An equivalent to ensure clause.
Definition: eval.c:1035
unsigned int do_line
Definition: ruby.c:143
VALUE rb_utf8_str_new_cstr(const char *)
Definition: string.c:786
rb_encoding * rb_utf8_encoding(void)
Definition: encoding.c:1320
#define rb_argv
Definition: intern.h:663
VALUE rb_str_tmp_new(long)
Definition: string.c:1310
unsigned int warning
Definition: ruby.c:139
Definition: ruby.h:1071
void rb_load_fail(VALUE path, const char *err)
Definition: error.c:2575
VALUE rb_str_conv_enc_opts(VALUE str, rb_encoding *from, rb_encoding *to, int ecflags, VALUE ecopts)
Definition: string.c:885
VALUE rb_external_str_new_cstr(const char *)
Definition: string.c:1061
VALUE rb_parser_set_yydebug(VALUE self, VALUE flag)
Definition: ripper.c:17457
const char * rb_obj_classname(VALUE)
Definition: variable.c:459
VALUE rb_gv_set(const char *, VALUE)
Definition: variable.c:842
void ruby_incpush(const char *path)
Definition: ruby.c:369
Definition: node.h:233
VALUE rb_utf8_str_new(const char *, long)
Definition: string.c:751
VALUE rb_cISeq
Definition: iseq.c:29
#define RBASIC_SET_CLASS_RAW(obj, cls)
Definition: internal.h:1470
rb_gid_t getegid(void)
Definition: win32.c:2731
#define RB_TYPE_P(obj, type)
Definition: ruby.h:527
#define set_external_encoding_once(opt, e, elen)
Definition: ruby.c:914
#define MEMZERO(p, type, n)
Definition: ruby.h:1660
void rb_set_safe_level(int)
Definition: safe.c:47
VALUE rb_lastline_get(void)
Definition: vm.c:1241
rb_encoding * rb_default_external_encoding(void)
Definition: encoding.c:1425
RUBY_EXTERN VALUE rb_output_rs
Definition: intern.h:518
#define PREFIX_PATH()
#define FEATURE_BIT(bit)
Definition: ruby.c:67
const char * script
Definition: ruby.c:125
VALUE rb_str_encode_ospath(VALUE path)
Definition: file.c:232
#define F_SETFL
Definition: win32.h:587
#define is_option_with_arg(name, allow_hyphen, allow_envopt)
#define val
#define RUBY_RELATIVE(path, len)
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1893
IUnknown DWORD
Definition: win32ole.c:32
VALUE rb_parser_encoding(VALUE vparser)
Definition: ripper.c:17427
#define SET_WHEN_DUMP(bit)
RUBY_EXTERN char * strstr(const char *, const char *)
Definition: strstr.c:8
#define DEFINE_FEATURE(bit)
Definition: ruby.c:81
#define GetBindingPtr(obj, ptr)
Definition: vm_core.h:927
VALUE rb_str_cat2(VALUE, const char *)
#define ECONV_INVALID_REPLACE
Definition: encoding.h:388
VALUE rb_ary_new(void)
Definition: array.c:499
unsigned int do_search
Definition: ruby.c:145
#define NIL_P(v)
Definition: ruby.h:451
void ruby_incpush_expand(const char *path)
Definition: ruby.c:386
#define DEFAULT_RUBYGEMS_ENABLED
Definition: ruby.c:63
#define ISALNUM(c)
Definition: ruby.h:2148
void rb_lastline_set(VALUE)
Definition: vm.c:1247
#define IF_UTF8_PATH(t, f)
Definition: ruby.c:430
NODE * rb_parser_append_print(VALUE vparser, NODE *node)
Definition: ripper.c:17152
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Definition: string.c:1002
int argc
Definition: ruby.c:187
#define Qfalse
Definition: ruby.h:436
VALUE rb_parser_set_context(VALUE vparser, const struct rb_block *base, int main)
Definition: ripper.c:17367
RUBY_EXTERN VALUE rb_fs
Definition: intern.h:514
void rb_gc_register_mark_object(VALUE obj)
Definition: gc.c:6227
#define rb_str_new2
Definition: intern.h:835
#define COMMA
Definition: ruby.c:66
void ruby_push_include(const char *path, VALUE(*filter)(VALUE))
Definition: ruby.c:349
ruby_cmdline_options_t * opt
Definition: ruby.c:1783
unsigned int verbose
Definition: ruby.c:140
#define isdirsep(x)
Definition: dln.c:115
Definition: util.c:841
#define numberof(array)
Definition: etc.c:618
#define LITERAL_NAME_ELEMENT(name)
Definition: ruby.c:815
VALUE rb_str_resize(VALUE, long)
Definition: string.c:2644
void ruby_set_script_name(VALUE name)
Sets the current script name to this value.
Definition: ruby.c:2132
VALUE rb_const_get(VALUE, ID)
Definition: variable.c:2292
VALUE fname
Definition: ruby.c:1781
#define RSTRING_LEN(str)
Definition: ruby.h:971
void rb_define_module_function(VALUE module, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a module function for module.
Definition: class.c:1731
VALUE rb_io_fdopen(int, int, const char *)
Definition: io.c:7648
#define RARRAY_CONST_PTR(a)
Definition: ruby.h:1021
VALUE rb_reg_new(const char *, long, int)
Definition: re.c:2913
#define DUMP_BIT(bit)
Definition: ruby.c:93
int errno
#define TRUE
Definition: nkf.h:175
#define RUBY_EXTERN
Definition: missing.h:77
VALUE rb_obj_freeze(VALUE)
call-seq: obj.freeze -> obj
Definition: object.c:1331
VALUE rb_io_gets(VALUE)
Definition: io.c:3281
VALUE rb_sprintf(const char *format,...)
Definition: sprintf.c:1452
int ruby_is_fd_loadable(int fd)
Definition: file.c:5825
void Init_prelude(void)
void rb_gvar_readonly_setter(VALUE v, ID id, void *d, struct rb_global_variable *g)
Definition: variable.c:572
void ruby_prog_init(void)
Defines built-in variables.
Definition: ruby.c:2190
#define rb_progname
Definition: ruby.c:1354
#define EACH_DEBUG_FEATURES(X, SEP)
Definition: ruby.c:77
VALUE rb_hash_new(void)
Definition: hash.c:424
void rb_str_modify_expand(VALUE, long)
Definition: string.c:2054
VALUE rb_ivar_set(VALUE, ID, VALUE)
Definition: variable.c:1315
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4309
#define PRIsVALUE
Definition: ruby.h:135
unsigned long ID
Definition: ruby.h:86
#define PATH_ENV
Definition: defines.h:306
void rb_thread_wait_fd(int)
Definition: thread.c:3776
#define Qnil
Definition: ruby.h:438
void rb_const_set(VALUE, ID, VALUE)
Definition: variable.c:2573
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition: eval.c:615
feature_flag_bits
Definition: ruby.c:83
VALUE rb_argv0
Definition: ruby.c:1356
VALUE rb_io_close(VALUE)
Definition: io.c:4501
unsigned long VALUE
Definition: ruby.h:85
VALUE rb_vm_top_self(void)
Definition: vm.c:3166
rb_uid_t geteuid(void)
Definition: win32.c:2717
#define set_encoding_part(type)
rb_encoding * rb_locale_encoding(void)
Definition: encoding.c:1370
#define EACH_DUMPS(X, SEP)
Definition: ruby.c:95
VALUE rb_eSecurityError
Definition: error.c:810
char * strchr(char *, char)
VALUE rb_eTypeError
Definition: error.c:801
const char ruby_initial_load_paths[]
Definition: loadpath.c:62
char * getenv()
#define NAME_MATCH_P(name, str, len)
Definition: ruby.c:800
RUBY_EXTERN size_t strlcpy(char *, const char *, size_t)
Definition: strlcpy.c:29
VALUE rb_str_new_cstr(const char *)
Definition: string.c:771
RUBY_EXTERN VALUE rb_rs
Definition: intern.h:516
struct ruby_cmdline_options::@112 src
VALUE rb_io_ungetbyte(VALUE, VALUE)
Definition: io.c:3982
void ruby_gc_set_params(int safe_level)
Definition: gc.c:7553
VALUE rb_str_dup(VALUE)
Definition: string.c:1488
#define forbid_setid(s)
Definition: ruby.c:184
void rb_define_hooked_variable(const char *, VALUE *, VALUE(*)(ANYARGS), void(*)(ANYARGS))
Definition: variable.c:617
#define rb_funcallv
Definition: console.c:21
register unsigned int len
Definition: zonetab.h:51
#define StringValueCStr(v)
Definition: ruby.h:571
#define RSTRING_PTR(str)
Definition: ruby.h:975
#define ECONV_UNDEF_REPLACE
Definition: encoding.h:390
#define RARRAY_ASET(a, i, v)
Definition: ruby.h:1034
VALUE rb_iseq_disasm(const rb_iseq_t *iseq)
Definition: iseq.c:1515
#define set_source_encoding_once(opt, e, elen)
Definition: ruby.c:916
VALUE rb_funcall_passing_block(VALUE, ID, int, const VALUE *)
Definition: vm_eval.c:826
#define f
#define INT2FIX(i)
Definition: ruby.h:232
#define SET_COMPILE_OPTION(h, o, name)
#define RARRAY_AREF(a, i)
Definition: ruby.h:1033
void * ruby_process_options(int argc, char **argv)
Definition: ruby.c:2236
void ruby_script(const char *name)
Sets the current script name to this value.
Definition: ruby.c:2119
VALUE rb_file_expand_path(VALUE fname, VALUE dname)
Definition: file.c:3775
VALUE rb_eRuntimeError
Definition: error.c:800
#define PATH_SEP_CHAR
Definition: defines.h:304
unsigned int do_loop
Definition: ruby.c:141
unsigned int do_print
Definition: ruby.c:142
void ruby_init_loadpath(void)
Definition: ruby.c:448
void rb_enc_set_default_internal(VALUE encoding)
Definition: encoding.c:1561
RUBY_EXTERN char * strerror(int)
Definition: strerror.c:11
void ruby_set_argv(int argc, char **argv)
Definition: ruby.c:2215
#define RTEST(v)
Definition: ruby.h:450
void rb_warning(const char *fmt,...)
Definition: error.c:267
#define T_STRING
Definition: ruby.h:496
VALUE rb_class_new_instance(int, const VALUE *, VALUE)
Allocates and initializes an instance of klass.
Definition: object.c:2170
struct rb_encoding_entry * list
Definition: encoding.c:55
void rb_define_variable(const char *, VALUE *)
Definition: variable.c:636
VALUE rb_str_cat_cstr(VALUE, const char *)
Definition: string.c:2756
#define set_internal_encoding_once(opt, e, elen)
Definition: ruby.c:912
#define ISPRINT(c)
Definition: ruby.h:2143
#define TOLOWER(c)
Definition: ruby.h:2154
#define src_encoding_index
Definition: ruby.c:151
void rb_vm_set_progname(VALUE filename)
Definition: vm.c:3110
VALUE f
Definition: ruby.c:1784
VALUE rb_parser_new(void)
Definition: ripper.c:17357
VALUE rb_realpath_internal(VALUE basedir, VALUE path, int strict)
Definition: file.c:4078
char * rb_enc_path_last_separator(const char *path, const char *end, rb_encoding *enc)
Definition: file.c:3157
#define ruby_debug
Definition: ruby.h:1814
#define StringValuePtr(v)
Definition: ruby.h:570
void ruby_sysinit(int *argc, char ***argv)
Initializes the process for libruby.
Definition: ruby.c:2296
void * rb_load_file_str(VALUE fname_v)
Definition: ruby.c:2030
RUBY_EXTERN int dup2(int, int)
Definition: dup2.c:27
enum rb_block_type type
Definition: vm_core.h:659
VALUE rb_str_new_frozen(VALUE)
Definition: string.c:1158
#define EACH_FEATURES(X, SEP)
Definition: ruby.c:68
#define ruby_show_copyright()
Definition: backward.h:65
rb_encoding * rb_ascii8bit_encoding(void)
Definition: encoding.c:1305
rb_gid_t getgid(void)
Definition: win32.c:2724
int rb_enc_find_index(const char *name)
Definition: encoding.c:704
#define is_option_with_optarg(name, allow_hyphen, allow_envopt, needs_arg, next_arg)
#define RSTRING_LENINT(str)
Definition: ruby.h:983
#define CONST_ID(var, str)
Definition: ruby.h:1743
VALUE parser
Definition: ruby.c:1780
RUBY_EXTERN VALUE rb_stdout
Definition: ruby.h:1971
#define rb_intern_const(str)
Definition: ruby.h:1777
VALUE rb_define_module(const char *name)
Definition: class.c:768
void rb_stdio_set_default_encoding(void)
Definition: io.c:11284
#define rb_intern(str)
void ruby_init_setproctitle(int argc, char *argv[])
#define fstat(fd, st)
Definition: win32.h:184
#define stat(path, st)
Definition: win32.h:183
#define mod(x, y)
Definition: date_strftime.c:28
VALUE rb_const_remove(VALUE, ID)
Definition: variable.c:2344
#define NULL
Definition: _sdbm.c:102
#define rb_define_readonly_boolean(name, val)
Definition: ruby.c:1370
struct ruby_cmdline_options::@112::@113 enc
RUBY_EXTERN void setproctitle(const char *fmt,...)
Definition: setproctitle.c:139
const struct rb_block block
Definition: vm_core.h:931
#define MODE_TO_LOAD
#define ruby_verbose
Definition: ruby.h:1813
NODE * rb_parser_while_loop(VALUE vparser, NODE *node, int chomp, int split)
Definition: ripper.c:17185
void rb_loaderror(const char *fmt,...)
Definition: error.c:2306
NODE * rb_parser_compile_string(VALUE vparser, const char *f, VALUE s, int line)
Definition: ripper.c:11534
#define O_BINARY
Definition: _sdbm.c:88
int ruby_env_debug_option(const char *str, int len, void *arg)
Definition: debug.c:143
const char ruby_engine[]
Definition: version.c:35
void rb_w32_sysinit(int *, char ***)
Definition: win32.c:831
VALUE rb_attr_get(VALUE, ID)
Definition: variable.c:1224
char * strrchr(const char *, const char)
char ** argv
Definition: ruby.c:188
#define ISSPACE(c)
Definition: ruby.h:2145
#define require(name)
Definition: dmyenc.c:1
rb_encoding * rb_enc_from_index(int index)
Definition: encoding.c:616
void * rb_load_file(const char *fname)
Definition: ruby.c:2023
VALUE rb_str_new(const char *, long)
Definition: string.c:737
#define GET_VM()
Definition: vm_core.h:1582