Ruby  1.9.3p392(2013-02-22revision39386)
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 
12 
13 #define IS_RBEXT(e) (strcmp((e), ".rb") == 0)
14 #define IS_SOEXT(e) (strcmp((e), ".so") == 0 || strcmp((e), ".o") == 0)
15 #ifdef DLEXT2
16 #define IS_DLEXT(e) (strcmp((e), DLEXT) == 0 || strcmp((e), DLEXT2) == 0)
17 #else
18 #define IS_DLEXT(e) (strcmp((e), DLEXT) == 0)
19 #endif
20 
21 
22 static const char *const loadable_ext[] = {
23  ".rb", DLEXT,
24 #ifdef DLEXT2
25  DLEXT2,
26 #endif
27  0
28 };
29 
30 VALUE
32 {
33  VALUE load_path = GET_VM()->load_path;
34  return load_path;
35 }
36 
37 VALUE
39 {
40  VALUE load_path = rb_get_load_path();
41  VALUE ary;
42  long i;
43 
44  ary = rb_ary_new2(RARRAY_LEN(load_path));
45  for (i = 0; i < RARRAY_LEN(load_path); ++i) {
46  VALUE path = rb_file_expand_path_fast(RARRAY_PTR(load_path)[i], Qnil);
47  rb_str_freeze(path);
48  rb_ary_push(ary, path);
49  }
50  rb_obj_freeze(ary);
51  return ary;
52 }
53 
54 static VALUE
56 {
57  return vm->load_path;
58 }
59 
60 static VALUE
62 {
63  return GET_VM()->loaded_features;
64 }
65 
66 static st_table *
68 {
69  return GET_VM()->loading_table;
70 }
71 
72 static VALUE
73 loaded_feature_path(const char *name, long vlen, const char *feature, long len,
74  int type, VALUE load_path)
75 {
76  long i;
77  long plen;
78  const char *e;
79 
80  if(vlen < len) return 0;
81  if (!strncmp(name+(vlen-len),feature,len)){
82  plen = vlen - len - 1;
83  } else {
84  for (e = name + vlen; name != e && *e != '.' && *e != '/'; --e);
85  if (*e!='.' ||
86  e-name < len ||
87  strncmp(e-len,feature,len) )
88  return 0;
89  plen = e - name - len - 1;
90  }
91  for (i = 0; i < RARRAY_LEN(load_path); ++i) {
92  VALUE p = RARRAY_PTR(load_path)[i];
93  const char *s = StringValuePtr(p);
94  long n = RSTRING_LEN(p);
95 
96  if (n != plen ) continue;
97  if (n && (strncmp(name, s, n) || name[n] != '/')) continue;
98  switch (type) {
99  case 's':
100  if (IS_DLEXT(&name[n+len+1])) return p;
101  break;
102  case 'r':
103  if (IS_RBEXT(&name[n+len+1])) return p;
104  break;
105  default:
106  return p;
107  }
108  }
109  return 0;
110 }
111 
113  const char *name;
114  long len;
115  int type;
117  const char *result;
118 };
119 
120 static int
122 {
123  const char *s = (const char *)v;
124  struct loaded_feature_searching *fp = (struct loaded_feature_searching *)f;
125  VALUE p = loaded_feature_path(s, strlen(s), fp->name, fp->len,
126  fp->type, fp->load_path);
127  if (!p) return ST_CONTINUE;
128  fp->result = s;
129  return ST_STOP;
130 }
131 
132 static int
133 rb_feature_p(const char *feature, const char *ext, int rb, int expanded, const char **fn)
134 {
135  VALUE v, features, p, load_path = 0;
136  const char *f, *e;
137  long i, len, elen, n;
138  st_table *loading_tbl;
139  st_data_t data;
140  int type;
141 
142  if (fn) *fn = 0;
143  if (ext) {
144  elen = strlen(ext);
145  len = strlen(feature) - elen;
146  type = rb ? 'r' : 's';
147  }
148  else {
149  len = strlen(feature);
150  elen = 0;
151  type = 0;
152  }
153  features = get_loaded_features();
154  for (i = 0; i < RARRAY_LEN(features); ++i) {
155  v = RARRAY_PTR(features)[i];
156  f = StringValuePtr(v);
157  if ((n = RSTRING_LEN(v)) < len) continue;
158  if (strncmp(f, feature, len) != 0) {
159  if (expanded) continue;
160  if (!load_path) load_path = rb_get_expanded_load_path();
161  if (!(p = loaded_feature_path(f, n, feature, len, type, load_path)))
162  continue;
163  expanded = 1;
164  f += RSTRING_LEN(p) + 1;
165  }
166  if (!*(e = f + len)) {
167  if (ext) continue;
168  return 'u';
169  }
170  if (*e != '.') continue;
171  if ((!rb || !ext) && (IS_SOEXT(e) || IS_DLEXT(e))) {
172  return 's';
173  }
174  if ((rb || !ext) && (IS_RBEXT(e))) {
175  return 'r';
176  }
177  }
178  loading_tbl = get_loading_table();
179  if (loading_tbl) {
180  f = 0;
181  if (!expanded) {
182  struct loaded_feature_searching fs;
183  fs.name = feature;
184  fs.len = len;
185  fs.type = type;
186  fs.load_path = load_path ? load_path : rb_get_load_path();
187  fs.result = 0;
188  st_foreach(loading_tbl, loaded_feature_path_i, (st_data_t)&fs);
189  if ((f = fs.result) != 0) {
190  if (fn) *fn = f;
191  goto loading;
192  }
193  }
194  if (st_get_key(loading_tbl, (st_data_t)feature, &data)) {
195  if (fn) *fn = (const char*)data;
196  loading:
197  if (!ext) return 'u';
198  return !IS_RBEXT(ext) ? 's' : 'r';
199  }
200  else {
201  VALUE bufstr;
202  char *buf;
203 
204  if (ext && *ext) return 0;
205  bufstr = rb_str_tmp_new(len + DLEXT_MAXLEN);
206  buf = RSTRING_PTR(bufstr);
207  MEMCPY(buf, feature, char, len);
208  for (i = 0; (e = loadable_ext[i]) != 0; i++) {
209  strlcpy(buf + len, e, DLEXT_MAXLEN + 1);
210  if (st_get_key(loading_tbl, (st_data_t)buf, &data)) {
211  rb_str_resize(bufstr, 0);
212  if (fn) *fn = (const char*)data;
213  return i ? 's' : 'r';
214  }
215  }
216  rb_str_resize(bufstr, 0);
217  }
218  }
219  return 0;
220 }
221 
222 int
223 rb_provided(const char *feature)
224 {
225  return rb_feature_provided(feature, 0);
226 }
227 
228 int
229 rb_feature_provided(const char *feature, const char **loading)
230 {
231  const char *ext = strrchr(feature, '.');
232  volatile VALUE fullpath = 0;
233 
234  if (*feature == '.' &&
235  (feature[1] == '/' || strncmp(feature+1, "./", 2) == 0)) {
236  fullpath = rb_file_expand_path_fast(rb_str_new2(feature), Qnil);
237  feature = RSTRING_PTR(fullpath);
238  }
239  if (ext && !strchr(ext, '/')) {
240  if (IS_RBEXT(ext)) {
241  if (rb_feature_p(feature, ext, TRUE, FALSE, loading)) return TRUE;
242  return FALSE;
243  }
244  else if (IS_SOEXT(ext) || IS_DLEXT(ext)) {
245  if (rb_feature_p(feature, ext, FALSE, FALSE, loading)) return TRUE;
246  return FALSE;
247  }
248  }
249  if (rb_feature_p(feature, 0, TRUE, FALSE, loading))
250  return TRUE;
251  return FALSE;
252 }
253 
254 static void
256 {
259  "$LOADED_FEATURES is frozen; cannot append feature");
260  }
261  rb_ary_push(get_loaded_features(), feature);
262 }
263 
264 void
265 rb_provide(const char *feature)
266 {
268 }
269 
270 NORETURN(static void load_failed(VALUE));
271 
272 static void
273 rb_load_internal(VALUE fname, int wrap)
274 {
275  int state;
276  rb_thread_t *th = GET_THREAD();
277  volatile VALUE wrapper = th->top_wrapper;
278  volatile VALUE self = th->top_self;
279  volatile int loaded = FALSE;
280  volatile int mild_compile_error;
281 #ifndef __GNUC__
282  rb_thread_t *volatile th0 = th;
283 #endif
284 
285  th->errinfo = Qnil; /* ensure */
286 
287  if (!wrap) {
288  rb_secure(4); /* should alter global state */
289  th->top_wrapper = 0;
290  }
291  else {
292  /* load in anonymous module as toplevel */
294  th->top_wrapper = rb_module_new();
296  }
297 
298  mild_compile_error = th->mild_compile_error;
299  PUSH_TAG();
300  state = EXEC_TAG();
301  if (state == 0) {
302  NODE *node;
303  VALUE iseq;
304 
305  th->mild_compile_error++;
306  node = (NODE *)rb_load_file(RSTRING_PTR(fname));
307  loaded = TRUE;
308  iseq = rb_iseq_new_top(node, rb_str_new2("<top (required)>"), fname, rb_realpath_internal(Qnil, fname, 1), Qfalse);
309  th->mild_compile_error--;
310  rb_iseq_eval(iseq);
311  }
312  POP_TAG();
313 
314 #ifndef __GNUC__
315  th = th0;
316  fname = RB_GC_GUARD(fname);
317 #endif
318  th->mild_compile_error = mild_compile_error;
319  th->top_self = self;
320  th->top_wrapper = wrapper;
321 
322  if (!loaded && !FIXNUM_P(GET_THREAD()->errinfo)) {
323  /* an error on loading don't include INT2FIX(TAG_FATAL) see r35625 */
324  rb_exc_raise(GET_THREAD()->errinfo);
325  }
326  if (state) {
328  }
329 
330  if (!NIL_P(GET_THREAD()->errinfo)) {
331  /* exception during load */
332  rb_exc_raise(th->errinfo);
333  }
334 }
335 
336 void
337 rb_load(VALUE fname, int wrap)
338 {
339  VALUE tmp = rb_find_file(FilePathValue(fname));
340  if (!tmp) load_failed(fname);
341  rb_load_internal(tmp, wrap);
342 }
343 
344 void
345 rb_load_protect(VALUE fname, int wrap, int *state)
346 {
347  int status;
348 
349  PUSH_TAG();
350  if ((status = EXEC_TAG()) == 0) {
351  rb_load(fname, wrap);
352  }
353  POP_TAG();
354  if (state)
355  *state = status;
356 }
357 
358 /*
359  * call-seq:
360  * load(filename, wrap=false) -> true
361  *
362  * Loads and executes the Ruby
363  * program in the file _filename_. If the filename does not
364  * resolve to an absolute path, the file is searched for in the library
365  * directories listed in <code>$:</code>. If the optional _wrap_
366  * parameter is +true+, the loaded script will be executed
367  * under an anonymous module, protecting the calling program's global
368  * namespace. In no circumstance will any local variables in the loaded
369  * file be propagated to the loading environment.
370  */
371 
372 static VALUE
374 {
375  VALUE fname, wrap, path;
376 
377  rb_scan_args(argc, argv, "11", &fname, &wrap);
378  path = rb_find_file(FilePathValue(fname));
379  if (!path) {
380  if (!rb_file_load_ok(RSTRING_PTR(fname)))
381  load_failed(fname);
382  path = fname;
383  }
384  rb_load_internal(path, RTEST(wrap));
385  return Qtrue;
386 }
387 
388 static char *
389 load_lock(const char *ftptr)
390 {
391  st_data_t data;
392  st_table *loading_tbl = get_loading_table();
393 
394  if (!loading_tbl || !st_lookup(loading_tbl, (st_data_t)ftptr, &data)) {
395  /* loading ruby library should be serialized. */
396  if (!loading_tbl) {
397  GET_VM()->loading_table = loading_tbl = st_init_strtable();
398  }
399  /* partial state */
400  ftptr = ruby_strdup(ftptr);
401  data = (st_data_t)rb_barrier_new();
402  st_insert(loading_tbl, (st_data_t)ftptr, data);
403  return (char *)ftptr;
404  }
405  if (RTEST(ruby_verbose)) {
406  rb_warning("loading in progress, circular require considered harmful - %s", ftptr);
407  rb_backtrace();
408  }
409  return RTEST(rb_barrier_wait((VALUE)data)) ? (char *)ftptr : 0;
410 }
411 
412 static void
413 load_unlock(const char *ftptr, int done)
414 {
415  if (ftptr) {
416  st_data_t key = (st_data_t)ftptr;
417  st_data_t data;
418  st_table *loading_tbl = get_loading_table();
419 
420  if (st_delete(loading_tbl, &key, &data)) {
421  VALUE barrier = (VALUE)data;
422  xfree((char *)key);
423  if (done)
424  rb_barrier_destroy(barrier);
425  else
426  rb_barrier_release(barrier);
427  }
428  }
429 }
430 
431 
432 /*
433  * call-seq:
434  * require(name) -> true or false
435  *
436  * Loads the given +name+, returning +true+ if successful and +false+ if the
437  * feature is already loaded.
438  *
439  * If the filename does not resolve to an absolute path, it will be searched
440  * for in the directories listed in <code>$LOAD_PATH</code> (<code>$:</code>).
441  *
442  * If the filename has the extension ".rb", it is loaded as a source file; if
443  * the extension is ".so", ".o", or ".dll", or the default shared library
444  * extension on the current platform, Ruby loads the shared library as a
445  * Ruby extension. Otherwise, Ruby tries adding ".rb", ".so", and so on
446  * to the name until found. If the file named cannot be found, a LoadError
447  * will be raised.
448  *
449  * For Ruby extensions the filename given may use any shared library
450  * extension. For example, on Linux the socket extension is "socket.so" and
451  * <code>require 'socket.dll'</code> will load the socket extension.
452  *
453  * The absolute path of the loaded file is added to
454  * <code>$LOADED_FEATURES</code> (<code>$"</code>). A file will not be
455  * loaded again if its path already appears in <code>$"</code>. For example,
456  * <code>require 'a'; require './a'</code> will not load <code>a.rb</code>
457  * again.
458  *
459  * require "my-library.rb"
460  * require "db-driver"
461  */
462 
463 VALUE
465 {
466  return rb_require_safe(fname, rb_safe_level());
467 }
468 
469 /*
470  * call-seq:
471  * require_relative(string) -> true or false
472  *
473  * Ruby tries to load the library named _string_ relative to the requiring
474  * file's path. If the file's path cannot be determined a LoadError is raised.
475  * If a file is loaded +true+ is returned and false otherwise.
476  */
477 VALUE
479 {
481  if (NIL_P(base)) {
482  rb_raise(rb_eLoadError, "cannot infer basepath");
483  }
484  base = rb_file_dirname(base);
485  return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
486 }
487 
488 static int
489 search_required(VALUE fname, volatile VALUE *path, int safe_level)
490 {
491  VALUE tmp;
492  char *ext, *ftptr;
493  int type, ft = 0;
494  const char *loading;
495 
496  *path = 0;
497  ext = strrchr(ftptr = RSTRING_PTR(fname), '.');
498  if (ext && !strchr(ext, '/')) {
499  if (IS_RBEXT(ext)) {
500  if (rb_feature_p(ftptr, ext, TRUE, FALSE, &loading)) {
501  if (loading) *path = rb_filesystem_str_new_cstr(loading);
502  return 'r';
503  }
504  if ((tmp = rb_find_file_safe(fname, safe_level)) != 0) {
505  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
506  if (!rb_feature_p(ftptr, ext, TRUE, TRUE, &loading) || loading)
507  *path = tmp;
508  return 'r';
509  }
510  return 0;
511  }
512  else if (IS_SOEXT(ext)) {
513  if (rb_feature_p(ftptr, ext, FALSE, FALSE, &loading)) {
514  if (loading) *path = rb_filesystem_str_new_cstr(loading);
515  return 's';
516  }
517  tmp = rb_str_subseq(fname, 0, ext - RSTRING_PTR(fname));
518 #ifdef DLEXT2
519  OBJ_FREEZE(tmp);
520  if (rb_find_file_ext_safe(&tmp, loadable_ext + 1, safe_level)) {
521  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
522  if (!rb_feature_p(ftptr, ext, FALSE, TRUE, &loading) || loading)
523  *path = tmp;
524  return 's';
525  }
526 #else
527  rb_str_cat2(tmp, DLEXT);
528  OBJ_FREEZE(tmp);
529  if ((tmp = rb_find_file_safe(tmp, safe_level)) != 0) {
530  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
531  if (!rb_feature_p(ftptr, ext, FALSE, TRUE, &loading) || loading)
532  *path = tmp;
533  return 's';
534  }
535 #endif
536  }
537  else if (IS_DLEXT(ext)) {
538  if (rb_feature_p(ftptr, ext, FALSE, FALSE, &loading)) {
539  if (loading) *path = rb_filesystem_str_new_cstr(loading);
540  return 's';
541  }
542  if ((tmp = rb_find_file_safe(fname, safe_level)) != 0) {
543  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
544  if (!rb_feature_p(ftptr, ext, FALSE, TRUE, &loading) || loading)
545  *path = tmp;
546  return 's';
547  }
548  }
549  }
550  else if ((ft = rb_feature_p(ftptr, 0, FALSE, FALSE, &loading)) == 'r') {
551  if (loading) *path = rb_filesystem_str_new_cstr(loading);
552  return 'r';
553  }
554  tmp = fname;
555  type = rb_find_file_ext_safe(&tmp, loadable_ext, safe_level);
556  switch (type) {
557  case 0:
558  if (ft)
559  break;
560  ftptr = RSTRING_PTR(tmp);
561  return rb_feature_p(ftptr, 0, FALSE, TRUE, 0);
562 
563  default:
564  if (ft)
565  break;
566  case 1:
567  ext = strrchr(ftptr = RSTRING_PTR(tmp), '.');
568  if (rb_feature_p(ftptr, ext, !--type, TRUE, &loading) && !loading)
569  break;
570  *path = tmp;
571  }
572  return type ? 's' : 'r';
573 }
574 
575 static void
577 {
578  VALUE mesg = rb_str_buf_new_cstr("cannot load such file -- ");
579  rb_str_append(mesg, fname); /* should be ASCII compatible */
581 }
582 
583 static VALUE
585 {
587  return (VALUE)dln_load(RSTRING_PTR(path));
588 }
589 
590 VALUE
591 rb_require_safe(VALUE fname, int safe)
592 {
593  volatile VALUE result = Qnil;
594  rb_thread_t *th = GET_THREAD();
595  volatile VALUE errinfo = th->errinfo;
596  int state;
597  struct {
598  int safe;
599  } volatile saved;
600  char *volatile ftptr = 0;
601 
602  PUSH_TAG();
603  saved.safe = rb_safe_level();
604  if ((state = EXEC_TAG()) == 0) {
605  VALUE path;
606  long handle;
607  int found;
608 
610  FilePathValue(fname);
612  found = search_required(fname, &path, safe);
613  if (found) {
614  if (!path || !(ftptr = load_lock(RSTRING_PTR(path)))) {
615  result = Qfalse;
616  }
617  else {
618  switch (found) {
619  case 'r':
620  rb_load_internal(path, 0);
621  break;
622 
623  case 's':
625  path, 0, path);
627  break;
628  }
629  rb_provide_feature(path);
630  result = Qtrue;
631  }
632  }
633  }
634  POP_TAG();
635  load_unlock(ftptr, !state);
636 
637  rb_set_safe_level_force(saved.safe);
638  if (state) {
639  JUMP_TAG(state);
640  }
641 
642  if (NIL_P(result)) {
643  load_failed(fname);
644  }
645 
646  th->errinfo = errinfo;
647 
648  return result;
649 }
650 
651 VALUE
652 rb_require(const char *fname)
653 {
654  VALUE fn = rb_str_new2(fname);
655  OBJ_FREEZE(fn);
656  return rb_require_safe(fn, rb_safe_level());
657 }
658 
659 static VALUE
661 {
663  (*(void (*)(void))arg)();
664  return Qnil;
665 }
666 
668 ruby_init_ext(const char *name, void (*init)(void))
669 {
670  if (load_lock(name)) {
672  0, rb_str_new2(name));
673  rb_provide(name);
674  load_unlock(name, 1);
675  }
676 }
677 
678 /*
679  * call-seq:
680  * mod.autoload(module, filename) -> nil
681  *
682  * Registers _filename_ to be loaded (using <code>Kernel::require</code>)
683  * the first time that _module_ (which may be a <code>String</code> or
684  * a symbol) is accessed in the namespace of _mod_.
685  *
686  * module A
687  * end
688  * A.autoload(:B, "b")
689  * A::B.doit # autoloads "b"
690  */
691 
692 static VALUE
694 {
695  ID id = rb_to_id(sym);
696 
697  FilePathValue(file);
698  rb_autoload(mod, id, RSTRING_PTR(file));
699  return Qnil;
700 }
701 
702 /*
703  * call-seq:
704  * mod.autoload?(name) -> String or nil
705  *
706  * Returns _filename_ to be loaded if _name_ is registered as
707  * +autoload+ in the namespace of _mod_.
708  *
709  * module A
710  * end
711  * A.autoload(:B, "b")
712  * A.autoload?(:B) #=> "b"
713  */
714 
715 static VALUE
717 {
718  return rb_autoload_p(mod, rb_to_id(sym));
719 }
720 
721 /*
722  * call-seq:
723  * autoload(module, filename) -> nil
724  *
725  * Registers _filename_ to be loaded (using <code>Kernel::require</code>)
726  * the first time that _module_ (which may be a <code>String</code> or
727  * a symbol) is accessed.
728  *
729  * autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
730  */
731 
732 static VALUE
734 {
735  VALUE klass = rb_class_real(rb_vm_cbase());
736  if (NIL_P(klass)) {
737  rb_raise(rb_eTypeError, "Can not set autoload on singleton class");
738  }
739  return rb_mod_autoload(klass, sym, file);
740 }
741 
742 /*
743  * call-seq:
744  * autoload?(name) -> String or nil
745  *
746  * Returns _filename_ to be loaded if _name_ is registered as
747  * +autoload+.
748  *
749  * autoload(:B, "b")
750  * autoload?(:B) #=> "b"
751  */
752 
753 static VALUE
755 {
756  /* use rb_vm_cbase() as same as rb_f_autoload. */
757  VALUE klass = rb_vm_cbase();
758  if (NIL_P(klass)) {
759  return Qnil;
760  }
761  return rb_mod_autoload_p(klass, sym);
762 }
763 
764 void
766 {
767 #undef rb_intern
768 #define rb_intern(str) rb_intern2((str), strlen(str))
769  rb_vm_t *vm = GET_VM();
770  static const char var_load_path[] = "$:";
771  ID id_load_path = rb_intern2(var_load_path, sizeof(var_load_path)-1);
772 
774  rb_alias_variable(rb_intern("$-I"), id_load_path);
775  rb_alias_variable(rb_intern("$LOAD_PATH"), id_load_path);
776  vm->load_path = rb_ary_new();
777 
779  rb_define_virtual_variable("$LOADED_FEATURES", get_loaded_features, 0);
780  vm->loaded_features = rb_ary_new();
781 
784  rb_define_global_function("require_relative", rb_f_require_relative, 1);
789 
792 }
793