Ruby  2.0.0p195(2013-05-14revision40734)
load.c
Go to the documentation of this file.
1 /*
2  * load methods from eval.c
3  */
4 
5 #include "ruby/ruby.h"
6 #include "ruby/util.h"
7 #include "internal.h"
8 #include "dln.h"
9 #include "eval_intern.h"
10 #include "probes.h"
11 
13 
14 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
15 
16 #define IS_RBEXT(e) (strcmp((e), ".rb") == 0)
17 #define IS_SOEXT(e) (strcmp((e), ".so") == 0 || strcmp((e), ".o") == 0)
18 #ifdef DLEXT2
19 #define IS_DLEXT(e) (strcmp((e), DLEXT) == 0 || strcmp((e), DLEXT2) == 0)
20 #else
21 #define IS_DLEXT(e) (strcmp((e), DLEXT) == 0)
22 #endif
23 
24 static const char *const loadable_ext[] = {
25  ".rb", DLEXT,
26 #ifdef DLEXT2
27  DLEXT2,
28 #endif
29  0
30 };
31 
32 VALUE
34 {
35  VALUE load_path = GET_VM()->load_path;
36  return load_path;
37 }
38 
44 };
45 
46 /* Construct expanded load path and store it to cache.
47  We rebuild load path partially if the cache is invalid.
48  We don't cache non string object and expand it every time. We ensure that
49  string objects in $LOAD_PATH are frozen.
50  */
51 static void
52 rb_construct_expanded_load_path(int type, int *has_relative, int *has_non_cache)
53 {
54  rb_vm_t *vm = GET_VM();
55  VALUE load_path = vm->load_path;
56  VALUE expanded_load_path = vm->expanded_load_path;
57  VALUE ary;
58  long i;
59  int level = rb_safe_level();
60 
61  ary = rb_ary_tmp_new(RARRAY_LEN(load_path));
62  for (i = 0; i < RARRAY_LEN(load_path); ++i) {
63  VALUE path, as_str, expanded_path;
64  int is_string, non_cache;
65  char *as_cstr;
66  as_str = path = RARRAY_PTR(load_path)[i];
67  is_string = RB_TYPE_P(path, T_STRING) ? 1 : 0;
68  non_cache = !is_string ? 1 : 0;
69  as_str = rb_get_path_check_to_string(path, level);
70  as_cstr = RSTRING_PTR(as_str);
71 
72  if (!non_cache) {
73  if ((type == EXPAND_RELATIVE &&
74  rb_is_absolute_path(as_cstr)) ||
75  (type == EXPAND_HOME &&
76  (!as_cstr[0] || as_cstr[0] != '~')) ||
77  (type == EXPAND_NON_CACHE)) {
78  /* Use cached expanded path. */
79  rb_ary_push(ary, RARRAY_PTR(expanded_load_path)[i]);
80  continue;
81  }
82  }
83  if (!*has_relative && !rb_is_absolute_path(as_cstr))
84  *has_relative = 1;
85  if (!*has_non_cache && non_cache)
86  *has_non_cache = 1;
87  /* Freeze only string object. We expand other objects every time. */
88  if (is_string)
89  rb_str_freeze(path);
90  as_str = rb_get_path_check_convert(path, as_str, level);
91  expanded_path = rb_file_expand_path_fast(as_str, Qnil);
92  rb_str_freeze(expanded_path);
93  rb_ary_push(ary, expanded_path);
94  }
95  rb_obj_freeze(ary);
96  vm->expanded_load_path = ary;
98 }
99 
100 static VALUE
102 {
103  char *cwd = my_getcwd();
104  VALUE cwd_str = rb_filesystem_str_new_cstr(cwd);
105  xfree(cwd);
106  return cwd_str;
107 }
108 
109 VALUE
111 {
112  rb_vm_t *vm = GET_VM();
113  const VALUE non_cache = Qtrue;
114 
116  /* The load path was modified. Rebuild the expanded load path. */
117  int has_relative = 0, has_non_cache = 0;
118  rb_construct_expanded_load_path(EXPAND_ALL, &has_relative, &has_non_cache);
119  if (has_relative) {
121  }
122  else if (has_non_cache) {
123  /* Non string object. */
124  vm->load_path_check_cache = non_cache;
125  }
126  else {
127  vm->load_path_check_cache = 0;
128  }
129  }
130  else if (vm->load_path_check_cache == non_cache) {
131  int has_relative = 1, has_non_cache = 1;
132  /* Expand only non-cacheable objects. */
134  &has_relative, &has_non_cache);
135  }
136  else if (vm->load_path_check_cache) {
137  int has_relative = 1, has_non_cache = 1;
138  VALUE cwd = load_path_getcwd();
139  if (!rb_str_equal(vm->load_path_check_cache, cwd)) {
140  /* Current working directory or filesystem encoding was changed.
141  Expand relative load path and non-cacheable objects again. */
142  vm->load_path_check_cache = cwd;
144  &has_relative, &has_non_cache);
145  }
146  else {
147  /* Expand only tilde (User HOME) and non-cacheable objects. */
149  &has_relative, &has_non_cache);
150  }
151  }
152  return vm->expanded_load_path;
153 }
154 
155 static VALUE
157 {
158  return vm->load_path;
159 }
160 
161 static VALUE
163 {
164  return GET_VM()->loaded_features;
165 }
166 
167 static void
169 {
170  rb_vm_t *vm = GET_VM();
172 }
173 
174 static struct st_table *
176 {
177  return GET_VM()->loaded_features_index;
178 }
179 
180 static st_table *
182 {
183  return GET_VM()->loading_table;
184 }
185 
186 static void
187 features_index_add_single(VALUE short_feature, VALUE offset)
188 {
189  struct st_table *features_index;
190  VALUE this_feature_index = Qnil;
191  char *short_feature_cstr;
192 
193  Check_Type(offset, T_FIXNUM);
194  Check_Type(short_feature, T_STRING);
195  short_feature_cstr = StringValueCStr(short_feature);
196 
197  features_index = get_loaded_features_index_raw();
198  st_lookup(features_index, (st_data_t)short_feature_cstr, (st_data_t *)&this_feature_index);
199 
200  if (NIL_P(this_feature_index)) {
201  st_insert(features_index, (st_data_t)ruby_strdup(short_feature_cstr), (st_data_t)offset);
202  }
203  else if (RB_TYPE_P(this_feature_index, T_FIXNUM)) {
204  VALUE feature_indexes[2];
205  feature_indexes[0] = this_feature_index;
206  feature_indexes[1] = offset;
207  this_feature_index = rb_ary_tmp_new(numberof(feature_indexes));
208  rb_ary_cat(this_feature_index, feature_indexes, numberof(feature_indexes));
209  st_insert(features_index, (st_data_t)short_feature_cstr, (st_data_t)this_feature_index);
210  }
211  else {
212  Check_Type(this_feature_index, T_ARRAY);
213  rb_ary_push(this_feature_index, offset);
214  }
215 }
216 
217 /* Add to the loaded-features index all the required entries for
218  `feature`, located at `offset` in $LOADED_FEATURES. We add an
219  index entry at each string `short_feature` for which
220  feature == "#{prefix}#{short_feature}#{e}"
221  where `e` is empty or matches %r{^\.[^./]*$}, and `prefix` is empty
222  or ends in '/'. This maintains the invariant that `rb_feature_p()`
223  relies on for its fast lookup.
224 */
225 static void
227 {
228  VALUE short_feature;
229  const char *feature_str, *feature_end, *ext, *p;
230 
231  feature_str = StringValuePtr(feature);
232  feature_end = feature_str + RSTRING_LEN(feature);
233 
234  for (ext = feature_end; ext > feature_str; ext--)
235  if (*ext == '.' || *ext == '/')
236  break;
237  if (*ext != '.')
238  ext = NULL;
239  /* Now `ext` points to the only string matching %r{^\.[^./]*$} that is
240  at the end of `feature`, or is NULL if there is no such string. */
241 
242  p = ext ? ext : feature_end;
243  while (1) {
244  p--;
245  while (p >= feature_str && *p != '/')
246  p--;
247  if (p < feature_str)
248  break;
249  /* Now *p == '/'. We reach this point for every '/' in `feature`. */
250  short_feature = rb_str_subseq(feature, p + 1 - feature_str, feature_end - p - 1);
251  features_index_add_single(short_feature, offset);
252  if (ext) {
253  short_feature = rb_str_subseq(feature, p + 1 - feature_str, ext - p - 1);
254  features_index_add_single(short_feature, offset);
255  }
256  }
257  features_index_add_single(feature, offset);
258  if (ext) {
259  short_feature = rb_str_subseq(feature, 0, ext - feature_str);
260  features_index_add_single(short_feature, offset);
261  }
262 }
263 
264 static int
266 {
267  xfree((char *)key);
268  return ST_DELETE;
269 }
270 
271 static st_table *
273 {
274  VALUE features;
275  int i;
276  rb_vm_t *vm = GET_VM();
277 
279  /* The sharing was broken; something (other than us in rb_provide_feature())
280  modified loaded_features. Rebuild the index. */
282  features = vm->loaded_features;
283  for (i = 0; i < RARRAY_LEN(features); i++) {
284  VALUE entry, as_str;
285  as_str = entry = rb_ary_entry(features, i);
286  StringValue(as_str);
287  if (as_str != entry)
288  rb_ary_store(features, i, as_str);
289  rb_str_freeze(as_str);
290  features_index_add(as_str, INT2FIX(i));
291  }
293  }
294  return vm->loaded_features_index;
295 }
296 
297 /* This searches `load_path` for a value such that
298  name == "#{load_path[i]}/#{feature}"
299  if `feature` is a suffix of `name`, or otherwise
300  name == "#{load_path[i]}/#{feature}#{ext}"
301  for an acceptable string `ext`. It returns
302  `load_path[i].to_str` if found, else 0.
303 
304  If type is 's', then `ext` is acceptable only if IS_DLEXT(ext);
305  if 'r', then only if IS_RBEXT(ext); otherwise `ext` may be absent
306  or have any value matching `%r{^\.[^./]*$}`.
307 */
308 static VALUE
309 loaded_feature_path(const char *name, long vlen, const char *feature, long len,
310  int type, VALUE load_path)
311 {
312  long i;
313  long plen;
314  const char *e;
315 
316  if (vlen < len+1) return 0;
317  if (!strncmp(name+(vlen-len), feature, len)) {
318  plen = vlen - len - 1;
319  }
320  else {
321  for (e = name + vlen; name != e && *e != '.' && *e != '/'; --e);
322  if (*e != '.' ||
323  e-name < len ||
324  strncmp(e-len, feature, len))
325  return 0;
326  plen = e - name - len - 1;
327  }
328  if (type == 's' && !IS_DLEXT(&name[plen+len+1])
329  || type == 'r' && !IS_RBEXT(&name[plen+len+1])
330  || name[plen] != '/') {
331  return 0;
332  }
333  /* Now name == "#{prefix}/#{feature}#{ext}" where ext is acceptable
334  (possibly empty) and prefix is some string of length plen. */
335 
336  for (i = 0; i < RARRAY_LEN(load_path); ++i) {
337  VALUE p = RARRAY_PTR(load_path)[i];
338  const char *s = StringValuePtr(p);
339  long n = RSTRING_LEN(p);
340 
341  if (n != plen) continue;
342  if (n && strncmp(name, s, n)) continue;
343  return p;
344  }
345  return 0;
346 }
347 
349  const char *name;
350  long len;
351  int type;
353  const char *result;
354 };
355 
356 static int
358 {
359  const char *s = (const char *)v;
360  struct loaded_feature_searching *fp = (struct loaded_feature_searching *)f;
361  VALUE p = loaded_feature_path(s, strlen(s), fp->name, fp->len,
362  fp->type, fp->load_path);
363  if (!p) return ST_CONTINUE;
364  fp->result = s;
365  return ST_STOP;
366 }
367 
368 static int
369 rb_feature_p(const char *feature, const char *ext, int rb, int expanded, const char **fn)
370 {
371  VALUE features, this_feature_index = Qnil, v, p, load_path = 0;
372  const char *f, *e;
373  long i, len, elen, n;
374  st_table *loading_tbl, *features_index;
375  st_data_t data;
376  int type;
377 
378  if (fn) *fn = 0;
379  if (ext) {
380  elen = strlen(ext);
381  len = strlen(feature) - elen;
382  type = rb ? 'r' : 's';
383  }
384  else {
385  len = strlen(feature);
386  elen = 0;
387  type = 0;
388  }
389  features = get_loaded_features();
390  features_index = get_loaded_features_index();
391 
392  st_lookup(features_index, (st_data_t)feature, (st_data_t *)&this_feature_index);
393  /* We search `features` for an entry such that either
394  "#{features[i]}" == "#{load_path[j]}/#{feature}#{e}"
395  for some j, or
396  "#{features[i]}" == "#{feature}#{e}"
397  Here `e` is an "allowed" extension -- either empty or one
398  of the extensions accepted by IS_RBEXT, IS_SOEXT, or
399  IS_DLEXT. Further, if `ext && rb` then `IS_RBEXT(e)`,
400  and if `ext && !rb` then `IS_SOEXT(e) || IS_DLEXT(e)`.
401 
402  If `expanded`, then only the latter form (without load_path[j])
403  is accepted. Otherwise either form is accepted, *unless* `ext`
404  is false and an otherwise-matching entry of the first form is
405  preceded by an entry of the form
406  "#{features[i2]}" == "#{load_path[j2]}/#{feature}#{e2}"
407  where `e2` matches %r{^\.[^./]*$} but is not an allowed extension.
408  After a "distractor" entry of this form, only entries of the
409  form "#{feature}#{e}" are accepted.
410 
411  In `rb_provide_feature()` and `get_loaded_features_index()` we
412  maintain an invariant that the array `this_feature_index` will
413  point to every entry in `features` which has the form
414  "#{prefix}#{feature}#{e}"
415  where `e` is empty or matches %r{^\.[^./]*$}, and `prefix` is empty
416  or ends in '/'. This includes both match forms above, as well
417  as any distractors, so we may ignore all other entries in `features`.
418  */
419  for (i = 0; !NIL_P(this_feature_index); i++) {
420  VALUE entry;
421  long index;
422  if (RB_TYPE_P(this_feature_index, T_ARRAY)) {
423  if (i >= RARRAY_LEN(this_feature_index)) break;
424  entry = RARRAY_PTR(this_feature_index)[i];
425  }
426  else {
427  if (i > 0) break;
428  entry = this_feature_index;
429  }
430  index = FIX2LONG(entry);
431 
432  v = RARRAY_PTR(features)[index];
433  f = StringValuePtr(v);
434  if ((n = RSTRING_LEN(v)) < len) continue;
435  if (strncmp(f, feature, len) != 0) {
436  if (expanded) continue;
437  if (!load_path) load_path = rb_get_expanded_load_path();
438  if (!(p = loaded_feature_path(f, n, feature, len, type, load_path)))
439  continue;
440  expanded = 1;
441  f += RSTRING_LEN(p) + 1;
442  }
443  if (!*(e = f + len)) {
444  if (ext) continue;
445  return 'u';
446  }
447  if (*e != '.') continue;
448  if ((!rb || !ext) && (IS_SOEXT(e) || IS_DLEXT(e))) {
449  return 's';
450  }
451  if ((rb || !ext) && (IS_RBEXT(e))) {
452  return 'r';
453  }
454  }
455 
456  loading_tbl = get_loading_table();
457  if (loading_tbl) {
458  f = 0;
459  if (!expanded) {
460  struct loaded_feature_searching fs;
461  fs.name = feature;
462  fs.len = len;
463  fs.type = type;
464  fs.load_path = load_path ? load_path : rb_get_expanded_load_path();
465  fs.result = 0;
466  st_foreach(loading_tbl, loaded_feature_path_i, (st_data_t)&fs);
467  if ((f = fs.result) != 0) {
468  if (fn) *fn = f;
469  goto loading;
470  }
471  }
472  if (st_get_key(loading_tbl, (st_data_t)feature, &data)) {
473  if (fn) *fn = (const char*)data;
474  loading:
475  if (!ext) return 'u';
476  return !IS_RBEXT(ext) ? 's' : 'r';
477  }
478  else {
479  VALUE bufstr;
480  char *buf;
481 
482  if (ext && *ext) return 0;
483  bufstr = rb_str_tmp_new(len + DLEXT_MAXLEN);
484  buf = RSTRING_PTR(bufstr);
485  MEMCPY(buf, feature, char, len);
486  for (i = 0; (e = loadable_ext[i]) != 0; i++) {
487  strlcpy(buf + len, e, DLEXT_MAXLEN + 1);
488  if (st_get_key(loading_tbl, (st_data_t)buf, &data)) {
489  rb_str_resize(bufstr, 0);
490  if (fn) *fn = (const char*)data;
491  return i ? 's' : 'r';
492  }
493  }
494  rb_str_resize(bufstr, 0);
495  }
496  }
497  return 0;
498 }
499 
500 int
501 rb_provided(const char *feature)
502 {
503  return rb_feature_provided(feature, 0);
504 }
505 
506 int
507 rb_feature_provided(const char *feature, const char **loading)
508 {
509  const char *ext = strrchr(feature, '.');
510  volatile VALUE fullpath = 0;
511 
512  if (*feature == '.' &&
513  (feature[1] == '/' || strncmp(feature+1, "./", 2) == 0)) {
514  fullpath = rb_file_expand_path_fast(rb_get_path(rb_str_new2(feature)), Qnil);
515  feature = RSTRING_PTR(fullpath);
516  }
517  if (ext && !strchr(ext, '/')) {
518  if (IS_RBEXT(ext)) {
519  if (rb_feature_p(feature, ext, TRUE, FALSE, loading)) return TRUE;
520  return FALSE;
521  }
522  else if (IS_SOEXT(ext) || IS_DLEXT(ext)) {
523  if (rb_feature_p(feature, ext, FALSE, FALSE, loading)) return TRUE;
524  return FALSE;
525  }
526  }
527  if (rb_feature_p(feature, 0, TRUE, FALSE, loading))
528  return TRUE;
529  return FALSE;
530 }
531 
532 static void
534 {
535  VALUE features;
536 
537  features = get_loaded_features();
538  if (OBJ_FROZEN(features)) {
540  "$LOADED_FEATURES is frozen; cannot append feature");
541  }
542  rb_str_freeze(feature);
543 
544  rb_ary_push(features, feature);
545  features_index_add(feature, INT2FIX(RARRAY_LEN(features)-1));
547 }
548 
549 void
550 rb_provide(const char *feature)
551 {
553 }
554 
555 NORETURN(static void load_failed(VALUE));
556 
557 static void
558 rb_load_internal(VALUE fname, int wrap)
559 {
560  int state;
561  rb_thread_t *th = GET_THREAD();
562  volatile VALUE wrapper = th->top_wrapper;
563  volatile VALUE self = th->top_self;
564  volatile int loaded = FALSE;
565  volatile int mild_compile_error;
566 #ifndef __GNUC__
567  rb_thread_t *volatile th0 = th;
568 #endif
569 
570  th->errinfo = Qnil; /* ensure */
571 
572  if (!wrap) {
573  rb_secure(4); /* should alter global state */
574  th->top_wrapper = 0;
575  }
576  else {
577  /* load in anonymous module as toplevel */
579  th->top_wrapper = rb_module_new();
581  }
582 
583  mild_compile_error = th->mild_compile_error;
584  PUSH_TAG();
585  state = EXEC_TAG();
586  if (state == 0) {
587  NODE *node;
588  VALUE iseq;
589 
590  th->mild_compile_error++;
591  node = (NODE *)rb_load_file(RSTRING_PTR(fname));
592  loaded = TRUE;
593  iseq = rb_iseq_new_top(node, rb_str_new2("<top (required)>"), fname, rb_realpath_internal(Qnil, fname, 1), Qfalse);
594  th->mild_compile_error--;
595  rb_iseq_eval(iseq);
596  }
597  POP_TAG();
598 
599 #ifndef __GNUC__
600  th = th0;
601  fname = RB_GC_GUARD(fname);
602 #endif
603  th->mild_compile_error = mild_compile_error;
604  th->top_self = self;
605  th->top_wrapper = wrapper;
606 
607  if (!loaded && !FIXNUM_P(GET_THREAD()->errinfo)) {
608  /* an error on loading don't include INT2FIX(TAG_FATAL) see r35625 */
609  rb_exc_raise(GET_THREAD()->errinfo);
610  }
611  if (state) {
613  }
614 
615  if (!NIL_P(GET_THREAD()->errinfo)) {
616  /* exception during load */
617  rb_exc_raise(th->errinfo);
618  }
619 }
620 
621 void
622 rb_load(VALUE fname, int wrap)
623 {
624  VALUE tmp = rb_find_file(FilePathValue(fname));
625  if (!tmp) load_failed(fname);
626  rb_load_internal(tmp, wrap);
627 }
628 
629 void
630 rb_load_protect(VALUE fname, int wrap, int *state)
631 {
632  int status;
633 
634  PUSH_TAG();
635  if ((status = EXEC_TAG()) == 0) {
636  rb_load(fname, wrap);
637  }
638  POP_TAG();
639  if (state)
640  *state = status;
641 }
642 
643 /*
644  * call-seq:
645  * load(filename, wrap=false) -> true
646  *
647  * Loads and executes the Ruby
648  * program in the file _filename_. If the filename does not
649  * resolve to an absolute path, the file is searched for in the library
650  * directories listed in <code>$:</code>. If the optional _wrap_
651  * parameter is +true+, the loaded script will be executed
652  * under an anonymous module, protecting the calling program's global
653  * namespace. In no circumstance will any local variables in the loaded
654  * file be propagated to the loading environment.
655  */
656 
657 static VALUE
659 {
660  VALUE fname, wrap, path;
661 
662  rb_scan_args(argc, argv, "11", &fname, &wrap);
663 
666  rb_sourcefile(),
667  rb_sourceline());
668  }
669 
670  path = rb_find_file(FilePathValue(fname));
671  if (!path) {
672  if (!rb_file_load_ok(RSTRING_PTR(fname)))
673  load_failed(fname);
674  path = fname;
675  }
676  rb_load_internal(path, RTEST(wrap));
677 
680  rb_sourcefile(),
681  rb_sourceline());
682  }
683 
684  return Qtrue;
685 }
686 
687 static char *
688 load_lock(const char *ftptr)
689 {
690  st_data_t data;
691  st_table *loading_tbl = get_loading_table();
692 
693  if (!loading_tbl || !st_lookup(loading_tbl, (st_data_t)ftptr, &data)) {
694  /* loading ruby library should be serialized. */
695  if (!loading_tbl) {
696  GET_VM()->loading_table = loading_tbl = st_init_strtable();
697  }
698  /* partial state */
699  ftptr = ruby_strdup(ftptr);
701  st_insert(loading_tbl, (st_data_t)ftptr, data);
702  return (char *)ftptr;
703  }
704  if (RTEST(ruby_verbose)) {
705  rb_warning("loading in progress, circular require considered harmful - %s", ftptr);
706  /* TODO: display to $stderr, not stderr in C */
707  rb_backtrace();
708  }
709  switch (rb_thread_shield_wait((VALUE)data)) {
710  case Qfalse:
711  data = (st_data_t)ftptr;
712  st_insert(loading_tbl, data, (st_data_t)rb_thread_shield_new());
713  return 0;
714  case Qnil:
715  return 0;
716  }
717  return (char *)ftptr;
718 }
719 
720 static int
722 {
723  VALUE thread_shield = (VALUE)*value;
724  if (!existing) return ST_STOP;
725  if (done ? rb_thread_shield_destroy(thread_shield) : rb_thread_shield_release(thread_shield)) {
726  /* still in-use */
727  return ST_CONTINUE;
728  }
729  xfree((char *)*key);
730  return ST_DELETE;
731 }
732 
733 static void
734 load_unlock(const char *ftptr, int done)
735 {
736  if (ftptr) {
737  st_data_t key = (st_data_t)ftptr;
738  st_table *loading_tbl = get_loading_table();
739 
740  st_update(loading_tbl, key, release_thread_shield, done);
741  }
742 }
743 
744 
745 /*
746  * call-seq:
747  * require(name) -> true or false
748  *
749  * Loads the given +name+, returning +true+ if successful and +false+ if the
750  * feature is already loaded.
751  *
752  * If the filename does not resolve to an absolute path, it will be searched
753  * for in the directories listed in <code>$LOAD_PATH</code> (<code>$:</code>).
754  *
755  * If the filename has the extension ".rb", it is loaded as a source file; if
756  * the extension is ".so", ".o", or ".dll", or the default shared library
757  * extension on the current platform, Ruby loads the shared library as a
758  * Ruby extension. Otherwise, Ruby tries adding ".rb", ".so", and so on
759  * to the name until found. If the file named cannot be found, a LoadError
760  * will be raised.
761  *
762  * For Ruby extensions the filename given may use any shared library
763  * extension. For example, on Linux the socket extension is "socket.so" and
764  * <code>require 'socket.dll'</code> will load the socket extension.
765  *
766  * The absolute path of the loaded file is added to
767  * <code>$LOADED_FEATURES</code> (<code>$"</code>). A file will not be
768  * loaded again if its path already appears in <code>$"</code>. For example,
769  * <code>require 'a'; require './a'</code> will not load <code>a.rb</code>
770  * again.
771  *
772  * require "my-library.rb"
773  * require "db-driver"
774  *
775  * Any constants or globals within the loaded source file will be available
776  * in the calling program's global namespace. However, local variables will
777  * not be propagated to the loading environment.
778  *
779  */
780 
781 VALUE
783 {
784  return rb_require_safe(fname, rb_safe_level());
785 }
786 
787 /*
788  * call-seq:
789  * require_relative(string) -> true or false
790  *
791  * Ruby tries to load the library named _string_ relative to the requiring
792  * file's path. If the file's path cannot be determined a LoadError is raised.
793  * If a file is loaded +true+ is returned and false otherwise.
794  */
795 VALUE
797 {
799  if (NIL_P(base)) {
800  rb_loaderror("cannot infer basepath");
801  }
802  base = rb_file_dirname(base);
803  return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
804 }
805 
806 static int
807 search_required(VALUE fname, volatile VALUE *path, int safe_level)
808 {
809  VALUE tmp;
810  char *ext, *ftptr;
811  int type, ft = 0;
812  const char *loading;
813 
814  *path = 0;
815  ext = strrchr(ftptr = RSTRING_PTR(fname), '.');
816  if (ext && !strchr(ext, '/')) {
817  if (IS_RBEXT(ext)) {
818  if (rb_feature_p(ftptr, ext, TRUE, FALSE, &loading)) {
819  if (loading) *path = rb_filesystem_str_new_cstr(loading);
820  return 'r';
821  }
822  if ((tmp = rb_find_file_safe(fname, safe_level)) != 0) {
823  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
824  if (!rb_feature_p(ftptr, ext, TRUE, TRUE, &loading) || loading)
825  *path = tmp;
826  return 'r';
827  }
828  return 0;
829  }
830  else if (IS_SOEXT(ext)) {
831  if (rb_feature_p(ftptr, ext, FALSE, FALSE, &loading)) {
832  if (loading) *path = rb_filesystem_str_new_cstr(loading);
833  return 's';
834  }
835  tmp = rb_str_subseq(fname, 0, ext - RSTRING_PTR(fname));
836 #ifdef DLEXT2
837  OBJ_FREEZE(tmp);
838  if (rb_find_file_ext_safe(&tmp, loadable_ext + 1, safe_level)) {
839  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
840  if (!rb_feature_p(ftptr, ext, FALSE, TRUE, &loading) || loading)
841  *path = tmp;
842  return 's';
843  }
844 #else
845  rb_str_cat2(tmp, DLEXT);
846  OBJ_FREEZE(tmp);
847  if ((tmp = rb_find_file_safe(tmp, safe_level)) != 0) {
848  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
849  if (!rb_feature_p(ftptr, ext, FALSE, TRUE, &loading) || loading)
850  *path = tmp;
851  return 's';
852  }
853 #endif
854  }
855  else if (IS_DLEXT(ext)) {
856  if (rb_feature_p(ftptr, ext, FALSE, FALSE, &loading)) {
857  if (loading) *path = rb_filesystem_str_new_cstr(loading);
858  return 's';
859  }
860  if ((tmp = rb_find_file_safe(fname, safe_level)) != 0) {
861  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
862  if (!rb_feature_p(ftptr, ext, FALSE, TRUE, &loading) || loading)
863  *path = tmp;
864  return 's';
865  }
866  }
867  }
868  else if ((ft = rb_feature_p(ftptr, 0, FALSE, FALSE, &loading)) == 'r') {
869  if (loading) *path = rb_filesystem_str_new_cstr(loading);
870  return 'r';
871  }
872  tmp = fname;
873  type = rb_find_file_ext_safe(&tmp, loadable_ext, safe_level);
874  switch (type) {
875  case 0:
876  if (ft)
877  break;
878  ftptr = RSTRING_PTR(tmp);
879  return rb_feature_p(ftptr, 0, FALSE, TRUE, 0);
880 
881  default:
882  if (ft)
883  break;
884  case 1:
885  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
886  if (rb_feature_p(ftptr, ext, !--type, TRUE, &loading) && !loading)
887  break;
888  *path = tmp;
889  }
890  return type ? 's' : 'r';
891 }
892 
893 static void
895 {
896  rb_load_fail(fname, "cannot load such file");
897 }
898 
899 static VALUE
901 {
903  return (VALUE)dln_load(RSTRING_PTR(path));
904 }
905 
906 VALUE
907 rb_require_safe(VALUE fname, int safe)
908 {
909  volatile VALUE result = Qnil;
910  rb_thread_t *th = GET_THREAD();
911  volatile VALUE errinfo = th->errinfo;
912  int state;
913  struct {
914  int safe;
915  } volatile saved;
916  char *volatile ftptr = 0;
917 
920  rb_sourcefile(),
921  rb_sourceline());
922  }
923 
924  PUSH_TAG();
925  saved.safe = rb_safe_level();
926  if ((state = EXEC_TAG()) == 0) {
927  VALUE path;
928  long handle;
929  int found;
930 
932  FilePathValue(fname);
934 
937  rb_sourcefile(),
938  rb_sourceline());
939  }
940 
941  found = search_required(fname, &path, safe);
942 
945  rb_sourcefile(),
946  rb_sourceline());
947  }
948  if (found) {
949  if (!path || !(ftptr = load_lock(RSTRING_PTR(path)))) {
950  result = Qfalse;
951  }
952  else {
953  switch (found) {
954  case 'r':
955  rb_load_internal(path, 0);
956  break;
957 
958  case 's':
959  handle = (long)rb_vm_call_cfunc(rb_vm_top_self(), load_ext,
960  path, 0, path);
962  break;
963  }
964  rb_provide_feature(path);
965  result = Qtrue;
966  }
967  }
968  }
969  POP_TAG();
970  load_unlock(ftptr, !state);
971 
972  rb_set_safe_level_force(saved.safe);
973  if (state) {
974  JUMP_TAG(state);
975  }
976 
977  if (NIL_P(result)) {
978  load_failed(fname);
979  }
980 
981  th->errinfo = errinfo;
982 
985  rb_sourcefile(),
986  rb_sourceline());
987  }
988 
989  return result;
990 }
991 
992 VALUE
993 rb_require(const char *fname)
994 {
995  VALUE fn = rb_str_new2(fname);
996  OBJ_FREEZE(fn);
997  return rb_require_safe(fn, rb_safe_level());
998 }
999 
1000 static VALUE
1002 {
1004  (*(void (*)(void))arg)();
1005  return Qnil;
1006 }
1007 
1008 RUBY_FUNC_EXPORTED void
1009 ruby_init_ext(const char *name, void (*init)(void))
1010 {
1011  char* const lock_key = load_lock(name);
1012  if (lock_key) {
1014  0, rb_str_new2(name));
1015  rb_provide(name);
1016  load_unlock(lock_key, 1);
1017  }
1018 }
1019 
1020 /*
1021  * call-seq:
1022  * mod.autoload(module, filename) -> nil
1023  *
1024  * Registers _filename_ to be loaded (using <code>Kernel::require</code>)
1025  * the first time that _module_ (which may be a <code>String</code> or
1026  * a symbol) is accessed in the namespace of _mod_.
1027  *
1028  * module A
1029  * end
1030  * A.autoload(:B, "b")
1031  * A::B.doit # autoloads "b"
1032  */
1033 
1034 static VALUE
1036 {
1037  ID id = rb_to_id(sym);
1038 
1039  FilePathValue(file);
1040  rb_autoload(mod, id, RSTRING_PTR(file));
1041  return Qnil;
1042 }
1043 
1044 /*
1045  * call-seq:
1046  * mod.autoload?(name) -> String or nil
1047  *
1048  * Returns _filename_ to be loaded if _name_ is registered as
1049  * +autoload+ in the namespace of _mod_.
1050  *
1051  * module A
1052  * end
1053  * A.autoload(:B, "b")
1054  * A.autoload?(:B) #=> "b"
1055  */
1056 
1057 static VALUE
1059 {
1060  ID id = rb_check_id(&sym);
1061  if (!id) {
1062  return Qnil;
1063  }
1064  return rb_autoload_p(mod, id);
1065 }
1066 
1067 /*
1068  * call-seq:
1069  * autoload(module, filename) -> nil
1070  *
1071  * Registers _filename_ to be loaded (using <code>Kernel::require</code>)
1072  * the first time that _module_ (which may be a <code>String</code> or
1073  * a symbol) is accessed.
1074  *
1075  * autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
1076  */
1077 
1078 static VALUE
1080 {
1081  VALUE klass = rb_class_real(rb_vm_cbase());
1082  if (NIL_P(klass)) {
1083  rb_raise(rb_eTypeError, "Can not set autoload on singleton class");
1084  }
1085  return rb_mod_autoload(klass, sym, file);
1086 }
1087 
1088 /*
1089  * call-seq:
1090  * autoload?(name) -> String or nil
1091  *
1092  * Returns _filename_ to be loaded if _name_ is registered as
1093  * +autoload+.
1094  *
1095  * autoload(:B, "b")
1096  * autoload?(:B) #=> "b"
1097  */
1098 
1099 static VALUE
1101 {
1102  /* use rb_vm_cbase() as same as rb_f_autoload. */
1103  VALUE klass = rb_vm_cbase();
1104  if (NIL_P(klass)) {
1105  return Qnil;
1106  }
1107  return rb_mod_autoload_p(klass, sym);
1108 }
1109 
1110 void
1112 {
1113 #undef rb_intern
1114 #define rb_intern(str) rb_intern2((str), strlen(str))
1115  rb_vm_t *vm = GET_VM();
1116  static const char var_load_path[] = "$:";
1117  ID id_load_path = rb_intern2(var_load_path, sizeof(var_load_path)-1);
1118 
1120  rb_alias_variable(rb_intern("$-I"), id_load_path);
1121  rb_alias_variable(rb_intern("$LOAD_PATH"), id_load_path);
1122  vm->load_path = rb_ary_new();
1125  vm->load_path_check_cache = 0;
1126 
1128  rb_define_virtual_variable("$LOADED_FEATURES", get_loaded_features, 0);
1129  vm->loaded_features = rb_ary_new();
1132 
1133  rb_define_global_function("load", rb_f_load, -1);
1134  rb_define_global_function("require", rb_f_require, 1);
1135  rb_define_global_function("require_relative", rb_f_require_relative, 1);
1136  rb_define_method(rb_cModule, "autoload", rb_mod_autoload, 2);
1137  rb_define_method(rb_cModule, "autoload?", rb_mod_autoload_p, 1);
1138  rb_define_global_function("autoload", rb_f_autoload, 2);
1139  rb_define_global_function("autoload?", rb_f_autoload_p, 1);
1140 
1143 }
1144