Ruby 4.1.0dev (2026-11-18 revision 9de06831e37534f8a163e598cc0c6903c7687430)
box.c (9de06831e37534f8a163e598cc0c6903c7687430)
1/* indent-tabs-mode: nil */
2
3#include "eval_intern.h"
4#include "internal.h"
5#include "internal/box.h"
6#include "internal/class.h"
7#include "internal/eval.h"
8#include "internal/error.h"
9#include "internal/file.h"
10#include "internal/gc.h"
11#include "internal/hash.h"
12#include "internal/io.h"
13#include "internal/load.h"
14#include "internal/random.h"
15#include "internal/st.h"
16#include "internal/variable.h"
17#include "iseq.h"
19#include "ruby/util.h"
20#include "vm_core.h"
21#include "darray.h"
22#include "zjit.h"
23
24#include "builtin.h"
25
26#include <stdio.h>
27
28#ifdef HAVE_FCNTL_H
29#include <fcntl.h>
30#endif
31#ifdef HAVE_SYS_SENDFILE_H
32# include <sys/sendfile.h>
33#endif
34#ifdef HAVE_COPYFILE_H
35#include <copyfile.h>
36#endif
37
39VALUE rb_cBoxEntry = 0;
40VALUE rb_mBoxLoader = 0;
41
42static rb_box_t master_box[1]; /* Initialize in initialize_master_box() */
43static rb_box_t *root_box;
44static rb_box_t *main_box;
45
46static rb_box_gem_flags_t box_gem_flags[1];
47
48static char *tmp_dir;
49static bool tmp_dir_has_dirsep;
50
51#ifndef MAXPATHLEN
52# define MAXPATHLEN 1024
53#endif
54
55/* process-private 0700 directory for box-local copies of extensions */
56static char box_ext_tmp_dir[MAXPATHLEN];
57static rb_pid_t box_ext_tmp_dir_owner;
58static unsigned long box_ext_seq;
59
60#define BOX_TMP_PREFIX "_ruby_box_"
61
62#if defined(_WIN32)
63# define DIRSEP "\\"
64#else
65# define DIRSEP "/"
66#endif
67
68bool ruby_box_enabled = false; // extern
69bool ruby_box_init_done = false; // extern
70bool ruby_box_crashed = false; // extern, changed only in vm.c
71
72VALUE rb_resolve_feature_path(VALUE klass, VALUE fname);
73static VALUE rb_box_inspect(VALUE obj);
74
75void
76rb_box_set_gem_flags(rb_box_gem_flags_t *flags)
77{
78
79 box_gem_flags->gem = flags->gem;
80 box_gem_flags->error_highlight = flags->error_highlight;
81 box_gem_flags->did_you_mean = flags->did_you_mean;
82 box_gem_flags->syntax_suggest = flags->syntax_suggest;
83}
84
85void
86rb_box_init_done(void)
87{
88 ruby_box_init_done = true;
89}
90
91const rb_box_t *
92rb_master_box(void)
93{
94 return master_box;
95}
96
97const rb_box_t *
98rb_root_box(void)
99{
100 if (!root_box) // The root box isn't initialized yet - The Ruby runtime is in setup.
101 return master_box;
102 return root_box;
103}
104
105const rb_box_t *
106rb_main_box(void)
107{
108 return main_box;
109}
110
111// NOTE: must be called by Ruby thread
112const rb_box_t *
113rb_current_box(void)
114{
115 /*
116 * If RUBY_BOX is not set, the master box is the only available one.
117 *
118 * While the root/main boxes are not initialized, the master box is
119 * the only valid box.
120 * This early return is to avoid accessing EC before its setup.
121 */
122 if (!root_box)
123 return master_box;
124 if (!main_box)
125 return root_box;
126
127 return rb_vm_current_box(GET_EC());
128}
129
130// NOTE: must be called by Ruby thread
131const rb_box_t *
132rb_loading_box(void)
133{
134 if (!root_box)
135 return master_box;
136 if (!main_box)
137 return root_box;
138
139 return rb_vm_loading_box(GET_EC());
140}
141
142// NOTE: must be called by Ruby thread
143const rb_box_t *
144rb_current_box_in_crash_report(void)
145{
146 if (ruby_box_crashed)
147 return NULL;
148 return rb_current_box();
149}
150
151static long box_id_counter = 0;
152
153static long
154box_generate_id(void)
155{
156 long id;
157 RB_VM_LOCKING() {
158 id = ++box_id_counter;
159 }
160 return id;
161}
162
163static VALUE
164box_main_to_s(VALUE obj)
165{
166 return rb_str_new2("main");
167}
168
169static void
170box_entry_initialize(rb_box_t *box)
171{
172 const rb_box_t *master = rb_master_box();
173
174 // These will be updated immediately
175 box->box_object = 0;
176 box->box_id = 0;
177
178 box->top_self = rb_obj_alloc(rb_cObject);
179 rb_define_singleton_method(box->top_self, "to_s", box_main_to_s, 0);
180 rb_define_alias(rb_singleton_class(box->top_self), "inspect", "to_s");
181 box->load_path = rb_ary_dup(master->load_path);
182 box->expanded_load_path = rb_ary_dup(master->expanded_load_path);
183 box->load_path_snapshot = rb_ary_new();
184 box->load_path_check_cache = 0;
185 box->loaded_features = rb_ary_dup(master->loaded_features);
186 box->loaded_features_snapshot = rb_ary_new();
187 box->loaded_features_index = st_init_numtable();
188 box->load_unstable_depth = 0;
189 box->loaded_features_realpaths = rb_hash_dup(master->loaded_features_realpaths);
190 box->loaded_features_realpath_map = rb_hash_dup(master->loaded_features_realpath_map);
191 box->loading_table = st_init_strtable();
192 box->ruby_dln_libmap = rb_hash_new();
193 box->gvar_tbl = rb_hash_new();
194 box->classext_cow_classes = st_init_numtable();
195
196 box->is_user = true;
197 box->is_optional = true;
198}
199
200void
201rb_box_gc_update_references(void *ptr)
202{
203 rb_box_t *box = (rb_box_t *)ptr;
204 if (!box) return;
205
206 if (box->box_object)
207 rb_gc_update_moved(&box->box_object);
208 if (box->top_self)
209 rb_gc_update_moved(&box->top_self);
210 rb_gc_update_moved(&box->load_path);
211 rb_gc_update_moved(&box->expanded_load_path);
212 rb_gc_update_moved(&box->load_path_snapshot);
213 if (box->load_path_check_cache) {
214 rb_gc_update_moved(&box->load_path_check_cache);
215 }
216 rb_gc_update_moved(&box->loaded_features);
217 rb_gc_update_moved(&box->loaded_features_snapshot);
218 rb_gc_update_moved(&box->loaded_features_realpaths);
219 rb_gc_update_moved(&box->loaded_features_realpath_map);
220 rb_gc_update_moved(&box->ruby_dln_libmap);
221 rb_gc_update_moved(&box->gvar_tbl);
222}
223
224void
225rb_box_entry_mark(void *ptr)
226{
227 const rb_box_t *box = (rb_box_t *)ptr;
228 if (!box) return;
229
230 rb_gc_mark(box->box_object);
231 rb_gc_mark(box->top_self);
232 rb_gc_mark(box->load_path);
233 rb_gc_mark(box->expanded_load_path);
234 rb_gc_mark(box->load_path_snapshot);
235 rb_gc_mark(box->load_path_check_cache);
236 rb_gc_mark(box->loaded_features);
237 rb_gc_mark(box->loaded_features_snapshot);
238 rb_gc_mark(box->loaded_features_realpaths);
239 rb_gc_mark(box->loaded_features_realpath_map);
240 if (box->loading_table) {
241 rb_mark_tbl(box->loading_table);
242 }
243 rb_gc_mark(box->ruby_dln_libmap);
244 rb_gc_mark(box->gvar_tbl);
245 if (box->classext_cow_classes) {
246 rb_mark_set(box->classext_cow_classes);
247 }
248}
249
250static int
251free_loading_table_entry(st_data_t key, st_data_t value, st_data_t arg)
252{
253 xfree((char *)key);
254 return ST_DELETE;
255}
256
257static int
258free_loaded_feature_index_i(st_data_t key, st_data_t value, st_data_t arg)
259{
260 if (!FIXNUM_P(value)) {
261 rb_darray_free_sized((void *)value, long);
262 }
263 return ST_CONTINUE;
264}
265
266static void
267free_box_st_tables(void *ptr)
268{
269 rb_box_t *box = (rb_box_t *)ptr;
270 if (box->loading_table) {
271 st_foreach(box->loading_table, free_loading_table_entry, 0);
272 st_free_table(box->loading_table);
273 box->loading_table = 0;
274 }
275
276 if (box->loaded_features_index) {
277 st_foreach(box->loaded_features_index, free_loaded_feature_index_i, 0);
278 st_free_table(box->loaded_features_index);
279 }
280}
281
282static int
283free_classext_for_box(st_data_t key, st_data_t _value, st_data_t box_arg)
284{
285 rb_classext_t *ext;
286 VALUE obj = (VALUE)key;
287 const rb_box_t *box = (const rb_box_t *)box_arg;
288
289 if (RB_TYPE_P(obj, T_NONE)) {
290 /* RUBY_FREE_AT_EXIT can free a class before the box that refers to
291 * it, and freeing a class already freed its classext for this box. */
292 return ST_CONTINUE;
293 }
294
295 if (RB_TYPE_P(obj, T_CLASS) || RB_TYPE_P(obj, T_MODULE)) {
296 ext = rb_class_unlink_classext(obj, box);
297 rb_class_classext_free(obj, ext, false);
298 }
299 else if (RB_TYPE_P(obj, T_ICLASS)) {
300 ext = rb_class_unlink_classext(obj, box);
301 rb_iclass_classext_free(obj, ext, false);
302 }
303 else {
304 rb_bug("Invalid type of object in classext_cow_classes: %s", rb_type_str(BUILTIN_TYPE(obj)));
305 }
306 return ST_CONTINUE;
307}
308
309static void
310box_entry_free(void *ptr)
311{
312 const rb_box_t *box = (const rb_box_t *)ptr;
313
314 if (box->classext_cow_classes) {
315 st_foreach(box->classext_cow_classes, free_classext_for_box, (st_data_t)box);
316 }
317
318 free_box_st_tables(ptr);
319 SIZED_FREE(box);
320}
321
322static size_t
323box_entry_memsize(const void *ptr)
324{
325 size_t size = sizeof(rb_box_t);
326 const rb_box_t *box = (const rb_box_t *)ptr;
327 if (box->loaded_features_index) {
328 size += rb_st_memsize(box->loaded_features_index);
329 }
330 if (box->loading_table) {
331 size += rb_st_memsize(box->loading_table);
332 }
333 return size;
334}
335
336static const rb_data_type_t rb_box_data_type = {
337 "Ruby::Box::Entry",
338 {
339 rb_box_entry_mark,
340 box_entry_free,
341 box_entry_memsize,
342 rb_box_gc_update_references,
343 },
344 0, 0, RUBY_TYPED_FREE_IMMEDIATELY // TODO: enable RUBY_TYPED_WB_PROTECTED when inserting write barriers
345};
346
347static const rb_data_type_t rb_master_box_data_type = {
348 "Ruby::Box::Master",
349 {
350 rb_box_entry_mark,
351 free_box_st_tables,
352 box_entry_memsize,
353 rb_box_gc_update_references,
354 },
355 &rb_box_data_type, 0, RUBY_TYPED_THREAD_SAFE_FREE // TODO: enable RUBY_TYPED_WB_PROTECTED when inserting write barriers
356};
357
358VALUE
359rb_box_entry_alloc(VALUE klass)
360{
361 rb_box_t *entry;
362 VALUE obj = TypedData_Make_Struct(klass, rb_box_t, &rb_box_data_type, entry);
363 box_entry_initialize(entry);
364 return obj;
365}
366
367static rb_box_t *
368get_box_struct_internal(VALUE entry)
369{
370 rb_box_t *sval;
371 TypedData_Get_Struct(entry, rb_box_t, &rb_box_data_type, sval);
372 return sval;
373}
374
375rb_box_t *
376rb_get_box_t(VALUE box)
377{
378 VALUE entry;
379 ID id_box_entry;
380
381 VM_ASSERT(box);
382
383 if (NIL_P(box))
384 return (rb_box_t *)rb_root_box();
385
386 VM_ASSERT(BOX_OBJ_P(box));
387
388 CONST_ID(id_box_entry, "__box_entry__");
389 entry = rb_attr_get(box, id_box_entry);
390 return get_box_struct_internal(entry);
391}
392
393VALUE
394rb_get_box_object(rb_box_t *box)
395{
396 VM_ASSERT(box && box->box_object);
397 return box->box_object;
398}
399
400/*
401 * call-seq:
402 * Ruby::Box.new -> new_box
403 *
404 * Returns a new Ruby::Box object.
405 */
406static VALUE
407box_initialize(VALUE box_value)
408{
409 rb_box_t *box;
410 rb_classext_t *object_classext;
411 VALUE entry;
412 ID id_box_entry;
413 CONST_ID(id_box_entry, "__box_entry__");
414
415 if (!rb_box_available()) {
416 rb_raise(rb_eRuntimeError, "Ruby Box is disabled. Set RUBY_BOX=1 environment variable to use Ruby::Box.");
417 }
418
419 entry = rb_class_new_instance_pass_kw(0, NULL, rb_cBoxEntry);
420 box = get_box_struct_internal(entry);
421
422 box->box_object = box_value;
423 box->box_id = box_generate_id();
424 rb_define_singleton_method(box->load_path, "resolve_feature_path", rb_resolve_feature_path, 1);
425
426 // Set the Ruby::Box object unique/consistent from any boxes to have just single
427 // constant table from any view of every (including main) box.
428 // If a code in the box adds a constant, the constant will be visible even from root/main.
429 RCLASS_SET_PRIME_CLASSEXT_WRITABLE(box_value, true);
430
431 // Get a clean constant table of Object even by writable one
432 // because ns was just created, so it has not touched any constants yet.
433 object_classext = RCLASS_EXT_WRITABLE_IN_BOX(rb_cObject, box);
434 RCLASS_SET_CONST_TBL(box_value, RCLASSEXT_CONST_TBL(object_classext), true);
435
436 rb_ivar_set(box_value, id_box_entry, entry);
437
438 if (ruby_box_init_done) {
439 if (box_gem_flags->gem) {
440 rb_vm_call_cfunc_in_box(Qnil, rb_define_gem_modules, (VALUE)box_gem_flags, Qnil,
441 rb_str_new_cstr("before_prelude.user.dummy"), (const rb_box_t *)box);
442 rb_load_gem_prelude((VALUE)box);
443 }
444 }
445
446 // Invalidate ZJIT code that assumes only the root box is active
447 rb_zjit_invalidate_root_box();
448
449 return box_value;
450}
451
452/*
453 * call-seq:
454 * Ruby::Box.enabled? -> true or false
455 *
456 * Returns +true+ if Ruby::Box is enabled.
457 */
458static VALUE
459rb_box_s_getenabled(VALUE recv)
460{
461 return RBOOL(rb_box_available());
462}
463
464/*
465 * call-seq:
466 * Ruby::Box.current -> box, nil or false
467 *
468 * Returns the current box.
469 * Returns +nil+ if Ruby Box is not enabled.
470 */
471static VALUE
472rb_box_s_current(VALUE recv)
473{
474 const rb_box_t *box;
475
476 if (!rb_box_available())
477 return Qnil;
478
479 box = rb_vm_current_box(GET_EC());
480 VM_ASSERT(box && box->box_object);
481 return box->box_object;
482}
483
484/*
485 * call-seq:
486 * load_path -> array
487 *
488 * Returns box local load path.
489 */
490static VALUE
491rb_box_load_path(VALUE box)
492{
493 VM_ASSERT(BOX_OBJ_P(box));
494 return rb_get_box_t(box)->load_path;
495}
496
497#ifdef _WIN32
498UINT rb_w32_system_tmpdir(WCHAR *path, UINT len);
499#endif
500
501/* Copied from mjit.c Ruby 3.0.3 */
502static char *
503system_default_tmpdir(void)
504{
505 // c.f. ext/etc/etc.c:etc_systmpdir()
506#ifdef _WIN32
507 WCHAR tmppath[_MAX_PATH];
508 UINT len = rb_w32_system_tmpdir(tmppath, numberof(tmppath));
509 if (len) {
510 int blen = WideCharToMultiByte(CP_UTF8, 0, tmppath, len, NULL, 0, NULL, NULL);
511 char *tmpdir = xmalloc(blen + 1);
512 WideCharToMultiByte(CP_UTF8, 0, tmppath, len, tmpdir, blen, NULL, NULL);
513 tmpdir[blen] = '\0';
514 return tmpdir;
515 }
516#elif defined _CS_DARWIN_USER_TEMP_DIR
517 char path[MAXPATHLEN];
518 size_t len = confstr(_CS_DARWIN_USER_TEMP_DIR, path, sizeof(path));
519 if (len > 0) {
520 char *tmpdir = xmalloc(len);
521 if (len > sizeof(path)) {
522 confstr(_CS_DARWIN_USER_TEMP_DIR, tmpdir, len);
523 }
524 else {
525 memcpy(tmpdir, path, len);
526 }
527 return tmpdir;
528 }
529#endif
530 return 0;
531}
532
533static int
534check_tmpdir(const char *dir)
535{
536 struct stat st;
537
538 if (!dir) return FALSE;
539 if (stat(dir, &st)) return FALSE;
540#ifndef S_ISDIR
541# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
542#endif
543 if (!S_ISDIR(st.st_mode)) return FALSE;
544#ifndef _WIN32
545# ifndef S_IWOTH
546# define S_IWOTH 002
547# endif
548 if (st.st_mode & S_IWOTH) {
549# ifdef S_ISVTX
550 if (!(st.st_mode & S_ISVTX)) return FALSE;
551# else
552 return FALSE;
553# endif
554 }
555 if (access(dir, W_OK)) return FALSE;
556#endif
557 return TRUE;
558}
559
560static char *
561system_tmpdir(void)
562{
563 char *tmpdir;
564# define RETURN_ENV(name) \
565 if (check_tmpdir(tmpdir = getenv(name))) return ruby_strdup(tmpdir)
566 RETURN_ENV("TMPDIR");
567 RETURN_ENV("TMP");
568 tmpdir = system_default_tmpdir();
569 if (check_tmpdir(tmpdir)) return tmpdir;
570 return ruby_strdup("/tmp");
571# undef RETURN_ENV
572}
573
574/* end of copy */
575
576/* Box-local copies of extensions are placed in a process-private 0700
577 * directory with an unpredictable name, so that other local users cannot
578 * occupy the copy destination in a shared TMPDIR [Bug #22110], and so
579 * that the file name of each copy stays short regardless of the depth of
580 * the original path (a full path flattened into a single file name can
581 * exceed NAME_MAX). */
582static void
583ensure_box_ext_tmp_dir(void)
584{
585 /* A forked child inherits the parent's directory path; discard it so
586 * that each process creates its own directory and removes only that
587 * one at teardown. */
588 if (box_ext_tmp_dir[0] && box_ext_tmp_dir_owner != getpid()) {
589 box_ext_tmp_dir[0] = '\0';
590 box_ext_seq = 0;
591 }
592 if (box_ext_tmp_dir[0]) return;
593
594 int last_errno = 0;
595 for (int retry = 0; retry < 10; retry++) {
596 char path[MAXPATHLEN];
597 uint64_t suffix;
598 if (ruby_fill_random_bytes(&suffix, sizeof(suffix), FALSE) != 0) {
599 /* no random source; mkdir(0700) below still refuses hijacked names */
600 suffix = (uint64_t)(uintptr_t)&suffix ^ (uint64_t)retry;
601 }
602 int wrote = snprintf(path, sizeof(path), "%s%s%sp%"PRI_PIDT_PREFIX"u_%.16"PRIx64,
603 tmp_dir, tmp_dir_has_dirsep ? "" : DIRSEP,
604 BOX_TMP_PREFIX, getpid(), suffix);
605 if (wrote >= (int)sizeof(path)) {
606 rb_raise(rb_eLoadError, "TMPDIR for Ruby Box extensions is too long: %s", tmp_dir);
607 }
608 if (mkdir(path, 0700) == 0) {
609 strlcpy(box_ext_tmp_dir, path, sizeof(box_ext_tmp_dir));
610 box_ext_tmp_dir_owner = getpid();
611 return;
612 }
613 last_errno = errno;
614 if (last_errno != EEXIST) break;
615 }
616 rb_raise(rb_eLoadError, "can't create the temporary directory for Ruby Box extensions under %s: %s",
617 tmp_dir, strerror(last_errno));
618}
619
620enum copy_error_type {
621 COPY_ERROR_NONE,
622 COPY_ERROR_SRC_OPEN,
623 COPY_ERROR_DST_OPEN,
624 COPY_ERROR_SRC_READ,
625 COPY_ERROR_DST_WRITE,
626 COPY_ERROR_SRC_STAT,
627 COPY_ERROR_DST_CHMOD,
628 COPY_ERROR_SYSERR
629};
630
631static const char *
632copy_ext_file_error(char *message, size_t size, int copy_retvalue)
633{
634#ifdef _WIN32
635 int error = GetLastError();
636 char *p = message;
637 size_t len = snprintf(message, size, "%d: ", error);
638
639#define format_message(sublang) FormatMessage(\
640 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, \
641 NULL, error, MAKELANGID(LANG_NEUTRAL, (sublang)), \
642 message + len, size - len, NULL)
643 if (format_message(SUBLANG_ENGLISH_US) == 0)
644 format_message(SUBLANG_DEFAULT);
645 for (p = message + len; *p; p++) {
646 if (*p == '\n' || *p == '\r')
647 *p = ' ';
648 }
649#else
650 switch (copy_retvalue) {
651 case COPY_ERROR_SRC_OPEN:
652 strlcpy(message, "can't open the extension path", size);
653 break;
654 case COPY_ERROR_DST_OPEN:
655 strlcpy(message, "can't open the file to write", size);
656 break;
657 case COPY_ERROR_SRC_READ:
658 strlcpy(message, "failed to read the extension path", size);
659 break;
660 case COPY_ERROR_DST_WRITE:
661 strlcpy(message, "failed to write the extension path", size);
662 break;
663 case COPY_ERROR_SRC_STAT:
664 strlcpy(message, "failed to stat the extension path to copy permissions", size);
665 break;
666 case COPY_ERROR_DST_CHMOD:
667 strlcpy(message, "failed to set permissions to the copied extension path", size);
668 break;
669 case COPY_ERROR_SYSERR:
670 strlcpy(message, strerror(errno), size);
671 break;
672 case COPY_ERROR_NONE: /* shouldn't be called */
673 default:
674 rb_bug("unknown return value of copy_ext_file: %d", copy_retvalue);
675 }
676#endif
677 return message;
678}
679
680#ifndef _WIN32
681static enum copy_error_type
682copy_stream(int src_fd, int dst_fd)
683{
684 char buffer[1024];
685 ssize_t rsize;
686
687 while ((rsize = read(src_fd, buffer, sizeof(buffer))) != 0) {
688 if (rsize < 0) return COPY_ERROR_SRC_READ;
689 for (size_t written = 0; written < (size_t)rsize;) {
690 ssize_t wsize = write(dst_fd, buffer+written, rsize-written);
691 if (wsize < 0) return COPY_ERROR_DST_WRITE;
692 written += (size_t)wsize;
693 }
694 }
695 return COPY_ERROR_NONE;
696}
697#endif
698
699static enum copy_error_type
700copy_ext_file(const char *src_path, const char *dst_path)
701{
702#if defined(_WIN32)
703 WCHAR *w_src = rb_w32_mbstr_to_wstr(CP_UTF8, src_path, -1, NULL);
704 WCHAR *w_dst = rb_w32_mbstr_to_wstr(CP_UTF8, dst_path, -1, NULL);
705 if (!w_src || !w_dst) {
706 free(w_src);
707 free(w_dst);
708 rb_memerror();
709 }
710
711 enum copy_error_type rvalue = CopyFileW(w_src, w_dst, TRUE) ?
712 COPY_ERROR_NONE : COPY_ERROR_SYSERR;
713 free(w_src);
714 free(w_dst);
715 return rvalue;
716#else
717# ifdef O_BINARY
718 const int bin = O_BINARY;
719# else
720 const int bin = 0;
721# endif
722# ifdef O_CLOEXEC
723 const int cloexec = O_CLOEXEC;
724# else
725 const int cloexec = 0;
726# endif
727 const int src_fd = open(src_path, O_RDONLY|cloexec|bin);
728 if (src_fd < 0) return COPY_ERROR_SRC_OPEN;
729 if (!cloexec) rb_maygvl_fd_fix_cloexec(src_fd);
730
731 struct stat src_st;
732 if (fstat(src_fd, &src_st)) {
733 close(src_fd);
734 return COPY_ERROR_SRC_STAT;
735 }
736
737 const int dst_fd = open(dst_path, O_WRONLY|O_CREAT|O_EXCL|cloexec|bin, S_IRWXU);
738 if (dst_fd < 0) {
739 close(src_fd);
740 return COPY_ERROR_DST_OPEN;
741 }
742 if (!cloexec) rb_maygvl_fd_fix_cloexec(dst_fd);
743
744 enum copy_error_type ret = COPY_ERROR_NONE;
745
746 if (fchmod(dst_fd, src_st.st_mode & 0777)) {
747 ret = COPY_ERROR_DST_CHMOD;
748 goto done;
749 }
750
751 const size_t count_max = (SIZE_MAX >> 1) + 1;
752 (void)count_max;
753
754# ifdef HAVE_COPY_FILE_RANGE
755 for (;;) {
756 ssize_t written = copy_file_range(src_fd, NULL, dst_fd, NULL, count_max, 0);
757 if (written == 0) goto done;
758 if (written < 0) break;
759 }
760# endif
761# ifdef HAVE_FCOPYFILE
762 if (fcopyfile(src_fd, dst_fd, NULL, COPYFILE_DATA) == 0) {
763 goto done;
764 }
765# endif
766# ifdef USE_SENDFILE
767 for (;;) {
768 ssize_t written = sendfile(src_fd, dst_fd, NULL count_max);
769 if (written == 0) goto done;
770 if (written < 0) break;
771 }
772# endif
773 ret = copy_stream(src_fd, dst_fd);
774
775 done:
776 close(src_fd);
777 if (dst_fd >= 0) close(dst_fd);
778 if (ret != COPY_ERROR_NONE) unlink(dst_path);
779 return ret;
780#endif
781}
782
783#if defined __CYGWIN__ || defined DOSISH
784#define isdirsep(x) ((x) == '/' || (x) == '\\')
785#else
786#define isdirsep(x) ((x) == '/')
787#endif
788
789static const char *
790ext_basename(const char *path)
791{
792 const char *base = path;
793 for (const char *pos = path; *pos; pos++) {
794 if (isdirsep(*pos)) base = pos + 1;
795 }
796 return base;
797}
798
799static void
800box_ext_cleanup_mark(void *p)
801{
802 rb_gc_mark((VALUE)p);
803}
804
805static void
806box_ext_cleanup_free(void *p)
807{
808 VALUE path = (VALUE)p;
809 unlink(RSTRING_PTR(path));
810}
811
812static const rb_data_type_t box_ext_cleanup_type = {
813 "box_ext_cleanup",
814 {box_ext_cleanup_mark, box_ext_cleanup_free},
816};
817
818void
819rb_box_cleanup_local_extension(VALUE cleanup)
820{
821 void *p = DATA_PTR(cleanup);
822 DATA_PTR(cleanup) = NULL;
823#ifndef _WIN32
824 if (p) box_ext_cleanup_free(p);
825#endif
826 (void)p;
827}
828
829#if defined(_WIN32)
830struct box_local_ext_list {
831 struct box_local_ext_list *next;
832 HMODULE handle;
833};
834static struct box_local_ext_list *box_local_exts;
835#endif
836
837void
838rb_box_defer_unload_local_extension(void *handle)
839{
840#if defined(_WIN32)
841 /* A box-local copy of an extension DLL must stay loaded as long as
842 * objects created by it can be finalized; unloading is deferred to
843 * rb_box_unload_local_extensions after the objspace is destructed.
844 * The loaded copy cannot be deleted on Windows, so the file is also
845 * removed there instead of in box_ext_cleanup_free. */
846 struct box_local_ext_list *ext = malloc(sizeof(struct box_local_ext_list));
847 if (!ext) return;
848 ext->handle = (HMODULE)handle;
849 ext->next = box_local_exts;
850 box_local_exts = ext;
851#endif
852}
853
854void
855rb_box_unload_local_extensions(void)
856{
857#if defined(_WIN32)
858 struct box_local_ext_list *ext = box_local_exts;
859 box_local_exts = NULL;
860 while (ext) {
861 struct box_local_ext_list *next = ext->next;
862 WCHAR module_path[MAXPATHLEN];
863 DWORD len = GetModuleFileNameW(ext->handle, module_path, numberof(module_path));
864
865 FreeLibrary(ext->handle);
866 if (len > 0 && len < numberof(module_path)) DeleteFileW(module_path);
867 free(ext);
868 ext = next;
869 }
870#endif
871 if (box_ext_tmp_dir[0] && box_ext_tmp_dir_owner == getpid()) {
872 rmdir(box_ext_tmp_dir);
873 box_ext_tmp_dir[0] = '\0';
874 }
875}
876
877VALUE
878rb_box_local_extension(VALUE box_value, VALUE path, VALUE *cleanup)
879{
880 char ext_path[MAXPATHLEN];
881 int wrote;
882 const char *src_path = RSTRING_PTR(path);
883 rb_box_t *box = rb_get_box_t(box_value);
884
885 ensure_box_ext_tmp_dir();
886 wrote = snprintf(ext_path, sizeof(ext_path), "%s%s%ld_%lu_%s",
887 box_ext_tmp_dir, DIRSEP, box->box_id, box_ext_seq++, ext_basename(src_path));
888 if (wrote >= (int)sizeof(ext_path)) {
889 rb_raise(rb_eLoadError, "extension file path in the box is too long: %"PRIsVALUE, path);
890 }
891 VALUE new_path = rb_str_new_cstr(ext_path);
892 *cleanup = TypedData_Wrap_Struct(0, &box_ext_cleanup_type, NULL);
893 enum copy_error_type copy_error = copy_ext_file(src_path, ext_path);
894 if (copy_error) {
895 char message[1024];
896 copy_ext_file_error(message, sizeof(message), copy_error);
897 rb_raise(rb_eLoadError, "can't prepare the extension file for Ruby Box (%s from %"PRIsVALUE"): %s", ext_path, path, message);
898 }
899 DATA_PTR(*cleanup) = (void *)new_path;
900 return new_path;
901}
902
903static VALUE
904rb_box_load(int argc, VALUE *argv, VALUE box)
905{
906 VALUE fname, wrap;
907 rb_scan_args(argc, argv, "11", &fname, &wrap);
908
909 rb_vm_frame_flag_set_box_require(GET_EC());
910
911 return rb_load_entrypoint(fname, wrap);
912}
913
914static VALUE
915rb_box_require(VALUE box, VALUE fname)
916{
917 rb_vm_frame_flag_set_box_require(GET_EC());
918
919 return rb_require_string(fname);
920}
921
922static VALUE
923rb_box_require_relative(VALUE box, VALUE fname)
924{
925 rb_vm_frame_flag_set_box_require(GET_EC());
926
927 return rb_require_relative_entrypoint(fname);
928}
929
930static void
931initialize_master_box(void)
932{
933 rb_vm_t *vm = GET_VM();
934 rb_box_t *master = (rb_box_t *)rb_master_box();
935
936 master->load_path = rb_ary_new();
937 master->expanded_load_path = rb_ary_hidden_new(0);
938 master->load_path_snapshot = rb_ary_hidden_new(0);
939 master->load_path_check_cache = 0;
940 rb_define_singleton_method(master->load_path, "resolve_feature_path", rb_resolve_feature_path, 1);
941
942 master->loaded_features = rb_ary_new();
943 master->loaded_features_snapshot = rb_ary_hidden_new(0);
944 master->loaded_features_index = st_init_numtable();
945 master->load_unstable_depth = 0;
946 master->loaded_features_realpaths = rb_hash_new();
947 rb_obj_hide(master->loaded_features_realpaths);
948 master->loaded_features_realpath_map = rb_hash_new();
949 rb_obj_hide(master->loaded_features_realpath_map);
950
951 master->ruby_dln_libmap = rb_hash_new();
952 master->gvar_tbl = rb_hash_new();
953 master->classext_cow_classes = NULL; // classext CoW never happen on the master box
954
955 vm->master_box = master;
956
957 if (rb_box_available()) {
958 VALUE master_box, entry;
959 ID id_box_entry;
960 CONST_ID(id_box_entry, "__box_entry__");
961
962 master_box = rb_obj_alloc(rb_cBox);
963 RCLASS_SET_PRIME_CLASSEXT_WRITABLE(master_box, true);
964 RCLASS_SET_CONST_TBL(master_box, RCLASSEXT_CONST_TBL(RCLASS_EXT_PRIME(rb_cObject)), true);
965
966 master->box_id = box_generate_id();
967 master->box_object = master_box;
968
969 entry = TypedData_Wrap_Struct(rb_cBoxEntry, &rb_master_box_data_type, master);
970 rb_ivar_set(master_box, id_box_entry, entry);
971
972 rb_gc_register_mark_object(master_box);
973 rb_gc_register_mark_object(entry);
974 }
975 else {
976 master->box_id = 1;
977 master->box_object = Qnil;
978 }
979}
980
981static VALUE
982rb_box_eval(VALUE box_value, VALUE str)
983{
984 const rb_iseq_t *iseq;
985 const rb_box_t *box;
986
987 StringValue(str);
988
989 iseq = rb_iseq_compile_iseq(str, rb_str_new_cstr("eval"));
990 VM_ASSERT(iseq);
991
992 box = (const rb_box_t *)rb_get_box_t(box_value);
993
994 return rb_iseq_eval(iseq, box);
995}
996
997static int box_experimental_warned = 0;
998
999RUBY_EXTERN const char ruby_api_version_name[];
1000
1001static VALUE
1002box_value_initialize(bool root, bool user, bool optional)
1003{
1004 rb_box_t *box;
1005 VALUE box_value = rb_class_new_instance(0, NULL, rb_cBox);
1006
1007 VM_ASSERT(BOX_OBJ_P(box_value));
1008
1009 box = rb_get_box_t(box_value);
1010 box->box_object = box_value;
1011 box->is_root = root;
1012 box->is_user = user;
1013 box->is_optional = optional;
1014 return box_value;
1015}
1016
1017void
1018rb_initialize_mandatory_boxes(void)
1019{
1020 VALUE root_box_value, main_box_value;
1021 rb_vm_t *vm = GET_VM();
1022
1023 VM_ASSERT(rb_box_available());
1024
1025 if (!box_experimental_warned) {
1027 "Ruby::Box is experimental, and the behavior may change in the future!\n"
1028 "See https://docs.ruby-lang.org/en/%s/Ruby/Box.html for known issues, etc.",
1029 ruby_api_version_name);
1030 box_experimental_warned = 1;
1031 }
1032
1033 root_box_value = box_value_initialize(true, false, false);
1034 main_box_value = box_value_initialize(false, true, false);
1035
1036 rb_const_set(rb_cBox, rb_intern("ROOT"), root_box_value);
1037 rb_const_set(rb_cBox, rb_intern("MAIN"), main_box_value);
1038
1039 vm->root_box = root_box = rb_get_box_t(root_box_value);
1040 vm->main_box = main_box = rb_get_box_t(main_box_value);
1041
1042 // create the writable classext of ::Object explicitly to finalize the set of visible top-level constants
1043 RCLASS_EXT_WRITABLE_IN_BOX(rb_cObject, root_box);
1044 RCLASS_EXT_WRITABLE_IN_BOX(rb_cObject, main_box);
1045}
1046
1047static VALUE
1048rb_box_inspect(VALUE obj)
1049{
1050 rb_box_t *box;
1051 VALUE r;
1052 if (obj == Qfalse) {
1053 r = rb_str_new_cstr("#<Ruby::Box:master>");
1054 return r;
1055 }
1056 box = rb_get_box_t(obj);
1057 r = rb_sprintf("#<Ruby::Box:%ld", box->box_id);
1058 if (BOX_MASTER_P(box)) {
1059 rb_str_cat_cstr(r, ",master");
1060 }
1061 if (BOX_ROOT_P(box)) {
1062 rb_str_cat_cstr(r, ",root");
1063 }
1064 if (BOX_USER_P(box)) {
1065 rb_str_cat_cstr(r, ",user");
1066 }
1067 if (BOX_MAIN_P(box)) {
1068 rb_str_cat_cstr(r, ",main");
1069 }
1070 else if (BOX_OPTIONAL_P(box)) {
1071 rb_str_cat_cstr(r, ",optional");
1072 }
1073 rb_str_cat_cstr(r, ">");
1074 return r;
1075}
1076
1077static VALUE
1078rb_box_loading_func(int argc, VALUE *argv, VALUE _self)
1079{
1080 rb_vm_frame_flag_set_box_require(GET_EC());
1081 return rb_call_super(argc, argv);
1082}
1083
1084static void
1085box_define_loader_method(const char *name)
1086{
1087 rb_define_private_method(rb_mBoxLoader, name, rb_box_loading_func, -1);
1088 rb_define_singleton_method(rb_mBoxLoader, name, rb_box_loading_func, -1);
1089}
1090
1091void
1092Init_master_box(void)
1093{
1094 master_box->loading_table = st_init_strtable();
1095}
1096
1097void
1098Init_enable_box(void)
1099{
1100 const char *env = getenv("RUBY_BOX");
1101 if (env && strlen(env) == 1 && env[0] == '1') {
1102 ruby_box_enabled = true;
1103 }
1104 else {
1105 ruby_box_init_done = true;
1106 }
1107}
1108
1109/* :nodoc: */
1110static VALUE
1111rb_box_s_master(VALUE recv)
1112{
1113 return master_box->box_object;
1114}
1115
1116/* :nodoc: */
1117static VALUE
1118rb_box_s_root(VALUE recv)
1119{
1120 return root_box->box_object;
1121}
1122
1123/* :nodoc: */
1124static VALUE
1125rb_box_s_main(VALUE recv)
1126{
1127 return main_box->box_object;
1128}
1129
1130/* :nodoc: */
1131static VALUE
1132rb_box_master_p(VALUE box_value)
1133{
1134 const rb_box_t *box = (const rb_box_t *)rb_get_box_t(box_value);
1135 return RBOOL(BOX_MASTER_P(box));
1136}
1137
1138/* :nodoc: */
1139static VALUE
1140rb_box_root_p(VALUE box_value)
1141{
1142 const rb_box_t *box = (const rb_box_t *)rb_get_box_t(box_value);
1143 return RBOOL(BOX_ROOT_P(box));
1144}
1145
1146/* :nodoc: */
1147static VALUE
1148rb_box_main_p(VALUE box_value)
1149{
1150 const rb_box_t *box = (const rb_box_t *)rb_get_box_t(box_value);
1151 return RBOOL(BOX_MAIN_P(box));
1152}
1153
1154#if RUBY_DEBUG
1155
1156static const char *
1157classname(VALUE klass)
1158{
1159 VALUE p;
1160 if (!klass) {
1161 return "Qfalse";
1162 }
1163 p = RCLASSEXT_CLASSPATH(RCLASS_EXT_PRIME(klass));
1164 if (RTEST(p))
1165 return RSTRING_PTR(p);
1166 if (RB_TYPE_P(klass, T_CLASS) || RB_TYPE_P(klass, T_MODULE) || RB_TYPE_P(klass, T_ICLASS))
1167 return "AnyClassValue";
1168 return "NonClassValue";
1169}
1170
1171static enum rb_id_table_iterator_result
1172dump_classext_methods_i(ID mid, VALUE _val, void *data)
1173{
1174 VALUE ary = (VALUE)data;
1175 rb_ary_push(ary, rb_id2str(mid));
1176 return ID_TABLE_CONTINUE;
1177}
1178
1179static enum rb_id_table_iterator_result
1180dump_classext_constants_i(ID mid, VALUE _val, void *data)
1181{
1182 VALUE ary = (VALUE)data;
1183 rb_ary_push(ary, rb_id2str(mid));
1184 return ID_TABLE_CONTINUE;
1185}
1186
1187static void
1188dump_classext_i(rb_classext_t *ext, bool is_prime, VALUE _recv, void *data)
1189{
1190 char buf[4096];
1191 struct rb_id_table *tbl;
1192 VALUE ary, res = (VALUE)data;
1193
1194 snprintf(buf, 4096, "Ruby::Box %ld:%s classext %p\n",
1195 RCLASSEXT_BOX(ext)->box_id, is_prime ? " prime" : "", (void *)ext);
1196 rb_str_cat_cstr(res, buf);
1197
1198 snprintf(buf, 2048, " Super: %s\n", classname(RCLASSEXT_SUPER(ext)));
1199 rb_str_cat_cstr(res, buf);
1200
1201 tbl = RCLASSEXT_M_TBL(ext);
1202 if (tbl) {
1203 ary = rb_ary_new_capa((rb_len_t)rb_id_table_size(tbl));
1204 rb_id_table_foreach(RCLASSEXT_M_TBL(ext), dump_classext_methods_i, (void *)ary);
1205 rb_ary_sort_bang(ary);
1206 snprintf(buf, 4096, " Methods(%"PRIdLEN"): ", RARRAY_LEN(ary));
1207 rb_str_cat_cstr(res, buf);
1208 rb_str_concat(res, rb_ary_join(ary, rb_str_new_cstr(",")));
1209 rb_str_cat_cstr(res, "\n");
1210 }
1211 else {
1212 rb_str_cat_cstr(res, " Methods(0): .\n");
1213 }
1214
1215 tbl = RCLASSEXT_CONST_TBL(ext);
1216 if (tbl) {
1217 ary = rb_ary_new_capa((rb_len_t)rb_id_table_size(tbl));
1218 rb_id_table_foreach(tbl, dump_classext_constants_i, (void *)ary);
1219 rb_ary_sort_bang(ary);
1220 snprintf(buf, 4096, " Constants(%"PRIdLEN"): ", RARRAY_LEN(ary));
1221 rb_str_cat_cstr(res, buf);
1222 rb_str_concat(res, rb_ary_join(ary, rb_str_new_cstr(",")));
1223 rb_str_cat_cstr(res, "\n");
1224 }
1225 else {
1226 rb_str_cat_cstr(res, " Constants(0): .\n");
1227 }
1228}
1229
1230/* :nodoc: */
1231static VALUE
1232rb_f_dump_classext(VALUE recv, VALUE klass)
1233{
1234 /*
1235 * The desired output String value is:
1236 * Class: 0x88800932 (String) [singleton]
1237 * Prime classext box(2,main), readable(t), writable(f)
1238 * Non-prime classexts: 3
1239 * Box 2: prime classext 0x88800933
1240 * Super: Object
1241 * Methods(43): aaaaa, bbbb, cccc, dddd, eeeee, ffff, gggg, hhhhh, ...
1242 * Constants(12): FOO, Bar, ...
1243 * Box 5: classext 0x88800934
1244 * Super: Object
1245 * Methods(43): aaaaa, bbbb, cccc, dddd, eeeee, ffff, gggg, hhhhh, ...
1246 * Constants(12): FOO, Bar, ...
1247 */
1248 char buf[2048];
1249 VALUE res;
1250 const rb_classext_t *ext;
1251 const rb_box_t *box;
1252 st_table *classext_tbl;
1253
1254 if (!(RB_TYPE_P(klass, T_CLASS) || RB_TYPE_P(klass, T_MODULE))) {
1255 snprintf(buf, 2048, "Non-class/module value: %p (%s)\n", (void *)klass, rb_type_str(BUILTIN_TYPE(klass)));
1256 return rb_str_new_cstr(buf);
1257 }
1258
1259 if (RB_TYPE_P(klass, T_CLASS)) {
1260 snprintf(buf, 2048, "Class: %p (%s)%s\n",
1261 (void *)klass, classname(klass), RCLASS_SINGLETON_P(klass) ? " [singleton]" : "");
1262 }
1263 else {
1264 snprintf(buf, 2048, "Module: %p (%s)\n", (void *)klass, classname(klass));
1265 }
1266 res = rb_str_new_cstr(buf);
1267
1268 ext = RCLASS_EXT_PRIME(klass);
1269 box = RCLASSEXT_BOX(ext);
1270 snprintf(buf, 2048, "Prime classext box(%ld,%s), readable(%s), writable(%s)\n",
1271 box->box_id,
1272 BOX_MASTER_P(box) ? "master" : (BOX_ROOT_P(box) ? "root" : (BOX_MAIN_P(box) ? "main" : "optional")),
1273 RCLASS_PRIME_CLASSEXT_READABLE_P(klass) ? "t" : "f",
1274 RCLASS_PRIME_CLASSEXT_WRITABLE_P(klass) ? "t" : "f");
1275 rb_str_cat_cstr(res, buf);
1276
1277 classext_tbl = RCLASS_CLASSEXT_TBL(klass);
1278 if (!classext_tbl) {
1279 rb_str_cat_cstr(res, "Non-prime classexts: 0\n");
1280 }
1281 else {
1282 snprintf(buf, 2048, "Non-prime classexts: %zu\n", st_table_size(classext_tbl));
1283 rb_str_cat_cstr(res, buf);
1284 }
1285
1286 rb_class_classext_foreach(klass, dump_classext_i, (void *)res);
1287
1288 return res;
1289}
1290
1291#endif /* RUBY_DEBUG */
1292
1293/*
1294 * Document-class: Ruby::Box
1295 *
1296 * :markup: markdown
1297 * # Ruby Box - Ruby's in-process separation of Classes and Modules
1298 *
1299 * Ruby Box is designed to provide separated spaces in a Ruby process, to isolate application code, libraries and monkey patches.
1300 *
1301 * ## Known issues
1302 *
1303 * * Experimental warning is shown when ruby starts with `RUBY_BOX=1` (specify `-W:no-experimental` option to hide it)
1304 * * Installing native extensions may fail under `RUBY_BOX=1` because of stack level too deep in extconf.rb
1305 * * `require 'active_support/core_ext'` may fail under `RUBY_BOX=1`
1306 * * Defined methods in a box may not be referred by built-in methods written in Ruby
1307 *
1308 * ## TODOs
1309 *
1310 * * Add the loaded box on iseq to check if another box tries running the iseq (add a field only when VM_CHECK_MODE?)
1311 * * Assign its own TOPLEVEL_BINDING in boxes
1312 * * Fix calling `warn` in boxes to refer `$VERBOSE` and `Warning.warn` in the box
1313 * * Make an internal data container class `Ruby::Box::Entry` invisible
1314 * * More test cases about `$LOAD_PATH` and `$LOADED_FEATURES`
1315 *
1316 * ## How to use
1317 *
1318 * ### Enabling Ruby Box
1319 *
1320 * First, an environment variable should be set at the ruby process bootup: `RUBY_BOX=1`.
1321 * The only valid value is `1` to enable Ruby Box. Other values (or unset `RUBY_BOX`) means disabling Ruby Box. And setting the value after Ruby program starts doesn't work.
1322 *
1323 * ### Using Ruby Box
1324 *
1325 * `Ruby::Box` class is the entrypoint of Ruby Box.
1326 *
1327 * ```ruby
1328 * box = Ruby::Box.new
1329 * box.require('something') # or require_relative, load
1330 * ```
1331 *
1332 * The required file (either .rb or .so/.dll/.bundle) is loaded in the box (`box` here). The required/loaded files from `something` will be loaded in the box recursively.
1333 *
1334 * ```ruby
1335 * # something.rb
1336 *
1337 * X = 1
1338 *
1339 * class Something
1340 * def self.x = X
1341 * def x = ::X
1342 * end
1343 * ```
1344 *
1345 * Classes/modules, those methods and constants defined in the box can be accessed via `box` object.
1346 *
1347 * ```ruby
1348 * X = 2
1349 * p X # 2
1350 * p ::X # 2
1351 * p box::Something.x # 1
1352 * p box::X # 1
1353 * ```
1354 *
1355 * Instance methods defined in the box also run with definitions in the box.
1356 *
1357 * ```ruby
1358 * s = box::Something.new
1359 *
1360 * p s.x # 1
1361 * ```
1362 *
1363 * ## Specifications
1364 *
1365 * ### Ruby Box types
1366 *
1367 * There are three box types:
1368 *
1369 * * Master box
1370 * * Root box
1371 * * User boxes
1372 *
1373 * Ruby bootstrap runs in the root box, and a
1374 *
1375 * There is the root box, just a single box in a Ruby process. All builtin classes/modules are defined and run in the root box. (See "Builtin classes and modules".)
1376 *
1377 * User boxes are to run user-written programs and libraries loaded from user programs. The user's main program (specified by the `ruby` command line argument) is executed in the "main" box, which is a user box automatically created at the end of Ruby's bootstrap. The files specified with `-r` command line option will be required in the main box.
1378 *
1379 * Calling `Ruby::Box.new` creates an "optional" box (a user, non-main box), technically equal to the main box.
1380 *
1381 * Ruby also has the master box. The master box is the "master copy" of all boxes. Boxes will be created as a copy of the master box. The master box is only for the source of box copies, and no code runs in the master box.
1382 *
1383 *
1384 * ```
1385 * [master]
1386 * |
1387 * |----[root]
1388 * |
1389 * |----[main]
1390 * |
1391 * |----[user box 1]
1392 * |
1393 * |----[user box 2]
1394 * ...
1395 * ```
1396 *
1397 * ### Ruby Box class and instances
1398 *
1399 * `Ruby::Box` is a class, as a subclass of `Module`. `Ruby::Box` instances are a kind of `Module`.
1400 *
1401 * ### Classes and modules defined in boxes
1402 *
1403 * The classes and modules, newly defined in a box `box`, are accessible via `box`. For example, if a class `A` is defined in `box`, it is accessible as `box::A` from outside of the box.
1404 *
1405 * In the box `box`, `A` can be referred to as `A` (and `::A`).
1406 *
1407 * ### Built-in classes and modules reopened in boxes
1408 *
1409 * In boxes, builtin classes/modules are visible and can be reopened. Those classes/modules can be reopened using `class` or `module` clauses, and class/module definitions can be changed.
1410 *
1411 * The changed definitions are visible only in the box. In other boxes, builtin classes/modules and those instances work without changed definitions.
1412 *
1413 * ```ruby
1414 * # in foo.rb
1415 * class String
1416 * BLANK_PATTERN = /\A\s*\z/
1417 * def blank?
1418 * self.match?(BLANK_PATTERN)
1419 * end
1420 * end
1421 *
1422 * module Foo
1423 * def self.foo = "foo"
1424 *
1425 * def self.foo_is_blank?
1426 * foo.blank?
1427 * end
1428 * end
1429 *
1430 * Foo.foo.blank? #=> false
1431 * "foo".blank? #=> false
1432 *
1433 * # in main.rb
1434 * box = Ruby::Box.new
1435 * box.require_relative('foo')
1436 *
1437 * box::Foo.foo_is_blank? #=> false (#blank? called in box)
1438 *
1439 * "foo".blank? # NoMethodError
1440 * String::BLANK_PATTERN # NameError
1441 * ```
1442 *
1443 * The main box and `box` above are different boxes, so monkey patches in main are also invisible in `box`.
1444 *
1445 * ### Builtin classes and modules
1446 *
1447 * In the box context, "builtin" classes and modules are classes and modules:
1448 *
1449 * * Accessible without any `require` calls in user scripts
1450 * * Defined before any user program start running
1451 *
1452 * Hereafter, "builtin classes and modules" will be referred to as just "builtin classes".
1453 *
1454 * Builtin classes and modules are loaded in all boxes, and run in the root box.
1455 *
1456 * ### Exceptional non-built-in classes/modules
1457 *
1458 * There are some exceptional classes/modules that are enabled in default, but aren't built-in classes. Those classes/modules are:
1459 *
1460 * * `RubyGems`
1461 * * `ErrorHighlight`
1462 * * `DidYouMean`
1463 * * `SyntaxSuggest`
1464 *
1465 * Those classes/modules (part of default gems) are loaded in each boxes independently. If a user box's code calls RubyGems, it calls the RubyGems inside the box itself, instead of the root box's one.
1466 *
1467 * ### Builtin classes referred via box objects
1468 *
1469 * Builtin classes in a box `box` can be referred from other boxes. For example, `box::String` is a valid reference, and `String` and `box::String` are identical (`String == box::String`, `String.object_id == box::String.object_id`).
1470 *
1471 * `box::String`-like reference returns just a `String` in the current box, so its definition is `String` in the box, not in `box`.
1472 *
1473 * ```ruby
1474 * # foo.rb
1475 * class String
1476 * def self.foo = "foo"
1477 * end
1478 *
1479 * # main.rb
1480 * box = Ruby::Box.new
1481 * box.require_relative('foo')
1482 *
1483 * box::String.foo # NoMethodError
1484 * ```
1485 *
1486 * ### Class instance variables, class variables, constants
1487 *
1488 * Builtin classes can have different sets of class instance variables, class variables and constants between boxes.
1489 *
1490 * ```ruby
1491 * # foo.rb
1492 * class Array
1493 * @v = "foo"
1494 * @@v = "_foo_"
1495 * V = "FOO"
1496 * end
1497 *
1498 * Array.instance_variable_get(:@v) #=> "foo"
1499 * Array.class_variable_get(:@@v) #=> "_foo_"
1500 * Array.const_get(:V) #=> "FOO"
1501 *
1502 * # main.rb
1503 * box = Ruby::Box.new
1504 * box.require_relative('foo')
1505 *
1506 * Array.instance_variable_get(:@v) #=> nil
1507 * Array.class_variable_get(:@@v) # NameError
1508 * Array.const_get(:V) # NameError
1509 * ```
1510 *
1511 * ### Global variables
1512 *
1513 * In boxes, changes on global variables are also isolated in the boxes. Changes on global variables in a box are visible/applied only in the box.
1514 *
1515 * ```ruby
1516 * # foo.rb
1517 * $foo = "foo"
1518 * $VERBOSE = nil
1519 *
1520 * puts "This appears: '#{$foo}'"
1521 *
1522 * # main.rb
1523 * p $foo #=> nil
1524 * p $VERBOSE #=> false
1525 *
1526 * box = Ruby::Box.new
1527 * box.require_relative('foo') # "This appears: 'foo'"
1528 *
1529 * p $foo #=> nil
1530 * p $VERBOSE #=> false
1531 * ```
1532 *
1533 * ### Top level constants
1534 *
1535 * Usually, top level constants are defined as constants of `Object`. In boxes, top level constants are constants of `Object` in the box. And the box object `box`'s constants are strictly equal to constants of `Object`.
1536 *
1537 * ```ruby
1538 * # foo.rb
1539 * FOO = 100
1540 *
1541 * FOO #=> 100
1542 * Object::FOO #=> 100
1543 *
1544 * # main.rb
1545 * box = Ruby::Box.new
1546 * box.require_relative('foo')
1547 *
1548 * box::FOO #=> 100
1549 *
1550 * FOO # NameError
1551 * Object::FOO # NameError
1552 * ```
1553 *
1554 * ### Top level methods
1555 *
1556 * Top level methods are private instance methods of `Object`, in each box.
1557 *
1558 * ```ruby
1559 * # foo.rb
1560 * def yay = "foo"
1561 *
1562 * class Foo
1563 * def self.say = yay
1564 * end
1565 *
1566 * Foo.say #=> "foo"
1567 * yay #=> "foo"
1568 *
1569 * # main.rb
1570 * box = Ruby::Box.new
1571 * box.require_relative('foo')
1572 *
1573 * box::Foo.say #=> "foo"
1574 *
1575 * yay # NoMethodError
1576 * ```
1577 *
1578 * There is no way to expose top level methods in boxes to others.
1579 * (See "Expose top level methods as a method of the box object" in "Discussions" section below)
1580 *
1581 * ### Ruby Box scopes
1582 *
1583 * Ruby Box works in file scope. One `.rb` file runs in a single box.
1584 *
1585 * Once a file is loaded in a box `box`, all methods/procs defined/created in the file run in `box`.
1586 *
1587 * ### Utility methods
1588 *
1589 * Several methods are available for trying/testing Ruby Box.
1590 *
1591 * * `Ruby::Box.current` returns the current box
1592 * * `Ruby::Box.enabled?` returns true/false to represent `RUBY_BOX=1` is specified or not
1593 * * `Ruby::Box.root` returns the root box
1594 * * `Ruby::Box.main` returns the main box
1595 * * `Ruby::Box#eval` evaluates a Ruby code (String) in the receiver box, just like calling `#load` with a file
1596 *
1597 * ## Implementation details
1598 *
1599 * ### ISeq inline method/constant cache
1600 *
1601 * As described above in "Ruby Box scopes", an ".rb" file runs in a box. So method/constant resolution will be done in a box consistently.
1602 *
1603 * That means ISeq inline caches work well even with boxes. Otherwise, it's a bug.
1604 *
1605 * ### Method call global cache (gccct)
1606 *
1607 * `rb_funcall()` C function refers to the global cc cache table (gccct), and the cache key is calculated with the current box.
1608 *
1609 * So, `rb_funcall()` calls have a performance penalty when Ruby Box is enabled.
1610 *
1611 * ### Current box and loading box
1612 *
1613 * The current box is the box that the executing code is in. `Ruby::Box.current` returns the current box object.
1614 *
1615 * The loading box is an internally managed box to determine the box to load newly required/loaded files. For example, `box` is the loading box when `box.require("foo")` is called.
1616 *
1617 * ## Discussions
1618 *
1619 * ### More builtin methods written in Ruby
1620 *
1621 * If Ruby Box is enabled by default, builtin methods can be written in Ruby because it can't be overridden by users' monkey patches. Builtin Ruby methods can be JIT-ed, and it could bring performance reward.
1622 *
1623 * ### Monkey patching methods called by builtin methods
1624 *
1625 * Builtin methods sometimes call other builtin methods. For example, `Hash#map` calls `Hash#each` to retrieve entries to be mapped. Without Ruby Box, Ruby users can overwrite `Hash#each` and expect the behavior change of `Hash#map` as a result.
1626 *
1627 * But with boxes, `Hash#map` runs in the root box. Ruby users can define `Hash#each` only in user boxes, so users cannot change `Hash#map`'s behavior in this case. To achieve it, users should override both`Hash#map` and `Hash#each` (or only `Hash#map`).
1628 *
1629 * It is a breaking change.
1630 *
1631 * Users can define methods using `Ruby::Box.root.eval(...)`, but it's clearly not ideal API.
1632 *
1633 * ### Assigning values to global variables used by builtin methods
1634 *
1635 * Similar to monkey patching methods, global variables assigned in a box is separated from the root box. Methods defined in the root box referring a global variable can't find the re-assigned one.
1636 *
1637 * ### Context of `$LOAD_PATH` and `$LOADED_FEATURES`
1638 *
1639 * Global variables `$LOAD_PATH` and `$LOADED_FEATURES` control `require` method behaviors. So those variables are determined by the loading box instead of the current box.
1640 *
1641 * This could potentially conflict with the user's expectations. We should find the solution.
1642 *
1643 * ### Expose top level methods as a method of the box object
1644 *
1645 * Currently, top level methods in boxes are not accessible from outside of the box. But there might be a use case to call other box's top level methods.
1646 *
1647 * ### Separate `cc_tbl` and `callable_m_tbl`, `cvc_tbl` for less classext CoW
1648 *
1649 * The fields of `rb_classext_t` contains several cache(-like) data, `cc_tbl`(callcache table), `callable_m_tbl`(table of resolved complemented methods) and `cvc_tbl`(class variable cache table).
1650 *
1651 * The classext CoW is triggered when the contents of `rb_classext_t` are changed, including `cc_tbl`, `callable_m_tbl`, and `cvc_tbl`. But those three tables are changed by just calling methods or referring class variables. So, currently, classext CoW is triggered much more times than the original expectation.
1652 *
1653 * If we can move those three tables outside of `rb_classext_t`, the number of copied `rb_classext_t` will be much less than the current implementation.
1654 */
1655void
1656Init_Box(void)
1657{
1658 tmp_dir = system_tmpdir();
1659 tmp_dir_has_dirsep = (strcmp(tmp_dir + (strlen(tmp_dir) - strlen(DIRSEP)), DIRSEP) == 0);
1660
1661 VALUE mRuby = rb_define_module("Ruby");
1662
1663 rb_cBox = rb_define_class_under(mRuby, "Box", rb_cModule);
1664 rb_define_method(rb_cBox, "initialize", box_initialize, 0);
1665
1666 /* :nodoc: */
1667 rb_cBoxEntry = rb_define_class_under(rb_cBox, "Entry", rb_cObject);
1668 rb_define_alloc_func(rb_cBoxEntry, rb_box_entry_alloc);
1669
1670 initialize_master_box();
1671
1672 /* :nodoc: */
1673 rb_mBoxLoader = rb_define_module_under(rb_cBox, "Loader");
1674 box_define_loader_method("require");
1675 box_define_loader_method("require_relative");
1676 box_define_loader_method("load");
1677
1678 if (rb_box_available()) {
1679 rb_include_module(rb_cObject, rb_mBoxLoader);
1680
1681 rb_define_singleton_method(rb_cBox, "master", rb_box_s_master, 0);
1682 rb_define_singleton_method(rb_cBox, "root", rb_box_s_root, 0);
1683 rb_define_singleton_method(rb_cBox, "main", rb_box_s_main, 0);
1684 rb_define_method(rb_cBox, "master?", rb_box_master_p, 0);
1685 rb_define_method(rb_cBox, "root?", rb_box_root_p, 0);
1686 rb_define_method(rb_cBox, "main?", rb_box_main_p, 0);
1687
1688#if RUBY_DEBUG
1689 rb_define_global_function("dump_classext", rb_f_dump_classext, 1);
1690#endif
1691 }
1692
1693 rb_define_singleton_method(rb_cBox, "enabled?", rb_box_s_getenabled, 0);
1694 rb_define_singleton_method(rb_cBox, "current", rb_box_s_current, 0);
1695
1696 rb_define_method(rb_cBox, "load_path", rb_box_load_path, 0);
1697 rb_define_method(rb_cBox, "load", rb_box_load, -1);
1698 rb_define_method(rb_cBox, "require", rb_box_require, 1);
1699 rb_define_method(rb_cBox, "require_relative", rb_box_require_relative, 1);
1700 rb_define_method(rb_cBox, "eval", rb_box_eval, 1);
1701
1702 rb_define_method(rb_cBox, "inspect", rb_box_inspect, 0);
1703}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define RUBY_EXTERN
Declaration of externally visible global variables.
Definition dllexport.h:45
Ruby-level global variables / constants, visible from C.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1737
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3025
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3068
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 xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define T_NONE
Old name of RUBY_T_NONE.
Definition value_type.h:74
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:474
VALUE rb_eLoadError
LoadError exception.
Definition error.c:1475
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
@ RB_WARN_CATEGORY_EXPERIMENTAL
Warning is for experimental features.
Definition error.h:51
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2264
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2305
VALUE rb_cBox
Ruby::Box class.
Definition box.c:38
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_class_new_instance_pass_kw(int argc, const VALUE *argv, VALUE klass)
Identical to rb_class_new_instance(), except it passes the passed keywords if any to the #initialize ...
Definition object.c:2282
VALUE rb_cModule
Module class.
Definition object.c:61
VALUE rb_call_super(int argc, const VALUE *argv)
This resembles ruby's super.
Definition vm_eval.c:365
void rb_memerror(void)
Triggers out-of-memory error.
Definition gc.c:6674
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_new(void)
Allocates a new, empty 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_sort_bang(VALUE ary)
Destructively sorts the passed array in-place, according to each elements' <=> result.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1646
VALUE rb_require_string(VALUE feature)
Finds and loads the given feature, if absent.
Definition load.c:1750
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
Definition string.c:4189
#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
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2168
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:4018
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
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
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
Definition pid_t.h:38
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:122
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
#define DATA_PTR(obj)
Convenient casting macro for backward compatibility.
Definition rtypeddata.h:439
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:557
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define RTEST
This is an old name of RB_TEST.
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 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