Ruby 4.1.0dev (2026-11-19 revision 1e71e987c206d5d77bf37e883aaa6262747b2458)
load.c (1e71e987c206d5d77bf37e883aaa6262747b2458)
1/*
2 * load methods from eval.c
3 */
4
5#include "dln.h"
6#include "eval_intern.h"
7#include "internal.h"
8#include "internal/box.h"
9#include "internal/dir.h"
10#include "internal/error.h"
11#include "internal/eval.h"
12#include "internal/file.h"
13#include "internal/hash.h"
14#include "internal/load.h"
15#include "internal/ruby_parser.h"
16#include "internal/thread.h"
17#include "internal/variable.h"
18#include "iseq.h"
19#include "prism_compile.h"
20#include "probes.h"
21#include "darray.h"
22#include "ruby/encoding.h"
23#include "ruby/util.h"
24#include "ractor_core.h"
25#include "vm_core.h"
26#include "vm_sync.h"
27
28#define IS_RBEXT(e) (strcmp((e), ".rb") == 0)
29#define IS_SOEXT(e) (strcmp((e), ".so") == 0 || strcmp((e), ".o") == 0)
30#define IS_DLEXT(e) (strcmp((e), DLEXT) == 0)
31
32enum {
33 loadable_ext_rb = (0+ /* .rb extension is the first in both tables */
34 1) /* offset by rb_find_file_ext() */
35};
36
37static const char *const loadable_ext[] = {
38 ".rb", DLEXT,
39 0
40};
41
42static const char *const ruby_ext[] = {
43 ".rb",
44 0
45};
46
47enum expand_type {
48 EXPAND_ALL,
49 EXPAND_RELATIVE,
50 EXPAND_HOME,
51 EXPAND_NON_CACHE
52};
53
54/* Bracket a rebuild that cannot run under the VM lock because it calls Ruby code
55 * or blocks on the filesystem. rb_feature_provided_ractor_safe() reads the depth
56 * under the lock and declines to answer while it is non-zero, which both keeps it
57 * out of a half-rebuilt index and pairs the lock release here with its acquire. */
58static void
59load_unstable_begin(const rb_box_t *box)
60{
61 RB_VM_LOCKING() {
62 ((rb_box_t *)box)->load_unstable_depth++;
63 }
64}
65
66static VALUE
67load_unstable_end(VALUE boxp)
68{
69 const rb_box_t *box = (const rb_box_t *)boxp;
70
71 RB_VM_LOCKING() {
72 RUBY_ASSERT(box->load_unstable_depth > 0);
73 ((rb_box_t *)box)->load_unstable_depth--;
74 }
75 return Qnil;
76}
77
78/* Construct expanded load path and store it to cache.
79 We rebuild load path partially if the cache is invalid.
80 We don't cache non string object and expand it every time. We ensure that
81 string objects in $LOAD_PATH are frozen.
82 */
83static void
84rb_construct_expanded_load_path(rb_box_t *box, enum expand_type type, int *has_relative, int *has_non_cache, rb_len_t *maxlen_out)
85{
86 VALUE load_path = box->load_path;
87 VALUE expanded_load_path = box->expanded_load_path;
88 VALUE snapshot;
89 VALUE ary;
90 rb_len_t i, maxlen = 0;
91
92 VM_ASSERT(box->load_unstable_depth > 0); // technically a race but benign
93
94 ary = rb_ary_hidden_new(RARRAY_LEN(load_path));
95 for (i = 0; i < RARRAY_LEN(load_path); ++i) {
96 VALUE path, as_str, expanded_path;
97 int is_string, non_cache;
98 char *as_cstr;
99 as_str = path = RARRAY_AREF(load_path, i);
100 is_string = RB_TYPE_P(path, T_STRING) ? 1 : 0;
101 non_cache = !is_string ? 1 : 0;
102 as_str = rb_get_path_check_to_string(path);
103 as_cstr = RSTRING_PTR(as_str);
104
105 if (!non_cache) {
106 if ((type == EXPAND_RELATIVE &&
107 rb_is_absolute_path(as_cstr)) ||
108 (type == EXPAND_HOME &&
109 (!as_cstr[0] || as_cstr[0] != '~')) ||
110 (type == EXPAND_NON_CACHE)) {
111 /* Use cached expanded path. */
112 expanded_path = RARRAY_AREF(expanded_load_path, i);
113 rb_len_t len = RSTRING_LEN(expanded_path);
114 if (len > maxlen) maxlen = len;
115 rb_ary_push(ary, expanded_path);
116 continue;
117 }
118 }
119 if (!*has_relative && !rb_is_absolute_path(as_cstr))
120 *has_relative = 1;
121 if (!*has_non_cache && non_cache)
122 *has_non_cache = 1;
123 /* Freeze only string object. We expand other objects every time. */
124 if (is_string)
125 rb_str_freeze(path);
126 as_str = rb_get_path_check_convert(as_str);
127 expanded_path = rb_check_realpath(Qnil, as_str, NULL);
128 if (NIL_P(expanded_path)) expanded_path = as_str;
129 rb_len_t len = RSTRING_LEN(expanded_path);
130 if (len > maxlen) maxlen = len;
131 rb_ary_push(ary, rb_fstring(expanded_path));
132 }
133 rb_ary_freeze(ary);
134 box->expanded_load_path = ary;
135 snapshot = box->load_path_snapshot;
136 load_path = box->load_path;
137 *maxlen_out = maxlen;
138 rb_ary_replace(snapshot, load_path);
139}
140
141static bool
142expanded_load_path_current_p(const rb_box_t *box)
143{
144 return RTEST(rb_ary_shared_with_p(box->load_path_snapshot, box->load_path)) &&
145 box->load_path_check_cache == 0;
146}
147
148static VALUE
149rebuild_expanded_load_path(VALUE boxp)
150{
151 rb_box_t *box = (rb_box_t *)boxp;
152 VALUE check_cache;
153 const VALUE non_cache = Qtrue;
154 const VALUE load_path_snapshot = box->load_path_snapshot;
155 const VALUE load_path = box->load_path;
156 rb_len_t maxlen = 0;
157
158 if (!rb_ary_shared_with_p(load_path_snapshot, load_path)) {
159 /* The load path was modified. Rebuild the expanded load path. */
160 int has_relative = 0, has_non_cache = 0;
161 rb_construct_expanded_load_path(box, EXPAND_ALL, &has_relative, &has_non_cache, &maxlen);
162 if (has_relative) {
163 box->load_path_check_cache = rb_dir_getwd_ospath();
164 }
165 else if (has_non_cache) {
166 /* Non string object. */
167 box->load_path_check_cache = non_cache;
168 }
169 else {
170 box->load_path_check_cache = 0;
171 }
172 }
173 else if ((check_cache = box->load_path_check_cache) == non_cache) {
174 int has_relative = 1, has_non_cache = 1;
175 /* Expand only non-cacheable objects. */
176 rb_construct_expanded_load_path(box, EXPAND_NON_CACHE,
177 &has_relative, &has_non_cache, &maxlen);
178 }
179 else if (check_cache) {
180 int has_relative = 1, has_non_cache = 1;
181 VALUE cwd = rb_dir_getwd_ospath();
182 if (!rb_str_equal(check_cache, cwd)) {
183 /* Current working directory or filesystem encoding was changed.
184 Expand relative load path and non-cacheable objects again. */
185 box->load_path_check_cache = cwd;
186 rb_construct_expanded_load_path(box, EXPAND_RELATIVE,
187 &has_relative, &has_non_cache, &maxlen);
188 }
189 else {
190 /* Expand only tilde (User HOME) and non-cacheable objects. */
191 rb_construct_expanded_load_path(box, EXPAND_HOME,
192 &has_relative, &has_non_cache, &maxlen);
193 }
194 }
195 if (maxlen) {
196 box->expanded_load_path_maxlen = maxlen;
197 }
198 return Qnil;
199}
200
201static VALUE
202get_expanded_load_path(rb_box_t *box)
203{
204 if (!expanded_load_path_current_p(box)) {
205 load_unstable_begin(box);
206 rb_ensure(rebuild_expanded_load_path, (VALUE)box, load_unstable_end, (VALUE)box);
207 }
208 return box->expanded_load_path;
209}
210
211VALUE
212rb_get_expanded_load_path(rb_len_t *maxlen)
213{
214 rb_box_t *box = (rb_box_t *)rb_loading_box();
215 VALUE load_path = get_expanded_load_path((rb_box_t *)box);
216 if (maxlen) {
217 *maxlen = box->expanded_load_path_maxlen;
218 }
219 return load_path;
220}
221
222static VALUE
223load_path_getter(ID _x, VALUE * _y)
224{
225 return rb_loading_box()->load_path;
226}
227
228static VALUE
229get_LOADED_FEATURES(ID _x, VALUE *_y)
230{
231 return rb_loading_box()->loaded_features;
232}
233
234static void
235reset_loaded_features_snapshot(const rb_box_t *box)
236{
237 VALUE snapshot = box->loaded_features_snapshot;
238 VALUE loaded_features = box->loaded_features;
239 rb_ary_replace(snapshot, loaded_features);
240}
241
242static struct st_table *
243get_loaded_features_index_raw(const rb_box_t *box)
244{
245 return box->loaded_features_index;
246}
247
248static st_data_t
249feature_key(const char *str, size_t len)
250{
251 return st_hash(str, len, 0xfea7009e);
252}
253
254static bool
255is_rbext_path(VALUE feature_path)
256{
257 rb_len_t len = RSTRING_LEN(feature_path);
258 rb_len_t rbext_len = rb_strlen_lit(".rb");
259 if (len <= rbext_len) return false;
260 return IS_RBEXT(RSTRING_PTR(feature_path) + len - rbext_len);
261}
262
263typedef rb_darray(long) feature_indexes_t;
264
265struct features_index_add_single_args {
266 const rb_box_t *box;
267 VALUE offset;
268 bool rb;
269};
270
271static int
272features_index_add_single_callback(st_data_t *key, st_data_t *value, st_data_t raw_args, int existing)
273{
274 struct features_index_add_single_args *args = (struct features_index_add_single_args *)raw_args;
275 const rb_box_t *box = args->box;
276 VALUE offset = args->offset;
277 bool rb = args->rb;
278
279 if (existing) {
280 VALUE this_feature_index = *value;
281
282 if (FIXNUM_P(this_feature_index)) {
283 VALUE loaded_features = box->loaded_features;
284 VALUE this_feature_path = RARRAY_AREF(loaded_features, FIX2LONG(this_feature_index));
285
286 feature_indexes_t feature_indexes;
287 rb_darray_make(&feature_indexes, 2);
288 int top = (rb && !is_rbext_path(this_feature_path)) ? 1 : 0;
289 rb_darray_set(feature_indexes, top^0, FIX2LONG(this_feature_index));
290 rb_darray_set(feature_indexes, top^1, FIX2LONG(offset));
291
292 RUBY_ASSERT(rb_darray_size(feature_indexes) == 2);
293 // assert feature_indexes does not look like a special const
294 RUBY_ASSERT(!SPECIAL_CONST_P((VALUE)feature_indexes));
295
296 *value = (st_data_t)feature_indexes;
297 }
298 else {
299 feature_indexes_t feature_indexes = (feature_indexes_t)this_feature_index;
300 long pos = -1;
301
302 if (rb) {
303 VALUE loaded_features = box->loaded_features;
304 for (size_t i = 0; i < rb_darray_size(feature_indexes); ++i) {
305 long idx = rb_darray_get(feature_indexes, i);
306 VALUE this_feature_path = RARRAY_AREF(loaded_features, idx);
307 Check_Type(this_feature_path, T_STRING);
308 if (!is_rbext_path(this_feature_path)) {
309 pos = i;
310 break;
311 }
312 }
313 }
314
315 rb_darray_append(&feature_indexes, FIX2LONG(offset));
316 /* darray may realloc which will change the pointer */
317 *value = (st_data_t)feature_indexes;
318
319 if (pos >= 0) {
320 long *ptr = rb_darray_data_ptr(feature_indexes);
321 long len = rb_darray_size(feature_indexes);
322 MEMMOVE(ptr + pos + 1, ptr + pos, long, len - pos - 1);
323 ptr[pos] = FIX2LONG(offset);
324 }
325 }
326 }
327 else {
328 *value = offset;
329 }
330
331 return ST_CONTINUE;
332}
333
334static void
335features_index_add_single(const rb_box_t *box, const char* str, size_t len, VALUE offset, bool rb)
336{
337 struct st_table *features_index;
338 st_data_t short_feature_key;
339
340 Check_Type(offset, T_FIXNUM);
341 short_feature_key = feature_key(str, len);
342
343 features_index = get_loaded_features_index_raw(box);
344
345 struct features_index_add_single_args args = {
346 .box = box,
347 .offset = offset,
348 .rb = rb,
349 };
350
351 st_update(features_index, short_feature_key, features_index_add_single_callback, (st_data_t)&args);
352}
353
354/* Add to the loaded-features index all the required entries for
355 `feature`, located at `offset` in $LOADED_FEATURES. We add an
356 index entry at each string `short_feature` for which
357 feature == "#{prefix}#{short_feature}#{ext}"
358 where `ext` is empty or matches %r{^\.[^./]*$}, and `prefix` is empty
359 or ends in '/'. This maintains the invariant that `rb_feature_p()`
360 relies on for its fast lookup.
361*/
362static void
363features_index_add(const rb_box_t *box, VALUE feature, VALUE offset)
364{
365 RUBY_ASSERT(rb_ractor_main_p());
366
367 const char *feature_str, *feature_end, *ext, *p;
368 bool rb = false;
369
370 feature_str = StringValuePtr(feature);
371 feature_end = feature_str + RSTRING_LEN(feature);
372
373 for (ext = feature_end; ext > feature_str; ext--)
374 if (*ext == '.' || *ext == '/')
375 break;
376 if (*ext != '.')
377 ext = NULL;
378 else
379 rb = IS_RBEXT(ext);
380 /* Now `ext` points to the only string matching %r{^\.[^./]*$} that is
381 at the end of `feature`, or is NULL if there is no such string. */
382
383 p = ext ? ext : feature_end;
384 while (1) {
385 p--;
386 while (p >= feature_str && *p != '/')
387 p--;
388 if (p < feature_str)
389 break;
390 /* Now *p == '/'. We reach this point for every '/' in `feature`. */
391 features_index_add_single(box, p + 1, feature_end - p - 1, offset, false);
392 if (ext) {
393 features_index_add_single(box, p + 1, ext - p - 1, offset, rb);
394 }
395 }
396 features_index_add_single(box, feature_str, feature_end - feature_str, offset, false);
397 if (ext) {
398 features_index_add_single(box, feature_str, ext - feature_str, offset, rb);
399 }
400}
401
402static int
403loaded_features_index_clear_i(st_data_t key, st_data_t val, st_data_t arg)
404{
405 VALUE obj = (VALUE)val;
406 if (!SPECIAL_CONST_P(obj)) {
407 rb_darray_free_sized((void *)obj, long);
408 }
409 return ST_DELETE;
410}
411
412static VALUE
413rebuild_loaded_features_index(VALUE boxp)
414{
415 const rb_box_t *box = (const rb_box_t *)boxp;
416 int i;
417 VALUE features = box->loaded_features;
418
419 st_foreach(box->loaded_features_index, loaded_features_index_clear_i, 0);
420
421 VALUE realpaths = box->loaded_features_realpaths;
422 VALUE realpath_map = box->loaded_features_realpath_map;
423 VALUE previous_realpath_map = rb_hash_dup(realpath_map);
424 rb_hash_clear(realpaths);
425 rb_hash_clear(realpath_map);
426
427 /* We have to make a copy of features here because the StringValue call
428 * below could call a Ruby method, which could modify $LOADED_FEATURES
429 * and cause it to be corrupt. */
430 features = rb_ary_resurrect(features);
431 for (i = 0; i < RARRAY_LEN(features); i++) {
432 VALUE entry, as_str;
433 as_str = entry = rb_ary_entry(features, i);
434 StringValue(as_str);
435 as_str = rb_fstring(as_str);
436 if (as_str != entry)
437 rb_ary_store(features, i, as_str);
438 features_index_add(box, as_str, INT2FIX(i));
439 }
440 /* The user modified $LOADED_FEATURES, so we should restore the changes. */
441 if (!OBJ_FROZEN(box->loaded_features) &&
442 !rb_ary_shared_with_p(features, box->loaded_features)) {
443 rb_ary_replace(box->loaded_features, features);
444 }
445 reset_loaded_features_snapshot(box);
446
447 features = box->loaded_features_snapshot;
448 rb_len_t j = RARRAY_LEN(features);
449 for (i = 0; i < j; i++) {
450 VALUE as_str = rb_ary_entry(features, i);
451 VALUE realpath = rb_hash_aref(previous_realpath_map, as_str);
452 if (NIL_P(realpath)) {
453 realpath = rb_check_realpath(Qnil, as_str, NULL);
454 if (NIL_P(realpath)) realpath = as_str;
455 realpath = rb_fstring(realpath);
456 }
457 rb_hash_aset(realpaths, realpath, Qtrue);
458 rb_hash_aset(realpath_map, as_str, realpath);
459 }
460 return Qnil;
461}
462
463static st_table *
464get_loaded_features_index(const rb_box_t *box)
465{
466 if (!rb_ary_shared_with_p(box->loaded_features_snapshot, box->loaded_features)) {
467 /* The sharing was broken; something (other than us in rb_provide_feature())
468 modified loaded_features. Rebuild the index. */
469 load_unstable_begin(box);
470 rb_ensure(rebuild_loaded_features_index, (VALUE)box, load_unstable_end, (VALUE)box);
471 }
472 return box->loaded_features_index;
473}
474
475/* This searches `load_path` for a value such that
476 name == "#{load_path[i]}/#{feature}"
477 if `feature` is a suffix of `name`, or otherwise
478 name == "#{load_path[i]}/#{feature}#{ext}"
479 for an acceptable string `ext`. It returns
480 `load_path[i].to_str` if found, else 0.
481
482 If type is 's', then `ext` is acceptable only if IS_DLEXT(ext);
483 if 'r', then only if IS_RBEXT(ext); otherwise `ext` may be absent
484 or have any value matching `%r{^\.[^./]*$}`.
485*/
486static VALUE
487loaded_feature_path(const char *name, rb_len_t vlen, const char *feature, rb_len_t len,
488 int type, VALUE load_path)
489{
490 rb_len_t i;
491 rb_len_t plen;
492 const char *e;
493
494 if (vlen < len+1) return 0;
495 if (strchr(feature, '.') && !strncmp(name+(vlen-len), feature, len)) {
496 plen = vlen - len;
497 }
498 else {
499 for (e = name + vlen; name != e && *e != '.' && *e != '/'; --e);
500 if (*e != '.' ||
501 e-name < len ||
502 strncmp(e-len, feature, len))
503 return 0;
504 plen = e - name - len;
505 }
506 if (plen > 0 && name[plen-1] != '/') {
507 return 0;
508 }
509 if (type == 's' ? !IS_DLEXT(&name[plen+len]) :
510 type == 'r' ? !IS_RBEXT(&name[plen+len]) :
511 0) {
512 return 0;
513 }
514 /* Now name == "#{prefix}/#{feature}#{ext}" where ext is acceptable
515 (possibly empty) and prefix is some string of length plen. */
516
517 if (plen > 0) --plen; /* exclude '.' */
518 for (i = 0; i < RARRAY_LEN(load_path); ++i) {
519 VALUE p = RARRAY_AREF(load_path, i);
520 const char *s = StringValuePtr(p);
521 rb_len_t n = RSTRING_LEN(p);
522
523 if (n != plen) continue;
524 if (n && strncmp(name, s, n)) continue;
525 return p;
526 }
527 return 0;
528}
529
531 const char *name;
532 rb_len_t len;
533 int type;
534 VALUE load_path;
535 const char *result;
536};
537
538static int
539loaded_feature_path_i(st_data_t v, st_data_t b, st_data_t f)
540{
541 const char *s = (const char *)v;
542 struct loaded_feature_searching *fp = (struct loaded_feature_searching *)f;
543 VALUE p = loaded_feature_path(s, strlen(s), fp->name, fp->len,
544 fp->type, fp->load_path);
545 if (!p) return ST_CONTINUE;
546 fp->result = s;
547 return ST_STOP;
548}
549
551 const rb_box_t *box;
552 st_table *features_index;
553 VALUE features;
554 VALUE load_path; /* 0 to expand $LOAD_PATH on demand, or to decline if no_dispatch */
555 const char *feature;
556 const char *ext;
557 rb_len_t len;
558 int type;
559 int rb;
560 int expanded;
561 bool no_dispatch; /* stop rather than run Ruby code */
562};
563
564/* We search `features` for an entry such that either
565 "#{features[i]}" == "#{load_path[j]}/#{feature}#{e}"
566 for some j, or
567 "#{features[i]}" == "#{feature}#{e}"
568 Here `e` is an "allowed" extension -- either empty or one
569 of the extensions accepted by IS_RBEXT, IS_SOEXT, or
570 IS_DLEXT. Further, if `ext && rb` then `IS_RBEXT(e)`,
571 and if `ext && !rb` then `IS_SOEXT(e) || IS_DLEXT(e)`.
572
573 If `expanded`, then only the latter form (without load_path[j])
574 is accepted. Otherwise either form is accepted, *unless* `ext`
575 is false and an otherwise-matching entry of the first form is
576 preceded by an entry of the form
577 "#{features[i2]}" == "#{load_path[j2]}/#{feature}#{e2}"
578 where `e2` matches %r{^\.[^./]*$} but is not an allowed extension.
579 After a "distractor" entry of this form, only entries of the
580 form "#{feature}#{e}" are accepted.
581
582 In `rb_provide_feature()` and `get_loaded_features_index()` we
583 maintain an invariant that the array `this_feature_index` will
584 point to every entry in `features` which has the form
585 "#{prefix}#{feature}#{e}"
586 where `e` is empty or matches %r{^\.[^./]*$}, and `prefix` is empty
587 or ends in '/'. This includes both match forms above, as well
588 as any distractors, so we may ignore all other entries in `features`.
589
590 Returns the type of the first entry that matches -- 'u', 's' or 'r', as
591 documented on rb_feature_p() -- or 0 if none does, or -1 if `no_dispatch`
592 stopped the search. `expanded` and `load_path` are in/out: the caller sees
593 whatever the search expanded.
594 */
595static int
596features_index_match(struct features_index_search *search)
597{
598 const char *const feature = search->feature;
599 const rb_len_t len = search->len;
600 VALUE this_feature_index;
601 st_data_t data;
602
603 if (!st_lookup(search->features_index, feature_key(feature, strlen(feature)), &data)) return 0;
604 if (NIL_P(this_feature_index = (VALUE)data)) return 0;
605
606 for (size_t i = 0; ; i++) {
607 long index;
608 VALUE v, p;
609 const char *f, *e;
610 rb_len_t n;
611
612 if (FIXNUM_P(this_feature_index)) {
613 if (i > 0) break;
614 index = FIX2LONG(this_feature_index);
615 }
616 else {
617 feature_indexes_t feature_indexes = (feature_indexes_t)this_feature_index;
618 if (i >= rb_darray_size(feature_indexes)) break;
619 index = rb_darray_get(feature_indexes, i);
620 }
621
622 if (index >= RARRAY_LEN(search->features)) continue;
623 v = RARRAY_AREF(search->features, index);
624 if (search->no_dispatch) {
625 /* StringValue() here could dispatch to_str. */
626 if (!RB_TYPE_P(v, T_STRING)) return -1;
627 f = RSTRING_PTR(v);
628 }
629 else {
630 f = StringValuePtr(v);
631 }
632 if ((n = RSTRING_LEN(v)) < len) continue;
633 if (strncmp(f, feature, len) != 0) {
634 if (search->expanded) continue;
635 if (!search->load_path) {
636 /* Expanding dispatches to_path and hits the filesystem. */
637 if (search->no_dispatch) return -1;
638 search->load_path = get_expanded_load_path((rb_box_t *)search->box);
639 }
640 if (!(p = loaded_feature_path(f, n, feature, len, search->type, search->load_path)))
641 continue;
642 search->expanded = 1;
643 f += RSTRING_LEN(p) + 1;
644 }
645 if (!*(e = f + len)) {
646 if (search->ext) continue;
647 return 'u';
648 }
649 if (*e != '.') continue;
650 if ((!search->rb || !search->ext) && (IS_SOEXT(e) || IS_DLEXT(e))) {
651 return 's';
652 }
653 if ((search->rb || !search->ext) && (IS_RBEXT(e))) {
654 return 'r';
655 }
656 }
657
658 return 0;
659}
660
661/*
662 * Returns the type of already provided feature.
663 * 'r': ruby script (".rb")
664 * 's': shared object (".so"/"."DLEXT)
665 * 'u': unsuffixed
666 */
667static int
668rb_feature_p(const rb_box_t *box, const char *feature, const char *ext, int rb, int expanded, const char **fn)
669{
670 const char *f, *e;
671 rb_len_t i, len;
672 st_table *loading_tbl;
673 st_data_t data;
674 int type, found;
675
676 if (fn) *fn = 0;
677 if (ext) {
678 len = strlen(feature) - strlen(ext);
679 type = rb ? 'r' : 's';
680 }
681 else {
682 len = strlen(feature);
683 type = 0;
684 }
685
686 VALUE features = box->loaded_features;
687 st_table *features_index = get_loaded_features_index(box);
688 struct features_index_search search = {
689 .box = box,
690 .features_index = features_index,
691 .features = features,
692 .load_path = 0,
693 .feature = feature,
694 .ext = ext,
695 .len = len,
696 .type = type,
697 .rb = rb,
698 .expanded = expanded,
699 .no_dispatch = false,
700 };
701 if ((found = features_index_match(&search)) != 0) return found;
702
703 loading_tbl = box->loading_table;
704 f = 0;
705 if (!search.expanded && !rb_is_absolute_path(feature)) {
706 struct loaded_feature_searching fs;
707 fs.name = feature;
708 fs.len = len;
709 fs.type = type;
710 fs.load_path = search.load_path ? search.load_path : get_expanded_load_path((rb_box_t *)box);
711 fs.result = 0;
712 st_foreach(loading_tbl, loaded_feature_path_i, (st_data_t)&fs);
713 if ((f = fs.result) != 0) {
714 if (fn) *fn = f;
715 goto loading;
716 }
717 }
718 if (st_get_key(loading_tbl, (st_data_t)feature, &data)) {
719 if (fn) *fn = (const char*)data;
720 goto loading;
721 }
722 else {
723 VALUE bufstr;
724 char *buf;
725 static const char so_ext[][4] = {
726 ".so", ".o",
727 };
728
729 if (ext && *ext) return 0;
730 bufstr = rb_str_tmp_new(len + DLEXT_MAXLEN);
731 buf = RSTRING_PTR(bufstr);
732 MEMCPY(buf, feature, char, len);
733 for (i = 0; (e = loadable_ext[i]) != 0; i++) {
734 strlcpy(buf + len, e, DLEXT_MAXLEN + 1);
735 if (st_get_key(loading_tbl, (st_data_t)buf, &data)) {
736 rb_str_resize(bufstr, 0);
737 if (fn) *fn = (const char*)data;
738 return i ? 's' : 'r';
739 }
740 }
741 for (i = 0; i < numberof(so_ext); i++) {
742 strlcpy(buf + len, so_ext[i], DLEXT_MAXLEN + 1);
743 if (st_get_key(loading_tbl, (st_data_t)buf, &data)) {
744 rb_str_resize(bufstr, 0);
745 if (fn) *fn = (const char*)data;
746 return 's';
747 }
748 }
749 rb_str_resize(bufstr, 0);
750 }
751 return 0;
752
753 loading:
754 if (!ext) return 'u';
755 return !IS_RBEXT(ext) ? 's' : 'r';
756}
757
758int
759rb_provided(const char *feature)
760{
761 return rb_feature_provided(feature, 0);
762}
763
764static int
765feature_provided(rb_box_t *box, const char *feature, const char **loading)
766{
767 const char *ext = strrchr(feature, '.');
768 VALUE fullpath = 0;
769
770 if (*feature == '.' &&
771 (feature[1] == '/' || strncmp(feature+1, "./", 2) == 0)) {
772 fullpath = rb_file_expand_path_fast(rb_get_path(rb_str_new2(feature)), Qnil);
773 feature = RSTRING_PTR(fullpath);
774 }
775 if (ext && !strchr(ext, '/')) {
776 if (IS_RBEXT(ext)) {
777 if (rb_feature_p(box, feature, ext, TRUE, FALSE, loading)) return TRUE;
778 return FALSE;
779 }
780 else if (IS_SOEXT(ext) || IS_DLEXT(ext)) {
781 if (rb_feature_p(box, feature, ext, FALSE, FALSE, loading)) return TRUE;
782 return FALSE;
783 }
784 }
785 if (rb_feature_p(box, feature, 0, TRUE, FALSE, loading))
786 return TRUE;
787 RB_GC_GUARD(fullpath);
788 return FALSE;
789}
790
791int
792rb_feature_provided(const char *feature, const char **loading)
793{
794 rb_box_t *box = (rb_box_t *)rb_current_box();
795 return feature_provided(box, feature, loading);
796}
797
798/* Read-only fast path for a non-main Ractor `require`. True only if the feature is
799 * already loaded and that could be established from this Ractor. false means hand the
800 * require to the main Ractor as usual. The two reasons for false -- known not loaded
801 * and cannot tell -- are deliberately not distinguished. Loading happens on the main
802 * Ractor either way.
803 *
804 * It walks loaded_features_snapshot, not loaded_features. The latter is
805 * $LOADED_FEATURES, which main-Ractor Ruby code can mutate at any time with no lock.
806 */
807static bool
808feature_p_ractor_safe(const rb_box_t *box, VALUE features, VALUE load_path,
809 const char *feature, const char *ext, int rb)
810{
811 ASSERT_vm_locking();
812 struct features_index_search search = {
813 .box = box,
814 .features_index = get_loaded_features_index_raw(box),
815 .features = features,
816 .load_path = load_path,
817 .feature = feature,
818 .ext = ext,
819 .len = ext ? strlen(feature) - strlen(ext) : strlen(feature),
820 .type = ext ? (rb ? 'r' : 's') : 0,
821 .rb = rb,
822 .expanded = 0,
823 .no_dispatch = true,
824 };
825
826 switch (features_index_match(&search)) {
827 case 'r':
828 return true;
829 case 's':
830 /* With a requested extension, search_required() stops at any match. With
831 * none it stops only at an .rb one and otherwise retries through
832 * rb_find_file_ext(), which can still load a shadowing .rb -- as it does
833 * for Init_pathname()'s rb_provide("pathname.so") plus lib/pathname.rb.
834 * Decline those rather than reporting the feature as loaded. */
835 return ext != NULL;
836 case 'u':
837 case 0:
838 default:
839 return false;
840 }
841}
842
843/* See feature_p_ractor_safe() for the contract and what makes this safe. */
844bool
845rb_feature_provided_ractor_safe(VALUE fname)
846{
847 const rb_box_t *box = rb_current_box();
848
849 // The hand-off runs on a fresh main-Ractor thread, so require_internal() there
850 // resolves rb_loading_box() to the main box, not to this one.
851 // TODO: figure out box cross-ractor box require
852 if (rb_box_available() && box != rb_main_box()) return false;
853
854 /* require_internal() converts before search_required(), and it is the converted
855 * name that lands in $LOADED_FEATURES, so compare against that. Convert here
856 * rather than under the VM lock below: loading a transcoder would require(). */
857 fname = rb_str_encode_ospath(fname);
858
859 const char *feature = RSTRING_PTR(fname);
860 rb_len_t flen = RSTRING_LEN(fname);
861 const char *ext;
862 bool provided = false;
863
864 if (flen == 0 || strlen(feature) != (size_t)flen) return false;
865 if (feature[0] == '.' &&
866 (feature[1] == '/' || strncmp(feature + 1, "./", 2) == 0)) {
867 /* search_required() resolves these against Dir.pwd. */
868 return false;
869 }
870
871 /* strrchr()/strchr() stand in for search_required()'s find_ext()/memchr(),
872 * which agree with them now that `feature` is known to be NUL-free. */
873 ext = strrchr(feature, '.');
874 if (ext && strchr(ext, '/')) {
875 /* The dot is in a directory component: no extension. */
876 ext = NULL;
877 }
878 else if (ext && !IS_RBEXT(ext) && !IS_SOEXT(ext) && !IS_DLEXT(ext)) {
879 /* search_required() makes no already-provided probe at all for an extension
880 * it does not recognize, so no match here is conclusive. */
881 return false;
882 }
883
884 RB_VM_LOCKING() {
885 /* Non-atomic reads of possibly mutating objects: main-Ractor Ruby code can
886 * mutate $LOADED_FEATURES and $LOAD_PATH with no lock. Only header words are
887 * read -- flags, shared root, length -- never the live buffer, so a torn read
888 * costs at worst the fast path or a stale answer, never memory safety. We also
889 * read non-shareable objects from the main Ractor here, but they remain live. */
890 if (box->load_unstable_depth == 0 &&
891 RTEST(rb_ary_shared_with_p(box->loaded_features_snapshot, box->loaded_features))) {
892 /* A stale expanded load path only rules out the matches that need one.
893 * Pass 0 and let features_index_match() decline if it has to expand. */
894 VALUE load_path = expanded_load_path_current_p(box) ?
895 box->expanded_load_path : 0;
896 provided = feature_p_ractor_safe(box, box->loaded_features_snapshot,
897 load_path, feature, ext,
898 ext ? IS_RBEXT(ext) : TRUE);
899 }
900 }
901
902 RB_GC_GUARD(fname);
903 return provided;
904}
905
907 const rb_box_t *box;
908 VALUE features;
909 VALUE feature;
910 unsigned int lev;
911};
912
913static VALUE
914provide_feature_locked(VALUE argp)
915{
916 const struct provide_feature_args *args = (struct provide_feature_args *)argp;
917 const rb_box_t *box = args->box;
918 VALUE features = args->features;
919
920 // If loaded_features and loaded_features_snapshot share the same backing
921 // array, pushing into it would cause the whole array to be copied.
922 // To avoid this we first clear loaded_features_snapshot.
923 rb_ary_clear(box->loaded_features_snapshot);
924 rb_ary_push(features, args->feature);
925 features_index_add(box, args->feature, INT2FIX(RARRAY_LEN(features)-1));
926 reset_loaded_features_snapshot(box);
927 return Qnil;
928}
929
930static VALUE
931provide_feature_unlock(VALUE argp)
932{
933 struct provide_feature_args *args = (struct provide_feature_args *)argp;
934
935 RB_VM_LOCK_LEAVE_LEV(&args->lev);
936 return Qnil;
937}
938
939static void
940rb_provide_feature(const rb_box_t *box, VALUE feature)
941{
942 VALUE features;
943
944 features = box->loaded_features;
945 if (OBJ_FROZEN(features)) {
946 rb_raise(rb_eRuntimeError,
947 "$LOADED_FEATURES is frozen; cannot append feature");
948 }
949 feature = rb_fstring(feature);
950
951 get_loaded_features_index(box);
952
953 struct provide_feature_args args = {
954 .box = box,
955 .features = features,
956 .feature = feature,
957 };
958 RB_VM_LOCK_ENTER_LEV(&args.lev);
959 rb_ensure(provide_feature_locked, (VALUE)&args, provide_feature_unlock, (VALUE)&args);
960}
961
962void
963rb_provide(const char *feature)
964{
965 /*
966 * rb_provide() must use rb_current_box to store provided features
967 * in the current box's loaded_features, etc.
968 */
969 rb_provide_feature(rb_current_box(), rb_fstring_cstr(feature));
970}
971
972NORETURN(static void load_failed(VALUE));
973
974static inline VALUE
975realpath_internal_cached(VALUE hash, VALUE path)
976{
977 VALUE ret = rb_hash_aref(hash, path);
978 if(RTEST(ret)) {
979 return ret;
980 }
981
982 VALUE realpath = rb_realpath_internal(Qnil, path, 1);
983 rb_hash_aset(hash, rb_fstring(path), rb_fstring(realpath));
984 return realpath;
985}
986
988 pm_parse_result_t result;
989 VALUE fname;
990 VALUE realpath_map;
991 const rb_iseq_t *iseq;
992 VALUE error;
993};
994
995static VALUE
996load_prism_parse(VALUE args_ptr)
997{
998 struct load_prism_args *args = (struct load_prism_args *)args_ptr;
999 pm_parse_result_t *result = &args->result;
1000 VALUE fname = args->fname;
1001
1002 VALUE error = pm_load_parse_file(result, fname, NULL);
1003 if (error != Qnil) {
1004 args->error = error;
1005 return Qnil;
1006 }
1007
1008 int error_state;
1009 args->iseq = pm_iseq_new_top(&result->node, rb_fstring_lit("<top (required)>"), fname,
1010 realpath_internal_cached(args->realpath_map, fname), NULL, &error_state);
1011 if (error_state) {
1012 RUBY_ASSERT(args->iseq == NULL);
1013 rb_jump_tag(error_state);
1014 }
1015
1016 return Qnil;
1017}
1018
1019static VALUE
1020load_prism_free_result(VALUE args_ptr)
1021{
1022 struct load_prism_args *args = (struct load_prism_args *)args_ptr;
1023 pm_parse_result_free(&args->result);
1024 return Qnil;
1025}
1026
1027static inline void
1028load_iseq_eval(rb_execution_context_t *ec, VALUE fname)
1029{
1030 const rb_box_t *box = rb_loading_box();
1031 const rb_iseq_t *iseq = rb_iseq_load_iseq(fname);
1032
1033 if (!iseq) {
1034 rb_execution_context_t *ec = GET_EC();
1035 VALUE v = rb_vm_push_frame_fname(ec, fname);
1036
1037 VALUE realpath_map = box->loaded_features_realpath_map;
1038
1039 if (rb_ruby_prism_p()) {
1040 struct load_prism_args args = {
1041 .fname = fname,
1042 .realpath_map = realpath_map,
1043 .iseq = NULL,
1044 .error = Qnil,
1045 };
1046 pm_parse_result_init(&args.result);
1047 args.result.node.coverage_enabled = 1;
1048
1049 /* The parse result must be freed even if parsing or compiling
1050 * raises (e.g. an asynchronously raised IOError while reading a
1051 * pipe), so wrap it in rb_ensure. */
1052 rb_ensure(load_prism_parse, (VALUE)&args, load_prism_free_result, (VALUE)&args);
1053
1054 if (args.error != Qnil) {
1055 rb_vm_pop_frame(ec);
1056 RB_GC_GUARD(v);
1057 rb_exc_raise(args.error);
1058 }
1059
1060 iseq = args.iseq;
1061 }
1062 else {
1063 rb_ast_t *ast;
1064 VALUE ast_value;
1065 VALUE parser = rb_parser_new();
1066 rb_parser_set_context(parser, NULL, FALSE);
1067 ast_value = rb_parser_load_file(parser, fname);
1068 ast = rb_ruby_ast_data_get(ast_value);
1069
1070 iseq = rb_iseq_new_top(ast_value, rb_fstring_lit("<top (required)>"),
1071 fname, realpath_internal_cached(realpath_map, fname), NULL);
1072 rb_ast_dispose(ast);
1073 }
1074
1075 rb_vm_pop_frame(ec);
1076 RB_GC_GUARD(v);
1077 }
1078 rb_exec_event_hook_script_compiled(ec, iseq, Qnil);
1079
1080 rb_iseq_eval(iseq, box);
1081}
1082
1083static inline enum ruby_tag_type
1084load_wrapping(rb_execution_context_t *ec, VALUE fname, VALUE load_wrapper)
1085{
1086 enum ruby_tag_type state;
1087 rb_box_t *box;
1088 rb_thread_t *th = rb_ec_thread_ptr(ec);
1089 volatile VALUE wrapper = th->top_wrapper;
1090 volatile VALUE self = th->top_self;
1091#if !defined __GNUC__
1092 rb_thread_t *volatile th0 = th;
1093#endif
1094
1095 ec->errinfo = Qnil; /* ensure */
1096
1097 /* load in module as toplevel */
1098 if (BOX_OBJ_P(load_wrapper)) {
1099 box = rb_get_box_t(load_wrapper);
1100 if (!box->top_self) {
1101 box->top_self = rb_obj_clone(rb_vm_top_self());
1102 }
1103 th->top_self = box->top_self;
1104 }
1105 else {
1106 th->top_self = rb_obj_clone(rb_vm_top_self());
1107 }
1108 th->top_wrapper = load_wrapper;
1109 rb_extend_object(th->top_self, th->top_wrapper);
1110
1111 EC_PUSH_TAG(ec);
1112 state = EC_EXEC_TAG();
1113 if (state == TAG_NONE) {
1114 load_iseq_eval(ec, fname);
1115 }
1116 EC_POP_TAG();
1117
1118#if !defined __GNUC__
1119 th = th0;
1120 fname = RB_GC_GUARD(fname);
1121#endif
1122 th->top_self = self;
1123 th->top_wrapper = wrapper;
1124 return state;
1125}
1126
1127static inline void
1128raise_load_if_failed(rb_execution_context_t *ec, enum ruby_tag_type state)
1129{
1130 if (state) {
1131 rb_vm_jump_tag_but_local_jump(state);
1132 }
1133
1134 if (!NIL_P(ec->errinfo)) {
1135 rb_exc_raise(ec->errinfo);
1136 }
1137}
1138
1139static void
1140rb_load_internal(VALUE fname, VALUE wrap)
1141{
1142 VALUE box_value;
1143 rb_execution_context_t *ec = GET_EC();
1144 const rb_box_t *box = rb_loading_box();
1145 enum ruby_tag_type state = TAG_NONE;
1146 if (RTEST(wrap)) {
1147 if (!RB_TYPE_P(wrap, T_MODULE)) {
1148 wrap = rb_module_new();
1149 }
1150 state = load_wrapping(ec, fname, wrap);
1151 }
1152 else if (BOX_OPTIONAL_P(box)) {
1153 box_value = box->box_object;
1154 state = load_wrapping(ec, fname, box_value);
1155 }
1156 else {
1157 load_iseq_eval(ec, fname);
1158 }
1159 raise_load_if_failed(ec, state);
1160}
1161
1162void
1163rb_load(VALUE fname, int wrap)
1164{
1165 VALUE tmp = rb_find_file(FilePathValue(fname));
1166 if (!tmp) load_failed(fname);
1167 rb_load_internal(tmp, RBOOL(wrap));
1168}
1169
1170void
1171rb_load_protect(VALUE fname, int wrap, int *pstate)
1172{
1173 enum ruby_tag_type state;
1174
1175 EC_PUSH_TAG(GET_EC());
1176 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1177 rb_load(fname, wrap);
1178 }
1179 EC_POP_TAG();
1180
1181 if (state != TAG_NONE) *pstate = state;
1182}
1183
1184VALUE
1185rb_load_entrypoint(VALUE fname, VALUE wrap)
1186{
1187 VALUE path, orig_fname;
1188
1189 orig_fname = rb_get_path_check_to_string(fname);
1190 fname = rb_str_encode_ospath(orig_fname);
1191 RUBY_DTRACE_HOOK(LOAD_ENTRY, RSTRING_PTR(orig_fname));
1192
1193 path = rb_find_file(fname);
1194 if (!path) {
1195 if (!rb_file_load_ok(RSTRING_PTR(fname)))
1196 load_failed(orig_fname);
1197 path = fname;
1198 }
1199 rb_load_internal(path, wrap);
1200
1201 RUBY_DTRACE_HOOK(LOAD_RETURN, RSTRING_PTR(orig_fname));
1202
1203 return Qtrue;
1204}
1205
1206/*
1207 * call-seq:
1208 * load(filename, wrap=false) -> true
1209 *
1210 * Loads and executes the Ruby program in the file _filename_.
1211 *
1212 * If the filename is an absolute path (e.g. starts with '/'), the file
1213 * will be loaded directly using the absolute path.
1214 *
1215 * If the filename is an explicit relative path (e.g. starts with './' or
1216 * '../'), the file will be loaded using the relative path from the current
1217 * directory.
1218 *
1219 * Otherwise, the file will be searched for in the library
1220 * directories listed in <code>$LOAD_PATH</code> (<code>$:</code>).
1221 * If the file is found in a directory, it will attempt to load the file
1222 * relative to that directory. If the file is not found in any of the
1223 * directories in <code>$LOAD_PATH</code>, the file will be loaded using
1224 * the relative path from the current directory.
1225 *
1226 * If the file doesn't exist when there is an attempt to load it, a
1227 * LoadError will be raised.
1228 *
1229 * If the optional _wrap_ parameter is +true+, the loaded script will
1230 * be executed under an anonymous module. If the optional _wrap_ parameter
1231 * is a module, the loaded script will be executed under the given module.
1232 * In no circumstance will any local variables in the loaded file be
1233 * propagated to the loading environment.
1234 */
1235
1236static VALUE
1237rb_f_load(int argc, VALUE *argv, VALUE _)
1238{
1239 VALUE fname, wrap;
1240 rb_scan_args(argc, argv, "11", &fname, &wrap);
1241 return rb_load_entrypoint(fname, wrap);
1242}
1243
1244static char *
1245load_lock(const rb_box_t *box, const char *ftptr, bool warn)
1246{
1247 st_data_t data;
1248 st_table *loading_tbl = box->loading_table;
1249
1250 if (!st_lookup(loading_tbl, (st_data_t)ftptr, &data)) {
1251 /* partial state */
1252 ftptr = ruby_strdup(ftptr);
1253 data = (st_data_t)rb_thread_shield_new();
1254 st_insert(loading_tbl, (st_data_t)ftptr, data);
1255 return (char *)ftptr;
1256 }
1257
1258 if (warn && rb_thread_shield_owned((VALUE)data)) {
1259 VALUE warning = rb_warning_string("loading in progress, circular require considered harmful - %s", ftptr);
1260 rb_backtrace_each(rb_str_append, warning);
1261 rb_warning("%"PRIsVALUE, warning);
1262 }
1263 switch (rb_thread_shield_wait((VALUE)data)) {
1264 case Qfalse:
1265 case Qnil:
1266 return 0;
1267 }
1268 return (char *)ftptr;
1269}
1270
1271static int
1272release_thread_shield(st_data_t *key, st_data_t *value, st_data_t done, int existing)
1273{
1274 VALUE thread_shield = (VALUE)*value;
1275 if (!existing) return ST_STOP;
1276 if (done) {
1277 rb_thread_shield_destroy(thread_shield);
1278 /* Delete the entry even if there are waiting threads, because they
1279 * won't load the file and won't delete the entry. */
1280 }
1281 else if (rb_thread_shield_release(thread_shield)) {
1282 /* still in-use */
1283 return ST_CONTINUE;
1284 }
1285 xfree((char *)*key);
1286 return ST_DELETE;
1287}
1288
1289static void
1290load_unlock(const rb_box_t *box, const char *ftptr, int done)
1291{
1292 if (ftptr) {
1293 st_data_t key = (st_data_t)ftptr;
1294 st_table *loading_tbl = box->loading_table;
1295
1296 st_update(loading_tbl, key, release_thread_shield, done);
1297 }
1298}
1299
1300static VALUE rb_require_string_internal(VALUE fname, bool resurrect);
1301
1302/*
1303 * call-seq:
1304 * require(name) -> true or false
1305 *
1306 * Loads the given +name+, returning +true+ if successful and +false+ if the
1307 * feature is already loaded.
1308 *
1309 * If the filename neither resolves to an absolute path nor starts with
1310 * './' or '../', the file will be searched for in the library
1311 * directories listed in <code>$LOAD_PATH</code> (<code>$:</code>).
1312 * If the filename starts with './' or '../', resolution is based on Dir.pwd.
1313 *
1314 * If the filename has the extension ".rb", it is loaded as a source file; if
1315 * the extension is ".so", ".o", or the default shared library extension on
1316 * the current platform, Ruby loads the shared library as a Ruby extension.
1317 * Otherwise, Ruby tries adding ".rb", ".so", and so on to the name until
1318 * found. If the file named cannot be found, a LoadError will be raised.
1319 *
1320 * For Ruby extensions the filename given may use ".so" or ".o". For example,
1321 * on macOS the socket extension is "socket.bundle" and
1322 * <code>require 'socket.so'</code> will load the socket extension.
1323 *
1324 * The absolute path of the loaded file is added to
1325 * <code>$LOADED_FEATURES</code> (<code>$"</code>). A file will not be
1326 * loaded again if its path already appears in <code>$"</code>. For example,
1327 * <code>require 'a'; require './a'</code> will not load <code>a.rb</code>
1328 * again.
1329 *
1330 * require "my-library.rb"
1331 * require "db-driver"
1332 *
1333 * Any constants or globals within the loaded source file will be available
1334 * in the calling program's global namespace. However, local variables will
1335 * not be propagated to the loading environment.
1336 *
1337 */
1338
1339VALUE
1341{
1342 return rb_require_string(fname);
1343}
1344
1345VALUE
1346rb_require_relative_entrypoint(VALUE fname)
1347{
1348 VALUE base = rb_current_realfilepath();
1349 if (NIL_P(base)) {
1350 rb_loaderror("cannot infer basepath");
1351 }
1352 base = rb_file_dirname(base);
1353 return rb_require_string_internal(rb_file_absolute_path(fname, base), false);
1354}
1355
1356/*
1357 * call-seq:
1358 * require_relative(string) -> true or false
1359 *
1360 * Ruby tries to load the library named _string_ relative to the directory
1361 * containing the requiring file. If the file does not exist a LoadError is
1362 * raised. Returns +true+ if the file was loaded and +false+ if the file was
1363 * already loaded before.
1364 */
1365static VALUE
1366rb_f_require_relative(VALUE obj, VALUE fname)
1367{
1368 return rb_require_relative_entrypoint(fname);
1369}
1370
1371static char *
1372find_ext(VALUE str, char **ptr, const char **end)
1373{
1374 rb_len_t len = RSTRING_LEN(str);
1375 *ptr = RSTRING_PTR(str);
1376 *end = *ptr + len;
1377 return memrchr(*ptr, '.', len);
1378}
1379
1380static bool
1381ext_equal(const char *ext, const char *end, const char *suffix, size_t len)
1382{
1383 return (size_t)(end - ext) == len && memcmp(ext, suffix, len) == 0;
1384}
1385
1386#define EXT_RB_P(ext, end) ext_equal(ext, end, ".rb", rb_strlen_lit(".rb"))
1387#define EXT_SO_P(ext, end) (ext_equal(ext, end, ".so", rb_strlen_lit(".so")) || \
1388 ext_equal(ext, end, ".o", rb_strlen_lit(".o")))
1389#define EXT_DLEXT_P(ext, end) ext_equal(ext, end, DLEXT, rb_strlen_lit(DLEXT))
1390
1391typedef int (*feature_func)(const rb_box_t *box, const char *feature, const char *ext, int rb, int expanded, const char **fn);
1392
1393static int
1394search_required(const rb_box_t *box, VALUE fname, volatile VALUE *path, feature_func rb_feature_p)
1395{
1396 VALUE tmp;
1397 char *ext, *ftptr;
1398 int ft = 0;
1399 const char *ftend, *loading;
1400
1401 *path = 0;
1402 ext = find_ext(fname, &ftptr, &ftend);
1403 if (ext && !memchr(ext, '/', ftend - ext)) {
1404 if (EXT_RB_P(ext, ftend)) {
1405 if (rb_feature_p(box, ftptr, ext, TRUE, FALSE, &loading)) {
1406 if (loading) *path = rb_filesystem_str_new_cstr(loading);
1407 return 'r';
1408 }
1409 if ((tmp = rb_find_file(fname)) != 0) {
1410 ext = find_ext(tmp, &ftptr, &ftend);
1411 if (!rb_feature_p(box, ftptr, ext, TRUE, TRUE, &loading) || loading)
1412 *path = tmp;
1413 return 'r';
1414 }
1415 return 0;
1416 }
1417 else if (EXT_SO_P(ext, ftend)) {
1418 if (rb_feature_p(box, ftptr, ext, FALSE, FALSE, &loading)) {
1419 if (loading) *path = rb_filesystem_str_new_cstr(loading);
1420 return 's';
1421 }
1422 tmp = rb_str_subseq(fname, 0, ext - RSTRING_PTR(fname));
1423 rb_str_cat2(tmp, DLEXT);
1424 OBJ_FREEZE(tmp);
1425 if ((tmp = rb_find_file(tmp)) != 0) {
1426 ext = find_ext(tmp, &ftptr, &ftend);
1427 if (!rb_feature_p(box, ftptr, ext, FALSE, TRUE, &loading) || loading)
1428 *path = tmp;
1429 return 's';
1430 }
1431 }
1432 else if (EXT_DLEXT_P(ext, ftend)) {
1433 if (rb_feature_p(box, ftptr, ext, FALSE, FALSE, &loading)) {
1434 if (loading) *path = rb_filesystem_str_new_cstr(loading);
1435 return 's';
1436 }
1437 if ((tmp = rb_find_file(fname)) != 0) {
1438 ext = find_ext(tmp, &ftptr, &ftend);
1439 if (!rb_feature_p(box, ftptr, ext, FALSE, TRUE, &loading) || loading)
1440 *path = tmp;
1441 return 's';
1442 }
1443 }
1444 }
1445 else if ((ft = rb_feature_p(box, ftptr, 0, FALSE, FALSE, &loading)) == 'r') {
1446 if (loading) *path = rb_filesystem_str_new_cstr(loading);
1447 return 'r';
1448 }
1449 tmp = fname;
1450 const unsigned int type = rb_find_file_ext(&tmp, ft == 's' ? ruby_ext : loadable_ext);
1451
1452 // Check if it's a statically linked extension when
1453 // not already a feature and not found as a dynamic library.
1454 if (!ft && type != loadable_ext_rb) {
1455 rb_vm_t *vm = GET_VM();
1456 if (vm->static_ext_inits.num_entries) {
1457 VALUE lookup_name = tmp;
1458 // Append ".so" if not already present so for example "etc" can find "etc.so".
1459 // We always register statically linked extensions with a ".so" extension.
1460 // See encinit.c and extinit.c (generated at build-time).
1461 if (!ext) {
1462 lookup_name = rb_str_dup(lookup_name);
1463 rb_str_cat_cstr(lookup_name, ".so");
1464 }
1465 ftptr = RSTRING_PTR(lookup_name);
1466 if (st_lookup(&vm->static_ext_inits, (st_data_t)ftptr, NULL)) {
1467 *path = rb_filesystem_str_new_cstr(ftptr);
1468 RB_GC_GUARD(lookup_name);
1469 return 's';
1470 }
1471 }
1472 }
1473
1474 switch (type) {
1475 case 0:
1476 if (ft)
1477 goto feature_present;
1478 ftptr = RSTRING_PTR(tmp);
1479 return rb_feature_p(box, ftptr, 0, FALSE, TRUE, 0);
1480
1481 default:
1482 if (ft) {
1483 goto feature_present;
1484 }
1485 /* fall through */
1486 case loadable_ext_rb:
1487 ext = find_ext(tmp, &ftptr, &ftend);
1488 if (rb_feature_p(box, ftptr, ext, type == loadable_ext_rb, TRUE, &loading) && !loading)
1489 break;
1490 *path = tmp;
1491 }
1492 return type > loadable_ext_rb ? 's' : 'r';
1493
1494 feature_present:
1495 if (loading) *path = rb_filesystem_str_new_cstr(loading);
1496 return ft;
1497}
1498
1499static void
1500load_failed(VALUE fname)
1501{
1502 rb_load_fail(fname, "cannot load such file");
1503}
1504
1505static VALUE
1506load_ext(VALUE path, VALUE fname)
1507{
1508 VALUE loaded = path;
1509 const rb_box_t *box = rb_loading_box();
1510 VALUE cleanup = 0;
1511 if (BOX_USER_P(box)) {
1512 loaded = rb_box_local_extension(box->box_object, path, &cleanup);
1513 }
1514 rb_scope_visibility_set(METHOD_VISI_PUBLIC);
1515 void *handle = dln_load_feature(RSTRING_PTR(loaded), RSTRING_PTR(fname));
1516 if (cleanup) {
1517 rb_box_cleanup_local_extension(cleanup);
1518 rb_box_defer_unload_local_extension(handle);
1519 }
1520 RB_GC_GUARD(loaded);
1521 RB_GC_GUARD(fname);
1522 return (VALUE)handle;
1523}
1524
1525static VALUE
1526run_static_ext_init(VALUE vm_ptr, VALUE feature_value)
1527{
1528 rb_vm_t *vm = (rb_vm_t *)vm_ptr;
1529 const char *feature = RSTRING_PTR(feature_value);
1530 st_data_t key = (st_data_t)feature;
1531 st_data_t init_func;
1532
1533 if (st_delete(&vm->static_ext_inits, &key, &init_func)) {
1534 ((void (*)(void))init_func)();
1535 return Qtrue;
1536 }
1537 return Qfalse;
1538}
1539
1540static int
1541no_feature_p(const rb_box_t *box, const char *feature, const char *ext, int rb, int expanded, const char **fn)
1542{
1543 return 0;
1544}
1545
1546// Documented in doc/language/globals.md
1547VALUE
1548rb_resolve_feature_path(VALUE klass, VALUE fname)
1549{
1550 VALUE path;
1551 int found;
1552 VALUE sym;
1553 const rb_box_t *box = rb_loading_box();
1554
1555 fname = rb_get_path(fname);
1556 path = rb_str_encode_ospath(fname);
1557 found = search_required(box, path, &path, no_feature_p);
1558
1559 switch (found) {
1560 case 'r':
1561 sym = ID2SYM(rb_intern("rb"));
1562 break;
1563 case 's':
1564 sym = ID2SYM(rb_intern("so"));
1565 break;
1566 default:
1567 return Qnil;
1568 }
1569
1570 return rb_ary_new_from_args(2, sym, path);
1571}
1572
1573static void
1574ext_config_push(rb_thread_t *th, volatile struct rb_ext_config *prev)
1575{
1576 *prev = th->ext_config;
1577 th->ext_config = (struct rb_ext_config){0};
1578}
1579
1580static void
1581ext_config_pop(rb_thread_t *th, volatile struct rb_ext_config *prev)
1582{
1583 th->ext_config = *prev;
1584}
1585
1586void
1588{
1589 GET_THREAD()->ext_config.ractor_safe = flag;
1590}
1591
1592/*
1593 * returns
1594 * 0: if already loaded (false)
1595 * 1: successfully loaded (true)
1596 * <0: not found (LoadError)
1597 * >1: exception
1598 */
1599static int
1600require_internal(rb_execution_context_t *ec, VALUE fname, int exception, bool warn)
1601{
1602 volatile int result = -1;
1603 rb_thread_t *th = rb_ec_thread_ptr(ec);
1604 const rb_box_t *box = rb_loading_box();
1605 volatile const struct {
1606 VALUE wrapper, self, errinfo;
1607 rb_execution_context_t *ec;
1608 const rb_box_t *box;
1609 } saved = {
1610 th->top_wrapper, th->top_self, ec->errinfo,
1611 ec, box,
1612 };
1613 enum ruby_tag_type state;
1614 char *volatile ftptr = 0;
1615 VALUE path;
1616 volatile VALUE saved_path;
1617 volatile VALUE realpath = 0;
1618 VALUE realpaths = box->loaded_features_realpaths;
1619 VALUE realpath_map = box->loaded_features_realpath_map;
1620 volatile bool reset_ext_config = false;
1621 volatile struct rb_ext_config prev_ext_config;
1622
1623 path = rb_str_encode_ospath(fname);
1624 RUBY_DTRACE_HOOK(REQUIRE_ENTRY, RSTRING_PTR(fname));
1625 saved_path = path;
1626
1627 EC_PUSH_TAG(ec);
1628 ec->errinfo = Qnil; /* ensure */
1629 th->top_wrapper = 0;
1630 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1631 VALUE handle;
1632 int found;
1633
1634 RUBY_DTRACE_HOOK(FIND_REQUIRE_ENTRY, RSTRING_PTR(fname));
1635 found = search_required(box, path, &saved_path, rb_feature_p);
1636 RUBY_DTRACE_HOOK(FIND_REQUIRE_RETURN, RSTRING_PTR(fname));
1637 path = saved_path;
1638
1639 if (found) {
1640 if (!path || !(ftptr = load_lock(box, RSTRING_PTR(path), warn))) {
1641 result = 0;
1642 }
1643 else if (!*ftptr) {
1644 result = TAG_RETURN;
1645 }
1646 else if (found == 's' && RTEST(rb_vm_call_cfunc_in_box(Qnil, run_static_ext_init, (VALUE)th->vm, path, path, box))) {
1647 result = TAG_RETURN;
1648 }
1649 else if (RTEST(rb_hash_aref(realpaths,
1650 realpath = realpath_internal_cached(realpath_map, path)))) {
1651 result = 0;
1652 }
1653 else {
1654 switch (found) {
1655 case 'r':
1656 load_iseq_eval(saved.ec, path);
1657 break;
1658
1659 case 's':
1660 reset_ext_config = true;
1661 ext_config_push(th, &prev_ext_config);
1662 handle = rb_vm_call_cfunc_in_box(box->top_self, load_ext, path, fname, path, box);
1663 rb_hash_aset(box->ruby_dln_libmap, path, PTR2NUM(handle));
1664 break;
1665 }
1666 result = TAG_RETURN;
1667 }
1668 }
1669 }
1670 EC_POP_TAG();
1671
1672 ec = saved.ec;
1673 box = saved.box;
1674 rb_thread_t *th2 = rb_ec_thread_ptr(ec);
1675 th2->top_self = saved.self;
1676 th2->top_wrapper = saved.wrapper;
1677 if (reset_ext_config) ext_config_pop(th2, &prev_ext_config);
1678
1679 path = saved_path;
1680 if (ftptr) load_unlock(box, RSTRING_PTR(path), !state);
1681
1682 if (state) {
1683 if (state == TAG_FATAL || state == TAG_THROW) {
1684 EC_JUMP_TAG(ec, state);
1685 }
1686 else if (exception) {
1687 /* usually state == TAG_RAISE only, except for
1688 * rb_iseq_load_iseq in load_iseq_eval case */
1689 VALUE exc = rb_vm_make_jump_tag_but_local_jump(state, Qundef);
1690 if (!NIL_P(exc)) ec->errinfo = exc;
1691 return TAG_RAISE;
1692 }
1693 else if (state == TAG_RETURN) {
1694 return TAG_RAISE;
1695 }
1696 RB_GC_GUARD(fname);
1697 /* never TAG_RETURN */
1698 return state;
1699 }
1700 if (!NIL_P(ec->errinfo)) {
1701 if (!exception) return TAG_RAISE;
1702 rb_exc_raise(ec->errinfo);
1703 }
1704
1705 if (result == TAG_RETURN) {
1706 rb_provide_feature(box, path);
1707 VALUE real = realpath;
1708 if (real) {
1709 real = rb_fstring(real);
1710 rb_hash_aset(realpaths, real, Qtrue);
1711 }
1712 }
1713 ec->errinfo = saved.errinfo;
1714
1715 RUBY_DTRACE_HOOK(REQUIRE_RETURN, RSTRING_PTR(fname));
1716
1717 return result;
1718}
1719
1720int
1721rb_require_internal_silent(VALUE fname)
1722{
1723 if (!rb_ractor_main_p()) {
1724 return NUM2INT(rb_ractor_require(fname, true));
1725 }
1726
1727 rb_execution_context_t *ec = GET_EC();
1728 return require_internal(ec, fname, 1, false);
1729}
1730
1731int
1732rb_require_internal(VALUE fname)
1733{
1734 rb_execution_context_t *ec = GET_EC();
1735 return require_internal(ec, fname, 1, RTEST(ruby_verbose));
1736}
1737
1738int
1739ruby_require_internal(const char *fname, unsigned int len)
1740{
1741 struct RString fake = {RBASIC_INIT};
1742 VALUE str = rb_setup_fake_str(&fake, fname, len, 0);
1743 rb_execution_context_t *ec = GET_EC();
1744 int result = require_internal(ec, str, 0, RTEST(ruby_verbose));
1745 rb_set_errinfo(Qnil);
1746 return result == TAG_RETURN ? 1 : result ? -1 : 0;
1747}
1748
1749VALUE
1751{
1752 return rb_require_string_internal(FilePathValue(fname), false);
1753}
1754
1755static VALUE
1756rb_require_string_internal(VALUE fname, bool resurrect)
1757{
1758 rb_execution_context_t *ec = GET_EC();
1759
1760 // main ractor check
1761 if (!rb_ractor_main_p()) {
1762 if (resurrect) fname = rb_str_resurrect(fname);
1763 return rb_ractor_require(fname, false);
1764 }
1765 else {
1766 int result = require_internal(ec, fname, 1, RTEST(ruby_verbose));
1767
1768 if (result > TAG_RETURN) {
1769 EC_JUMP_TAG(ec, result);
1770 }
1771 if (result < 0) {
1772 if (resurrect) fname = rb_str_resurrect(fname);
1773 load_failed(fname);
1774 }
1775
1776 return RBOOL(result);
1777 }
1778}
1779
1780VALUE
1781rb_require(const char *fname)
1782{
1783 struct RString fake = {RBASIC_INIT};
1784 VALUE str = rb_setup_fake_str(&fake, fname, strlen(fname), 0);
1785 return rb_require_string_internal(str, true);
1786}
1787
1788static int
1789register_init_ext(st_data_t *key, st_data_t *value, st_data_t init, int existing)
1790{
1791 const char *name = (char *)*key;
1792 if (existing) {
1793 /* already registered */
1794 rb_warn("%s is already registered", name);
1795 }
1796 else {
1797 *value = (st_data_t)init;
1798 }
1799 return ST_CONTINUE;
1800}
1801
1802// Private API for statically linked extensions.
1803// Used with the ext/Setup file, the --with-setup and
1804// --with-static-linked-ext configuration option, etc.
1805void
1806ruby_init_ext(const char *name, void (*init)(void))
1807{
1808 rb_vm_t *vm = GET_VM();
1809 const rb_box_t *box = rb_loading_box();
1810
1811 if (feature_provided((rb_box_t *)box, name, 0))
1812 return;
1813
1814 st_update(&vm->static_ext_inits, (st_data_t)name, register_init_ext, (st_data_t)init);
1815}
1816
1817/*
1818 * call-seq:
1819 * mod.autoload(const, filename) -> nil
1820 *
1821 * Registers _filename_ to be loaded (using Kernel::require)
1822 * the first time that _const_ (which may be a String or
1823 * a symbol) is accessed in the namespace of _mod_.
1824 *
1825 * module A
1826 * end
1827 * A.autoload(:B, "b")
1828 * A::B.doit # autoloads "b"
1829 *
1830 * If _const_ in _mod_ is defined as autoload, the file name to be
1831 * loaded is replaced with _filename_. If _const_ is defined but not
1832 * as autoload, does nothing.
1833 *
1834 * Files that are currently being loaded must not be registered for
1835 * autoload.
1836 */
1837
1838static VALUE
1839rb_mod_autoload(VALUE mod, VALUE sym, VALUE file)
1840{
1841 ID id = rb_to_id(sym);
1842
1843 FilePathValue(file);
1844 rb_autoload_str(mod, id, file);
1845 return Qnil;
1846}
1847
1848/*
1849 * call-seq:
1850 * mod.autoload_relative(const, filename) -> nil
1851 *
1852 * Registers _filename_ to be loaded (using Kernel::require)
1853 * the first time that _const_ (which may be a String or
1854 * a symbol) is accessed in the namespace of _mod_. The _filename_
1855 * is interpreted as relative to the directory of the file where
1856 * autoload_relative is called.
1857 *
1858 * module A
1859 * end
1860 * A.autoload_relative(:B, "b.rb")
1861 *
1862 * If _const_ in _mod_ is defined as autoload, the file name to be
1863 * loaded is replaced with _filename_. If _const_ is defined but not
1864 * as autoload, does nothing.
1865 *
1866 * The relative path is converted to an absolute path, which is what
1867 * will be returned by Module#autoload? for the constant.
1868 *
1869 * Raises LoadError if called without file context (e.g., from eval).
1870 */
1871
1872static VALUE
1873rb_mod_autoload_relative(VALUE mod, VALUE sym, VALUE file)
1874{
1875 ID id = rb_to_id(sym);
1876 VALUE base, absolute_path;
1877
1878 FilePathValue(file);
1879
1880 base = rb_current_realfilepath();
1881 if (NIL_P(base)) {
1882 rb_loaderror("cannot infer basepath (autoload_relative called without file context)");
1883 }
1884 base = rb_file_dirname(base);
1885 absolute_path = rb_file_absolute_path(file, base);
1886
1887 rb_autoload_str(mod, id, absolute_path);
1888 return Qnil;
1889}
1890
1891/*
1892 * call-seq:
1893 * mod.autoload?(name, inherit=true) -> String or nil
1894 *
1895 * Returns _filename_ to be loaded if _name_ is registered as
1896 * +autoload+ in the namespace of _mod_ or one of its ancestors.
1897 *
1898 * module A
1899 * end
1900 * A.autoload(:B, "b")
1901 * A.autoload?(:B) #=> "b"
1902 *
1903 * If +inherit+ is false, the lookup only checks the autoloads in the receiver:
1904 *
1905 * class A
1906 * autoload :CONST, "const.rb"
1907 * end
1908 *
1909 * class B < A
1910 * end
1911 *
1912 * B.autoload?(:CONST) #=> "const.rb", found in A (ancestor)
1913 * B.autoload?(:CONST, false) #=> nil, not found in B itself
1914 *
1915 */
1916
1917static VALUE
1918rb_mod_autoload_p(int argc, VALUE *argv, VALUE mod)
1919{
1920 int recur = (rb_check_arity(argc, 1, 2) == 1) ? TRUE : RTEST(argv[1]);
1921 VALUE sym = argv[0];
1922
1923 ID id = rb_check_id(&sym);
1924 if (!id) {
1925 return Qnil;
1926 }
1927 return rb_autoload_at_p(mod, id, recur);
1928}
1929
1930/*
1931 * call-seq:
1932 * autoload(const, filename) -> nil
1933 *
1934 * Registers _filename_ to be loaded (using Kernel::require)
1935 * the first time that _const_ (which may be a String or
1936 * a symbol) is accessed.
1937 *
1938 * autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
1939 *
1940 * If _const_ is defined as autoload, the file name to be loaded is
1941 * replaced with _filename_. If _const_ is defined but not as
1942 * autoload, does nothing.
1943 *
1944 * Files that are currently being loaded must not be registered for
1945 * autoload.
1946 */
1947
1948static VALUE
1949rb_f_autoload(VALUE obj, VALUE sym, VALUE file)
1950{
1951 VALUE klass = rb_class_real(rb_vm_cbase());
1952 if (!klass) {
1953 rb_raise(rb_eTypeError, "Can not set autoload on singleton class");
1954 }
1955 return rb_mod_autoload(klass, sym, file);
1956}
1957
1958/*
1959 * call-seq:
1960 * autoload_relative(const, filename) -> nil
1961 *
1962 * Registers _filename_ to be loaded (using Kernel::require)
1963 * the first time that _const_ (which may be a String or
1964 * a symbol) is accessed. The _filename_ is interpreted as
1965 * relative to the directory of the file where autoload_relative
1966 * is called.
1967 *
1968 * autoload_relative(:MyModule, "my_module.rb")
1969 *
1970 * If _const_ is defined as autoload, the file name to be loaded is
1971 * replaced with _filename_. If _const_ is defined but not as
1972 * autoload, does nothing.
1973 *
1974 * The relative path is converted to an absolute path, which is what
1975 * will be returned by Kernel#autoload? for the constant.
1976 *
1977 * Raises LoadError if called without file context (e.g., from eval).
1978 */
1979
1980static VALUE
1981rb_f_autoload_relative(VALUE obj, VALUE sym, VALUE file)
1982{
1983 VALUE klass = rb_class_real(rb_vm_cbase());
1984 if (!klass) {
1985 rb_raise(rb_eTypeError, "Can not set autoload on singleton class");
1986 }
1987 return rb_mod_autoload_relative(klass, sym, file);
1988}
1989
1990/*
1991 * call-seq:
1992 * autoload?(name, inherit=true) -> String or nil
1993 *
1994 * Returns _filename_ to be loaded if _name_ is registered as
1995 * +autoload+ in the current namespace or one of its ancestors.
1996 *
1997 * autoload(:B, "b")
1998 * autoload?(:B) #=> "b"
1999 *
2000 * module C
2001 * autoload(:D, "d")
2002 * autoload?(:D) #=> "d"
2003 * autoload?(:B) #=> nil
2004 * end
2005 *
2006 * class E
2007 * autoload(:F, "f")
2008 * autoload?(:F) #=> "f"
2009 * autoload?(:B) #=> "b"
2010 * end
2011 */
2012
2013static VALUE
2014rb_f_autoload_p(int argc, VALUE *argv, VALUE obj)
2015{
2016 /* use rb_vm_cbase() as same as rb_f_autoload. */
2017 VALUE klass = rb_vm_cbase();
2018 if (NIL_P(klass)) {
2019 return Qnil;
2020 }
2021 return rb_mod_autoload_p(argc, argv, klass);
2022}
2023
2024void *
2025rb_ext_resolve_symbol(const char* fname, const char* symbol)
2026{
2027 VALUE handle;
2028 VALUE resolved;
2029 VALUE path;
2030 const char *ext;
2031 VALUE fname_str = rb_str_new_cstr(fname);
2032 const rb_box_t *box = rb_loading_box();
2033
2034 resolved = rb_resolve_feature_path((VALUE)NULL, fname_str);
2035 if (NIL_P(resolved)) {
2036 ext = strrchr(fname, '.');
2037 if (!ext || !IS_SOEXT(ext)) {
2038 rb_str_cat_cstr(fname_str, ".so");
2039 }
2040 if (rb_feature_p(box, fname, 0, FALSE, FALSE, 0)) {
2041 return dln_symbol(NULL, symbol);
2042 }
2043 return NULL;
2044 }
2045 if (RARRAY_LEN(resolved) != 2 || rb_ary_entry(resolved, 0) != ID2SYM(rb_intern("so"))) {
2046 return NULL;
2047 }
2048 path = rb_ary_entry(resolved, 1);
2049 handle = rb_hash_lookup(box->ruby_dln_libmap, path);
2050 if (NIL_P(handle)) {
2051 return NULL;
2052 }
2053 return dln_symbol(NUM2PTR(handle), symbol);
2054}
2055
2056void
2057Init_load(void)
2058{
2059 static const char var_load_path[] = "$:";
2060 ID id_load_path = rb_intern2(var_load_path, sizeof(var_load_path)-1);
2061
2062 rb_define_hooked_variable(var_load_path, 0, load_path_getter, rb_gvar_readonly_setter);
2063 rb_gvar_box_ready(var_load_path);
2064 rb_alias_variable(rb_intern_const("$-I"), id_load_path);
2065 rb_alias_variable(rb_intern_const("$LOAD_PATH"), id_load_path);
2066
2067 rb_define_virtual_variable("$\"", get_LOADED_FEATURES, 0);
2068 rb_gvar_box_ready("$\"");
2069 rb_define_virtual_variable("$LOADED_FEATURES", get_LOADED_FEATURES, 0); // TODO: rb_alias_variable ?
2070 rb_gvar_box_ready("$LOADED_FEATURES");
2071
2072 rb_define_global_function("load", rb_f_load, -1);
2074 rb_define_global_function("require_relative", rb_f_require_relative, 1);
2075 rb_define_method(rb_cModule, "autoload", rb_mod_autoload, 2);
2076 rb_define_method(rb_cModule, "autoload_relative", rb_mod_autoload_relative, 2);
2077 rb_define_method(rb_cModule, "autoload?", rb_mod_autoload_p, -1);
2078 rb_define_global_function("autoload", rb_f_autoload, 2);
2079 rb_define_global_function("autoload_relative", rb_f_autoload_relative, 2);
2080 rb_define_global_function("autoload?", rb_f_autoload_p, -1);
2081}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition eval.c:1946
VALUE rb_module_new(void)
Creates a new, anonymous module.
Definition class.c:1629
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3358
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1700
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define NIL_P
Old name of RB_NIL_P.
#define FIXNUM_P
Old name of RB_FIXNUM_P.
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:476
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
void rb_loaderror(const char *fmt,...)
Raises an instance of rb_eLoadError.
Definition error.c:3960
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:495
VALUE rb_cModule
Module class.
Definition object.c:61
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition object.c:221
VALUE rb_obj_clone(VALUE obj)
Produces a shallow copy of the given object.
Definition object.c:497
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
Encoding relates APIs.
VALUE rb_ary_shared_with_p(VALUE lhs, VALUE rhs)
Queries if the passed two arrays share the same backend storage.
VALUE rb_ary_resurrect(VALUE ary)
I guess there is no use case of this function in extension libraries, but this is a routine identical...
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_replace(VALUE copy, VALUE orig)
Replaces the contents of the former object with the contents of the latter.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_hidden_new(rb_len_t capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:963
VALUE rb_f_require(VALUE self, VALUE feature)
Identical to rb_require_string(), except it ignores the first argument for no reason.
Definition load.c:1340
void rb_ext_ractor_safe(bool flag)
Asserts that the extension library that calls this function is aware of Ractor.
Definition load.c:1587
VALUE rb_require_string(VALUE feature)
Finds and loads the given feature, if absent.
Definition load.c:1750
int rb_feature_provided(const char *feature, const char **loading)
Identical to rb_provided(), except it additionally returns the "canonical" name of the loaded feature...
Definition load.c:792
void rb_load_protect(VALUE path, int wrap, int *state)
Identical to rb_load(), except it avoids potential global escapes.
Definition load.c:1171
int rb_provided(const char *feature)
Queries if the given feature has already been loaded into the execution context.
Definition load.c:759
void rb_load(VALUE path, int wrap)
Loads and executes the Ruby program in the given file.
Definition load.c:1163
void * rb_ext_resolve_symbol(const char *feature, const char *symbol)
Resolves and returns a symbol of a function in the native extension specified by the feature and symb...
Definition load.c:2025
VALUE rb_str_subseq(VALUE str, rb_len_t beg, rb_len_t len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3288
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3940
VALUE rb_str_tmp_new(rb_len_t len)
Allocates a "temporary" string.
Definition string.c:1811
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2052
VALUE rb_str_resurrect(VALUE str)
Like rb_str_dup(), but always create an instance of rb_cString regardless of the given object's class...
Definition string.c:2070
VALUE rb_filesystem_str_new_cstr(const char *ptr)
Identical to rb_filesystem_str_new(), except it assumes the passed pointer is a pointer to a C string...
Definition string.c:1480
VALUE rb_str_equal(VALUE str1, VALUE str2)
Equality of two strings.
Definition string.c:4446
#define rb_strlen_lit(str)
Length of a string literal.
Definition string.h:1717
VALUE rb_str_freeze(VALUE str)
This is the implementation of String#freeze.
Definition string.c:3413
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1681
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
void rb_alias_variable(ID dst, ID src)
Aliases a global variable.
Definition variable.c:1231
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1296
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:16247
rb_gvar_setter_t rb_gvar_readonly_setter
This function just raises rb_eNameError.
Definition variable.h:135
int len
Length of the buffer.
Definition io.h:8
char * ruby_strdup(const char *str)
This is our own version of strdup(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
Definition util.c:511
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:387
void rb_define_hooked_variable(const char *q, VALUE *w, type *e, void_type *r)
Define a function-backended global variable.
VALUE type(ANYARGS)
ANYARGS-ed function type.
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
void rb_define_virtual_variable(const char *q, type *w, void_type *e)
Define a function-backended global variable.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:422
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
VALUE rb_require(const char *feature)
Identical to rb_require_string(), except it takes C's string instead of Ruby's.
Definition load.c:1781
#define FilePathValue(v)
Ensures that the parameter object is a path.
Definition ruby.h:90
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Ruby's String.
Definition rstring.h:196
pm_scope_node_t node
The resulting scope node that will hold the generated AST.
Definition st.h:79
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:425
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376