Ruby 4.1.0dev (2026-11-27 revision 0d399335b733776187e43a783e5f950c18ad881c)
variable.c (0d399335b733776187e43a783e5f950c18ad881c)
1/**********************************************************************
2
3 variable.c -
4
5 $Author$
6 created at: Tue Apr 19 23:55:15 JST 1994
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
11
12**********************************************************************/
13
14#include "ruby/internal/config.h"
15#include <stddef.h>
17#include "ccan/list/list.h"
18#include "constant.h"
19#include "debug_counter.h"
20#include "id.h"
21#include "id_table.h"
22#include "internal.h"
23#include "internal/box.h"
24#include "internal/class.h"
25#include "internal/compilers.h"
26#include "internal/error.h"
27#include "internal/eval.h"
28#include "eval_intern.h"
29#include "internal/hash.h"
30#include "internal/object.h"
31#include "internal/gc.h"
32#include "internal/ractor.h"
33#include "internal/re.h"
34#include "internal/string.h"
35#include "internal/struct.h"
36#include "internal/symbol.h"
37#include "internal/thread.h"
38#include "internal/variable.h"
39#include "internal/vm.h"
40#include "ruby/encoding.h"
41#include "ruby/st.h"
42#include "ruby/util.h"
43#include "shape.h"
44#include "symbol.h"
45#include "variable.h"
46#include "vm_core.h"
47#include "ractor_core.h"
48#include "vm_sync.h"
49
50RUBY_EXTERN rb_serial_t ruby_vm_global_cvar_state;
51#define GET_GLOBAL_CVAR_STATE() (ruby_vm_global_cvar_state)
52
53typedef void rb_gvar_compact_t(void *var);
54
55static struct rb_id_table *rb_global_tbl;
56
57// This hash table maps file paths to loadable features. We use this to track
58// autoload state until it's no longer needed.
59// feature (file path) => struct autoload_data
60static VALUE autoload_features;
61
62// This mutex is used to protect autoloading state. We use a global mutex which
63// is held until a per-feature mutex can be created. This ensures there are no
64// race conditions relating to autoload state.
65static VALUE autoload_mutex;
66
67static void check_before_mod_set(VALUE, ID, VALUE, const char *);
68static void setup_const_entry(rb_const_entry_t *, VALUE, VALUE, rb_const_flag_t);
69static VALUE rb_const_search(VALUE klass, ID id, int exclude, int recurse, int visibility, VALUE *found_in);
70static st_table *generic_fields_tbl_;
71
72/* Mutex guarding the single global generic_fields table (all hosts, every Ractor). A
73 * dedicated mutex (vm->ractor.generic_fields_lock) because a local GC's marking reads
74 * the table and must not wait for the VM lock: joining a barrier mid-mark would expose
75 * a half-collected heap. The global GC's weak pass cleans the table under the barrier,
76 * lock-free. Sections that may allocate disable GC first: no self-re-entry. */
77
78typedef int rb_ivar_foreach_callback_func(ID key, VALUE val, st_data_t arg);
79static void rb_field_foreach(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only);
80
81void
82rb_generic_fields_lock_atfork(void)
83{
84 /* Another thread may have held it at fork time, so rebuild it in the child. */
85 rb_native_mutex_initialize(&GET_VM()->ractor.generic_fields_lock);
86}
87
88void
89Init_var_tables(void)
90{
91 rb_global_tbl = rb_id_table_create(0);
92 generic_fields_tbl_ = st_init_numtable();
93
94 autoload_mutex = rb_mutex_new();
95 rb_obj_hide(autoload_mutex);
96 rb_vm_register_global_object(autoload_mutex);
97
98 autoload_features = rb_ident_hash_new();
99 rb_obj_hide(autoload_features);
100 rb_vm_register_global_object(autoload_features);
101}
102
103static inline bool
104rb_namespace_p(VALUE obj)
105{
106 if (RB_SPECIAL_CONST_P(obj)) return false;
107 switch (RB_BUILTIN_TYPE(obj)) {
108 case T_MODULE: case T_CLASS: return true;
109 default: break;
110 }
111 return false;
112}
113
124static VALUE
125classname(VALUE klass, bool *permanent)
126{
127 *permanent = false;
128
129 VALUE classpath = RCLASS_CLASSPATH(klass);
130 if (classpath == 0) return Qnil;
131
132 *permanent = RCLASS_PERMANENT_CLASSPATH_P(klass);
133
134 return classpath;
135}
136
137VALUE
138rb_mod_name0(VALUE klass, bool *permanent)
139{
140 return classname(klass, permanent);
141}
142
143/*
144 * call-seq:
145 * mod.name -> string or nil
146 *
147 * Returns the name of the module <i>mod</i>. Returns +nil+ for anonymous modules.
148 */
149
150VALUE
152{
153 // YJIT needs this function to not allocate.
154 bool permanent;
155 return classname(mod, &permanent);
156}
157
158// Similar to logic in rb_mod_const_get().
159static bool
160is_constant_path(VALUE name)
161{
162 const char *path = RSTRING_PTR(name);
163 const char *pend = RSTRING_END(name);
164 rb_encoding *enc = rb_enc_get(name);
165
166 const char *p = path;
167
168 if (p >= pend || !*p) {
169 return false;
170 }
171
172 while (p < pend) {
173 if (p + 2 <= pend && p[0] == ':' && p[1] == ':') {
174 p += 2;
175 }
176
177 const char *pbeg = p;
178 while (p < pend && *p != ':') p++;
179
180 if (pbeg == p) return false;
181
182 if (rb_enc_symname_type(pbeg, p - pbeg, enc, 0) != ID_CONST) {
183 return false;
184 }
185 }
186
187 return true;
188}
189
191 VALUE names;
192 ID last;
193};
194
195static VALUE build_const_path(VALUE head, ID tail);
196static void set_sub_temporary_name_foreach(VALUE mod, struct sub_temporary_name_args *args, VALUE name);
197
198static VALUE
199set_sub_temporary_name_recursive(VALUE mod, VALUE data, int recursive)
200{
201 if (recursive) return Qfalse;
202
203 struct sub_temporary_name_args *args = (void *)data;
204 VALUE name = 0;
205 if (args->names) {
206 name = build_const_path(rb_ary_last(0, 0, args->names), args->last);
207 }
208 set_sub_temporary_name_foreach(mod, args, name);
209 return Qtrue;
210}
211
212static VALUE
213set_sub_temporary_name_topmost(VALUE mod, VALUE data, int recursive)
214{
215 if (recursive) return Qfalse;
216
217 struct sub_temporary_name_args *args = (void *)data;
218 VALUE name = args->names;
219 if (name) {
220 args->names = rb_ary_hidden_new(0);
221 }
222 set_sub_temporary_name_foreach(mod, args, name);
223 return Qtrue;
224}
225
226static enum rb_id_table_iterator_result
227set_sub_temporary_name_i(ID id, VALUE val, void *data)
228{
229 val = ((rb_const_entry_t *)val)->value;
230 if (rb_namespace_p(val) && !RCLASS_PERMANENT_CLASSPATH_P(val)) {
231 VALUE arg = (VALUE)data;
232 struct sub_temporary_name_args *args = data;
233 args->last = id;
234 rb_exec_recursive_paired(set_sub_temporary_name_recursive, val, arg, arg);
235 }
236 return ID_TABLE_CONTINUE;
237}
238
239static void
240set_sub_temporary_name_foreach(VALUE mod, struct sub_temporary_name_args *args, VALUE name)
241{
242 RCLASS_WRITE_CLASSPATH(mod, name, FALSE);
243 struct rb_id_table *tbl = RCLASS_CONST_TBL(mod);
244 if (!tbl) return;
245 if (!name) {
246 rb_id_table_foreach(tbl, set_sub_temporary_name_i, args);
247 }
248 else {
249 rb_len_t names_len = RARRAY_LEN(args->names); // paranoiac check?
250 rb_ary_push(args->names, name);
251 rb_id_table_foreach(tbl, set_sub_temporary_name_i, args);
252 rb_ary_set_len(args->names, names_len);
253 }
254}
255
256static void
257set_sub_temporary_name(VALUE mod, VALUE name)
258{
259 struct sub_temporary_name_args args = {name};
260 VALUE arg = (VALUE)&args;
261 rb_exec_recursive_paired(set_sub_temporary_name_topmost, mod, arg, arg);
262}
263
264/*
265 * call-seq:
266 * mod.set_temporary_name(string) -> self
267 * mod.set_temporary_name(nil) -> self
268 *
269 * Sets the temporary name of the module. This name is reflected in
270 * introspection of the module and the values that are related to it, such
271 * as instances, constants, and methods.
272 *
273 * The name should be +nil+ or a non-empty string that is not a valid constant
274 * path (to avoid confusing between permanent and temporary names).
275 *
276 * The method can be useful to distinguish dynamically generated classes and
277 * modules without assigning them to constants.
278 *
279 * If the module is given a permanent name by assigning it to a constant,
280 * the temporary name is discarded. A temporary name can't be assigned to
281 * modules that have a permanent name.
282 *
283 * If the given name is +nil+, the module becomes anonymous again.
284 *
285 * Example:
286 *
287 * m = Module.new # => #<Module:0x0000000102c68f38>
288 * m.name #=> nil
289 *
290 * m.set_temporary_name("fake_name") # => fake_name
291 * m.name #=> "fake_name"
292 *
293 * m.set_temporary_name(nil) # => #<Module:0x0000000102c68f38>
294 * m.name #=> nil
295 *
296 * c = Class.new
297 * c.set_temporary_name("MyClass(with description)") # => MyClass(with description)
298 *
299 * c.new # => #<MyClass(with description):0x0....>
300 *
301 * c::M = m
302 * c::M.name #=> "MyClass(with description)::M"
303 *
304 * # Assigning to a constant replaces the name with a permanent one
305 * C = c
306 *
307 * C.name #=> "C"
308 * C::M.name #=> "C::M"
309 * c.new # => #<C:0x0....>
310 */
311
312VALUE
313rb_mod_set_temporary_name(VALUE mod, VALUE name)
314{
315 rb_class_owner_check(mod);
316
317 // We don't allow setting the name if the classpath is already permanent:
318 if (RCLASS_PERMANENT_CLASSPATH_P(mod)) {
319 rb_raise(rb_eRuntimeError, "can't change permanent name");
320 }
321
322 if (NIL_P(name)) {
323 // Set the temporary classpath to NULL (anonymous):
324 RB_VM_LOCKING() {
325 set_sub_temporary_name(mod, 0);
326 }
327 }
328 else {
329 // Ensure the name is a string:
330 StringValue(name);
331
332 if (RSTRING_LEN(name) == 0) {
333 rb_raise(rb_eArgError, "empty class/module name");
334 }
335
336 if (is_constant_path(name)) {
337 rb_raise(rb_eArgError, "the temporary name must not be a constant path to avoid confusion");
338 }
339
340 name = rb_str_new_frozen(name);
342
343 // Set the temporary classpath to the given name:
344 RB_VM_LOCKING() {
345 set_sub_temporary_name(mod, name);
346 }
347 }
348
349 return mod;
350}
351
352static VALUE
353make_temporary_path(VALUE obj, VALUE klass)
354{
355 VALUE path;
356 switch (klass) {
357 case Qnil:
358 path = rb_sprintf("#<Class:%p>", (void*)obj);
359 break;
360 case Qfalse:
361 path = rb_sprintf("#<Module:%p>", (void*)obj);
362 break;
363 default:
364 path = rb_sprintf("#<%"PRIsVALUE":%p>", klass, (void*)obj);
365 break;
366 }
367 OBJ_FREEZE(path);
368 return path;
369}
370
371typedef VALUE (*fallback_func)(VALUE obj, VALUE name);
372
373static VALUE
374rb_tmp_class_path(VALUE klass, bool *permanent, fallback_func fallback)
375{
376 VALUE path = classname(klass, permanent);
377
378 if (!NIL_P(path)) {
379 return path;
380 }
381
382 if (RB_TYPE_P(klass, T_MODULE)) {
383 if (rb_obj_class(klass) == rb_cModule) {
384 path = Qfalse;
385 }
386 else {
387 bool perm;
388 path = rb_tmp_class_path(RBASIC(klass)->klass, &perm, fallback);
389 }
390 }
391
392 *permanent = false;
393 return fallback(klass, path);
394}
395
396VALUE
398{
399 bool permanent;
400 VALUE path = rb_tmp_class_path(klass, &permanent, make_temporary_path);
401 if (!NIL_P(path)) path = rb_str_dup(path);
402 return path;
403}
404
405VALUE
407{
408 return rb_mod_name(klass);
409}
410
411static VALUE
412no_fallback(VALUE obj, VALUE name)
413{
414 return name;
415}
416
417VALUE
418rb_search_class_path(VALUE klass)
419{
420 bool permanent;
421 return rb_tmp_class_path(klass, &permanent, no_fallback);
422}
423
424static VALUE
425build_const_pathname(VALUE head, VALUE tail)
426{
427 VALUE path = rb_str_dup(head);
428 rb_str_cat2(path, "::");
429 rb_str_append(path, tail);
430 return rb_fstring(path);
431}
432
433static VALUE
434build_const_path(VALUE head, ID tail)
435{
436 return build_const_pathname(head, rb_id2str(tail));
437}
438
439void
441{
442 bool permanent = true;
443
444 VALUE str;
445 if (under == rb_cObject) {
446 str = rb_str_new_frozen(name);
447 }
448 else {
449 str = rb_tmp_class_path(under, &permanent, make_temporary_path);
450 str = build_const_pathname(str, name);
451 }
452
454 RCLASS_SET_CLASSPATH(klass, str, permanent);
455}
456
457void
458rb_set_class_path(VALUE klass, VALUE under, const char *name)
459{
460 VALUE str = rb_str_new2(name);
461 OBJ_FREEZE(str);
462 rb_set_class_path_string(klass, under, str);
463}
464
465VALUE
467{
468 rb_encoding *enc = rb_enc_get(pathname);
469 const char *pbeg, *pend, *p, *path = RSTRING_PTR(pathname);
470 ID id;
471 VALUE c = rb_cObject;
472
473 if (!rb_enc_asciicompat(enc)) {
474 rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
475 }
476 pbeg = p = path;
477 pend = path + RSTRING_LEN(pathname);
478 if (path == pend || path[0] == '#') {
479 rb_raise(rb_eArgError, "can't retrieve anonymous class %"PRIsVALUE,
480 QUOTE(pathname));
481 }
482 while (p < pend) {
483 while (p < pend && *p != ':') p++;
484 id = rb_check_id_cstr(pbeg, p-pbeg, enc);
485 if (p < pend && p[0] == ':') {
486 if ((size_t)(pend - p) < 2 || p[1] != ':') goto undefined_class;
487 p += 2;
488 pbeg = p;
489 }
490 if (!id) {
491 goto undefined_class;
492 }
493 c = rb_const_search(c, id, TRUE, FALSE, FALSE, NULL);
494 if (UNDEF_P(c)) goto undefined_class;
495 if (!rb_namespace_p(c)) {
496 rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
497 pathname);
498 }
499 }
500 RB_GC_GUARD(pathname);
501
502 return c;
503
504 undefined_class:
505 rb_raise(rb_eArgError, "undefined class/module % "PRIsVALUE,
506 rb_str_subseq(pathname, 0, p-path));
508}
509
510VALUE
511rb_path2class(const char *path)
512{
513 return rb_path_to_class(rb_str_new_cstr(path));
514}
515
516VALUE
518{
519 return rb_class_path(rb_class_real(klass));
520}
521
522const char *
524{
525 bool permanent;
526 VALUE path = rb_tmp_class_path(rb_class_real(klass), &permanent, make_temporary_path);
527 if (NIL_P(path)) return NULL;
528 return RSTRING_PTR(path);
529}
530
531const char *
533{
534 return rb_class2name(CLASS_OF(obj));
535}
536
537struct trace_var {
538 int removed;
539 void (*func)(VALUE arg, VALUE val);
540 VALUE data;
541 struct trace_var *next;
542};
543
545 int counter;
546 int block_trace;
547 VALUE *data;
548 rb_gvar_getter_t *getter;
549 rb_gvar_setter_t *setter;
550 rb_gvar_marker_t *marker;
551 rb_gvar_compact_t *compactor;
552 struct trace_var *trace;
553 ID id;
554 bool box_ready;
555 bool box_dynamic;
556};
557
559 struct rb_global_variable *var;
560 ID id;
561 bool ractor_local;
562};
563
564static void
565free_global_variable(struct rb_global_variable *var)
566{
567 RUBY_ASSERT(var->counter == 0);
568
569 struct trace_var *trace = var->trace;
570 while (trace) {
571 struct trace_var *next = trace->next;
572 SIZED_FREE(trace);
573 trace = next;
574 }
575 SIZED_FREE(var);
576}
577
578static enum rb_id_table_iterator_result
579free_global_entry_i(VALUE val, void *arg)
580{
581 struct rb_global_entry *entry = (struct rb_global_entry *)val;
582 entry->var->counter--;
583 if (entry->var->counter == 0) {
584 free_global_variable(entry->var);
585 }
586 SIZED_FREE(entry);
587 return ID_TABLE_DELETE;
588}
589
590void
591rb_free_rb_global_tbl(void)
592{
593 rb_id_table_foreach_values(rb_global_tbl, free_global_entry_i, 0);
594 rb_id_table_free(rb_global_tbl);
595}
596
597void
598rb_free_generic_fields_tbl_(void)
599{
600 st_free_table(generic_fields_tbl_);
601}
602
603static void
604rb_gvar_undef_compactor(void *var)
605{
606}
607
608NORETURN(static void global_entry_isolation_error(ID id));
609
610static void
611global_entry_isolation_error(ID id)
612{
613 rb_raise(rb_eRactorIsolationError, "can not access global variable %s from non-main Ractor", rb_id2name(id));
614}
615
616/* Sets *isolation_error when the caller must raise; the caller has to do that
617 * once it no longer holds the VM lock. */
618static struct rb_global_entry*
619global_entry_lookup(ID id, bool create_entry, bool *isolation_error)
620{
621 struct rb_global_entry *entry;
622 VALUE data;
623
624 RB_VM_LOCKING() {
625 if (rb_id_table_lookup(rb_global_tbl, id, &data)) {
626 entry = (struct rb_global_entry *)data;
627 RUBY_ASSERT(entry != NULL);
628 }
629 else {
630 entry = NULL;
631 }
632
633 *isolation_error = UNLIKELY(!rb_ractor_main_p()) && (!entry || !entry->ractor_local);
634
635 if (!entry && create_entry && !*isolation_error) {
636 struct rb_global_variable *var = ALLOC(struct rb_global_variable);
637 entry = ALLOC(struct rb_global_entry);
638 entry->id = id;
639 entry->var = var;
640 entry->ractor_local = false;
641 var->id = id;
642 var->counter = 1;
643 var->data = 0;
644 var->getter = rb_gvar_undef_getter;
645 var->setter = rb_gvar_undef_setter;
646 var->marker = rb_gvar_undef_marker;
647 var->compactor = rb_gvar_undef_compactor;
648
649 var->block_trace = 0;
650 var->trace = 0;
651 var->box_ready = false;
652 var->box_dynamic = false;
653 rb_id_table_insert(rb_global_tbl, id, (VALUE)entry);
654 }
655 }
656
657 return entry;
658}
659
660static struct rb_global_entry*
661rb_find_global_entry(ID id)
662{
663 bool isolation_error;
664 struct rb_global_entry *entry = global_entry_lookup(id, false, &isolation_error);
665
666 if (isolation_error) global_entry_isolation_error(id);
667
668 return entry;
669}
670
671void
672rb_gvar_ractor_local(const char *name)
673{
674 struct rb_global_entry *entry = rb_find_global_entry(rb_intern(name));
675 entry->ractor_local = true;
676}
677
678void
679rb_gvar_box_ready(const char *name)
680{
681 struct rb_global_entry *entry = rb_find_global_entry(rb_intern(name));
682 entry->var->box_ready = true;
683}
684
685void
686rb_gvar_box_dynamic(const char *name)
687{
688 struct rb_global_entry *entry = rb_find_global_entry(rb_intern(name));
689 entry->var->box_dynamic = true;
690}
691
692static struct rb_global_entry*
694{
695 bool isolation_error;
696 struct rb_global_entry *entry = global_entry_lookup(id, true, &isolation_error);
697
698 if (isolation_error) global_entry_isolation_error(id);
699
700 return entry;
701}
702
703VALUE
705{
706 rb_warning("global variable '%"PRIsVALUE"' not initialized", QUOTE_ID(id));
707
708 return Qnil;
709}
710
711static void
712rb_gvar_val_compactor(void *_var)
713{
714 struct rb_global_variable *var = (struct rb_global_variable *)_var;
715
716 if (var->data) {
717 rb_gc_update_moved_ptr(&var->data);
718 }
719}
720
721void
723{
724 struct rb_global_variable *var = rb_global_entry(id)->var;
725 var->getter = rb_gvar_val_getter;
726 var->setter = rb_gvar_val_setter;
727 var->marker = rb_gvar_val_marker;
728 var->compactor = rb_gvar_val_compactor;
729
730 var->data = (void*)val;
731}
732
733void
735{
736}
737
738VALUE
739rb_gvar_val_getter(ID id, VALUE *data)
740{
741 return (VALUE)data;
742}
743
744void
746{
747 struct rb_global_variable *var = rb_global_entry(id)->var;
748 var->data = (void*)val;
749}
750
751void
753{
754 VALUE data = (VALUE)var;
755 if (data) rb_gc_mark_movable(data);
756}
757
758VALUE
760{
761 if (!var) return Qnil;
762 return *var;
763}
764
765void
766rb_gvar_var_setter(VALUE val, ID id, VALUE *data)
767{
768 *data = val;
769}
770
771void
773{
774 if (var) rb_gc_mark_maybe(*var);
775}
776
777void
779{
780 rb_name_error(id, "%"PRIsVALUE" is a read-only variable", QUOTE_ID(id));
781}
782
783static enum rb_id_table_iterator_result
784mark_global_entry(VALUE v, void *ignored)
785{
786 struct rb_global_entry *entry = (struct rb_global_entry *)v;
787 struct trace_var *trace;
788 struct rb_global_variable *var = entry->var;
789
790 (*var->marker)(var->data);
791 trace = var->trace;
792 while (trace) {
793 if (trace->data) rb_gc_mark_maybe(trace->data);
794 trace = trace->next;
795 }
796 return ID_TABLE_CONTINUE;
797}
798
799#define gc_mark_table(task) \
800 if (rb_global_tbl) { rb_id_table_foreach_values(rb_global_tbl, task##_global_entry, 0); }
801
802void
803rb_gc_mark_global_tbl(void)
804{
805 gc_mark_table(mark);
806}
807
808static enum rb_id_table_iterator_result
809update_global_entry(VALUE v, void *ignored)
810{
811 struct rb_global_entry *entry = (struct rb_global_entry *)v;
812 struct rb_global_variable *var = entry->var;
813
814 (*var->compactor)(var);
815 return ID_TABLE_CONTINUE;
816}
817
818void
819rb_gc_update_global_tbl(void)
820{
821 gc_mark_table(update);
822}
823
824static ID
825global_id(const char *name)
826{
827 ID id;
828
829 if (name[0] == '$') id = rb_intern(name);
830 else {
831 size_t len = strlen(name);
832 VALUE vbuf = 0;
833 char *buf = ALLOCV_N(char, vbuf, len+1);
834 buf[0] = '$';
835 memcpy(buf+1, name, len);
836 id = rb_intern2(buf, len+1);
837 ALLOCV_END(vbuf);
838 }
839 return id;
840}
841
842static ID
843find_global_id(const char *name)
844{
845 ID id;
846 size_t len = strlen(name);
847
848 if (name[0] == '$') {
849 id = rb_check_id_cstr(name, len, NULL);
850 }
851 else {
852 VALUE vbuf = 0;
853 char *buf = ALLOCV_N(char, vbuf, len+1);
854 buf[0] = '$';
855 memcpy(buf+1, name, len);
856 id = rb_check_id_cstr(buf, len+1, NULL);
857 ALLOCV_END(vbuf);
858 }
859
860 return id;
861}
862
863void
865 const char *name,
866 VALUE *var,
867 rb_gvar_getter_t *getter,
868 rb_gvar_setter_t *setter)
869{
870 volatile VALUE tmp = var ? *var : Qnil;
871 ID id = global_id(name);
872 struct rb_global_variable *gvar = rb_global_entry(id)->var;
873
874 gvar->data = (void*)var;
875 gvar->getter = getter ? (rb_gvar_getter_t *)getter : rb_gvar_var_getter;
876 gvar->setter = setter ? (rb_gvar_setter_t *)setter : rb_gvar_var_setter;
877 gvar->marker = rb_gvar_var_marker;
878
879 RB_GC_GUARD(tmp);
880}
881
882void
883rb_define_variable(const char *name, VALUE *var)
884{
885 rb_define_hooked_variable(name, var, 0, 0);
886}
887
888void
889rb_define_readonly_variable(const char *name, const VALUE *var)
890{
892}
893
894void
896 const char *name,
897 rb_gvar_getter_t *getter,
898 rb_gvar_setter_t *setter)
899{
900 if (!getter) getter = rb_gvar_val_getter;
901 if (!setter) setter = rb_gvar_readonly_setter;
902 rb_define_hooked_variable(name, 0, getter, setter);
903}
904
905static void
906rb_trace_eval(VALUE cmd, VALUE val)
907{
908 rb_eval_cmd_call_kw(cmd, 1, &val, RB_NO_KEYWORDS);
909}
910
911VALUE
912rb_f_trace_var(int argc, const VALUE *argv)
913{
914 VALUE var, cmd;
915 struct rb_global_entry *entry;
916 struct trace_var *trace;
917
918 if (rb_scan_args(argc, argv, "11", &var, &cmd) == 1) {
919 cmd = rb_block_proc();
920 }
921 if (NIL_P(cmd)) {
922 return rb_f_untrace_var(argc, argv);
923 }
924 entry = rb_global_entry(rb_to_id(var));
925 trace = ALLOC(struct trace_var);
926 trace->next = entry->var->trace;
927 trace->func = rb_trace_eval;
928 trace->data = cmd;
929 trace->removed = 0;
930 entry->var->trace = trace;
931
932 return Qnil;
933}
934
935static void
936remove_trace(struct rb_global_variable *var)
937{
938 struct trace_var *trace = var->trace;
939 struct trace_var t;
940 struct trace_var *next;
941
942 t.next = trace;
943 trace = &t;
944 while (trace->next) {
945 next = trace->next;
946 if (next->removed) {
947 trace->next = next->next;
948 SIZED_FREE(next);
949 }
950 else {
951 trace = next;
952 }
953 }
954 var->trace = t.next;
955}
956
957VALUE
958rb_f_untrace_var(int argc, const VALUE *argv)
959{
960 VALUE var, cmd;
961 ID id;
962 struct rb_global_entry *entry;
963 struct trace_var *trace;
964
965 rb_scan_args(argc, argv, "11", &var, &cmd);
966 id = rb_check_id(&var);
967 if (!id) {
968 rb_name_error_str(var, "undefined global variable %"PRIsVALUE"", QUOTE(var));
969 }
970 if ((entry = rb_find_global_entry(id)) == NULL) {
971 rb_name_error(id, "undefined global variable %"PRIsVALUE"", QUOTE_ID(id));
972 }
973
974 trace = entry->var->trace;
975 if (NIL_P(cmd)) {
976 VALUE ary = rb_ary_new();
977
978 while (trace) {
979 struct trace_var *next = trace->next;
980 rb_ary_push(ary, (VALUE)trace->data);
981 trace->removed = 1;
982 trace = next;
983 }
984
985 if (!entry->var->block_trace) remove_trace(entry->var);
986 return ary;
987 }
988 else {
989 while (trace) {
990 if (trace->data == cmd) {
991 trace->removed = 1;
992 if (!entry->var->block_trace) remove_trace(entry->var);
993 return rb_ary_new3(1, cmd);
994 }
995 trace = trace->next;
996 }
997 }
998 return Qnil;
999}
1000
1002 struct trace_var *trace;
1003 VALUE val;
1004};
1005
1006static VALUE
1007trace_ev(VALUE v)
1008{
1009 struct trace_data *data = (void *)v;
1010 struct trace_var *trace = data->trace;
1011
1012 while (trace) {
1013 (*trace->func)(trace->data, data->val);
1014 trace = trace->next;
1015 }
1016
1017 return Qnil;
1018}
1019
1020static VALUE
1021trace_en(VALUE v)
1022{
1023 struct rb_global_variable *var = (void *)v;
1024 var->block_trace = 0;
1025 remove_trace(var);
1026 return Qnil; /* not reached */
1027}
1028
1029static void
1030gvar_trace(struct rb_global_variable *var, VALUE val)
1031{
1032 struct trace_data trace;
1033
1034 if (var->trace && !var->block_trace) {
1035 var->block_trace = 1;
1036 trace.trace = var->trace;
1037 trace.val = val;
1038 rb_ensure(trace_ev, (VALUE)&trace, trace_en, (VALUE)var);
1039 }
1040}
1041
1042static VALUE
1043rb_gvar_set_entry(struct rb_global_entry *entry, VALUE val)
1044{
1045 struct rb_global_variable *var = entry->var;
1046
1047 (*var->setter)(val, entry->id, var->data);
1048 gvar_trace(var, val);
1049 return val;
1050}
1051
1052static inline bool
1053gvar_use_box_tbl(const rb_box_t *box, const struct rb_global_entry *entry)
1054{
1055 return BOX_USER_P(box) &&
1056 !entry->var->box_dynamic &&
1057 (!entry->var->box_ready || entry->var->setter != rb_gvar_readonly_setter);
1058}
1059
1060VALUE
1061rb_gvar_set(ID id, VALUE val)
1062{
1063 VALUE retval;
1064 struct rb_global_entry *entry = NULL;
1065 const rb_box_t *box = rb_current_box();
1066 bool use_box_tbl = false;
1067 bool isolation_error = false;
1068
1069 RB_VM_LOCKING() {
1070 entry = global_entry_lookup(id, true, &isolation_error);
1071
1072 if (!isolation_error && gvar_use_box_tbl(box, entry)) {
1073 use_box_tbl = true;
1074 rb_hash_aset(box->gvar_tbl, rb_id2sym(entry->var->id), val);
1075 retval = val;
1076 }
1077 }
1078
1079 if (isolation_error) global_entry_isolation_error(id);
1080
1081 if (use_box_tbl) {
1082 gvar_trace(entry->var, val);
1083 }
1084 else {
1085 retval = rb_gvar_set_entry(entry, val);
1086 }
1087 return retval;
1088}
1089
1090VALUE
1091rb_gv_set(const char *name, VALUE val)
1092{
1093 return rb_gvar_set(global_id(name), val);
1094}
1095
1096VALUE
1097rb_gvar_get(ID id)
1098{
1099 VALUE retval, gvars, key;
1100 const rb_box_t *box = rb_current_box();
1101 bool use_box_tbl = false;
1102 bool isolation_error = false;
1103 struct rb_global_entry *entry = NULL;
1104 struct rb_global_variable *var = NULL;
1105
1106 RB_VM_LOCKING() {
1107 // TODO: use lock-free rb_id_table when it's available for use (doesn't yet exist)
1108 entry = global_entry_lookup(id, true, &isolation_error);
1109
1110 if (!isolation_error) {
1111 var = entry->var;
1112
1113 if (gvar_use_box_tbl(box, entry)) {
1114 use_box_tbl = true;
1115 gvars = box->gvar_tbl;
1116 key = rb_id2sym(var->id);
1117 if (RTEST(rb_hash_has_key(gvars, key))) { // this gvar is already cached
1118 retval = rb_hash_aref(gvars, key);
1119 }
1120 else {
1121 // An undefined gvar has no value to snapshot, and caching its nil
1122 // would make rb_gvar_defined() report it as defined in this box.
1123 bool cache = var->getter != rb_gvar_undef_getter;
1124 RB_VM_UNLOCK();
1125 {
1126 retval = (*var->getter)(entry->id, var->data);
1127 if (rb_obj_respond_to(retval, rb_intern("clone"), 1)) {
1128 retval = rb_funcall(retval, rb_intern("clone"), 0);
1129 }
1130 }
1131 RB_VM_LOCK();
1132 if (cache) rb_hash_aset(gvars, key, retval);
1133 }
1134 }
1135 }
1136 }
1137
1138 if (isolation_error) global_entry_isolation_error(id);
1139
1140 if (!use_box_tbl) {
1141 retval = (*var->getter)(entry->id, var->data);
1142 }
1143 return retval;
1144}
1145
1146VALUE
1147rb_gv_get(const char *name)
1148{
1149 ID id = find_global_id(name);
1150
1151 if (!id) {
1152 rb_warning("global variable '%s' not initialized", name);
1153 return Qnil;
1154 }
1155
1156 return rb_gvar_get(id);
1157}
1158
1159VALUE
1160rb_gvar_defined(ID id)
1161{
1162 const rb_box_t *box = rb_current_box();
1163 bool defined;
1164
1165 RB_VM_LOCKING() {
1166 const struct rb_global_entry *entry = rb_global_entry(id);
1167
1168 defined = entry->var->getter != rb_gvar_undef_getter ||
1169 (gvar_use_box_tbl(box, entry) &&
1170 RTEST(rb_hash_has_key(box->gvar_tbl, rb_id2sym(entry->var->id))));
1171 }
1172 return RBOOL(defined);
1173}
1174
1176rb_gvar_getter_function_of(ID id)
1177{
1178 const struct rb_global_entry *entry = rb_global_entry(id);
1179 return entry->var->getter;
1180}
1181
1183rb_gvar_setter_function_of(ID id)
1184{
1185 const struct rb_global_entry *entry = rb_global_entry(id);
1186 return entry->var->setter;
1187}
1188
1189static enum rb_id_table_iterator_result
1190gvar_i(ID key, VALUE val, void *a)
1191{
1192 VALUE ary = (VALUE)a;
1193 rb_ary_push(ary, ID2SYM(key));
1194 return ID_TABLE_CONTINUE;
1195}
1196
1197VALUE
1199{
1200 VALUE ary = rb_ary_new();
1201 VALUE sym, backref = rb_backref_get();
1202
1203 if (!rb_ractor_main_p()) {
1204 rb_raise(rb_eRactorIsolationError, "can not access global variables from non-main Ractors");
1205 }
1206 /* gvar access (get/set) in boxes creates gvar entries globally */
1207
1208 rb_id_table_foreach(rb_global_tbl, gvar_i, (void *)ary);
1209 if (!NIL_P(backref)) {
1210 char buf[2];
1211 int i, nmatch = rb_match_count(backref);
1212 buf[0] = '$';
1213 for (i = 1; i <= nmatch; ++i) {
1214 if (!RTEST(rb_reg_nth_defined(i, backref))) continue;
1215 if (i < 10) {
1216 /* probably reused, make static ID */
1217 buf[1] = (char)(i + '0');
1218 sym = ID2SYM(rb_intern2(buf, 2));
1219 }
1220 else {
1221 /* dynamic symbol */
1222 sym = rb_str_intern(rb_sprintf("$%d", i));
1223 }
1224 rb_ary_push(ary, sym);
1225 }
1226 }
1227 return ary;
1228}
1229
1230void
1232{
1233 struct rb_global_entry *entry1 = NULL, *entry2;
1234 VALUE data1;
1235 struct rb_id_table *gtbl = rb_global_tbl;
1236 bool tracer_error = false;
1237
1238 if (!rb_ractor_main_p()) {
1239 rb_raise(rb_eRactorIsolationError, "can not access global variables from non-main Ractors");
1240 }
1241
1242 RB_VM_LOCKING() {
1243 bool isolation_error;
1244 entry2 = global_entry_lookup(name2, true, &isolation_error);
1245 VM_ASSERT(!isolation_error); /* main Ractor, checked above */
1246
1247 if (!rb_id_table_lookup(gtbl, name1, &data1)) {
1248 entry1 = ZALLOC(struct rb_global_entry);
1249 entry1->id = name1;
1250 rb_id_table_insert(gtbl, name1, (VALUE)entry1);
1251 }
1252 else if ((entry1 = (struct rb_global_entry *)data1)->var != entry2->var) {
1253 struct rb_global_variable *var = entry1->var;
1254 if (var->block_trace) {
1255 tracer_error = true;
1256 }
1257 else {
1258 var->counter--;
1259 if (var->counter == 0) {
1260 free_global_variable(var);
1261 }
1262 }
1263 }
1264 if (!tracer_error && entry1->var != entry2->var) {
1265 entry2->var->counter++;
1266 entry1->var = entry2->var;
1267 }
1268 }
1269
1270 if (tracer_error) rb_raise(rb_eRuntimeError, "can't alias in tracer");
1271}
1272
1273static void
1274class_ivar_set_ractor_check(VALUE klass, ID id)
1275{
1276 if (rb_is_instance_id(id) && // check only normal ivars
1277 UNLIKELY(!rb_class_owned_p(klass))) {
1278 rb_raise(
1279 rb_eRactorIsolationError,
1280 "can not set instance variables of classes/modules "
1281 "created by another Ractor (%"PRIsVALUE" from %"PRIsVALUE")",
1282 rb_id2str(id),
1283 rb_class_path(klass)
1284 );
1285 }
1286}
1287
1288// klass is the class the variable is stored in, not the receiver: which one that
1289// is can migrate (cvar_overtaken), and it is the one with a single writer.
1290static void
1291cvar_set_ractor_check(VALUE klass, ID id)
1292{
1293 if (UNLIKELY(!rb_class_owned_p(klass))) {
1294 rb_raise(rb_eRactorIsolationError,
1295 "can not set class variable %"PRIsVALUE" of %"PRIsVALUE", which was created by another Ractor",
1296 rb_id2str(id), klass);
1297 }
1298}
1299
1300static void
1301cvar_read_ractor_check(VALUE klass, ID id, VALUE val)
1302{
1303 if (UNLIKELY(!rb_class_owned_p(klass)) && !rb_class_field_shareable_p(klass, val)) {
1304 rb_raise(rb_eRactorIsolationError,
1305 "can not read non-shareable class variable %"PRIsVALUE" of %"PRIsVALUE", which was created by another Ractor",
1306 rb_id2str(id), klass);
1307 }
1308}
1309
1310static inline void
1311ivar_ractor_assert(VALUE obj, ID id)
1312{
1313 RUBY_ASSERT(!rb_is_instance_id(id) /* internal ID */ ||
1314 SPECIAL_CONST_P(obj) ||
1315 !rb_ractor_shareable_p(obj) ||
1316 RB_OBJ_FROZEN_RAW(obj) ||
1317 RB_TYPE_P(obj, T_CLASS) || RB_TYPE_P(obj, T_MODULE) ||
1318 RB_TYPE_P(obj, T_ICLASS) || RB_TYPE_P(obj, T_IMEMO) ||
1319 rb_shape_frozen_p(RBASIC_SHAPE_ID(obj)),
1320 "shareable object must not have writable instance variables");
1321}
1322
1323struct st_table *
1324rb_generic_fields_tbl_get(void)
1325{
1326 return generic_fields_tbl_;
1327}
1328
1329/* generic_fields is one global table. Leaf lock discipline: under gf_lock, take no
1330 * other lock, do not allocate, and create no safepoint. In single-Ractor mode the
1331 * GVL already serializes everything, so no lock is taken. */
1332static inline void
1333gf_lock(void)
1334{
1335 if (rb_multi_ractor_p()) {
1336 rb_native_mutex_lock(&GET_VM()->ractor.generic_fields_lock);
1337 }
1338}
1339
1340static inline void
1341gf_unlock(void)
1342{
1343 if (rb_multi_ractor_p()) {
1344 rb_native_mutex_unlock(&GET_VM()->ractor.generic_fields_lock);
1345 }
1346}
1347
1348void
1349rb_mark_generic_ivar(VALUE obj)
1350{
1351 /* Under a multi-objspace global GC (stop-the-world) there is no per-object
1352 * lookup: after marking, rb_gc_vm_generic_fields_mark_foreach marks the values of
1353 * the live keys. A single-objspace impl (mmtk) has no such pass, so mark here. */
1354 if (rb_gc_during_global_gc_p() && rb_gc_multi_objspace_p()) {
1355 return;
1356 }
1357
1358 /* Per-object marking for a local GC or for compaction (single objspace). gf_lock
1359 * excludes writers in other Ractors. */
1360 VALUE data = 0;
1361 gf_lock();
1362 st_lookup(generic_fields_tbl_, (st_data_t)obj, (st_data_t *)&data);
1363 gf_unlock();
1364 if (data) {
1365 rb_gc_mark_movable(data);
1366 }
1367}
1368
1369/* Look up obj's generic fields in the single global table. A snapshot host being
1370 * materialized (which lives in the sender's objspace) is in the same table, so the
1371 * receiving side can look it up directly. */
1372VALUE
1373rb_obj_fields_generic_uncached(VALUE obj)
1374{
1375 VALUE fields_obj = 0;
1376 int found = 0;
1377
1378 gf_lock();
1379 found = st_lookup(generic_fields_tbl_, (st_data_t)obj, (st_data_t *)&fields_obj);
1380 gf_unlock();
1381
1382 if (!found) {
1383 rb_bug("Object is missing entry in generic_fields_tbl");
1384 }
1385 return fields_obj;
1386}
1387
1388static bool
1389obj_use_generic_fields_tbl_p(VALUE obj)
1390{
1391 switch (BUILTIN_TYPE(obj)) {
1392 case T_OBJECT:
1393 case T_CLASS:
1394 case T_MODULE:
1395 case T_STRUCT:
1396 case T_DATA:
1397 return false;
1398 default:
1399 return true;
1400 }
1401}
1402
1403static VALUE
1404obj_fields_get(VALUE obj)
1405{
1406 switch (BUILTIN_TYPE(obj)) {
1407 case T_IMEMO:
1408 RUBY_ASSERT(IMEMO_TYPE_P(obj, imemo_fields));
1409 return obj;
1410
1411 case T_OBJECT:
1412 return ROBJECT_FIELDS_OBJ(obj);
1413
1414 case T_CLASS:
1415 case T_MODULE:
1416 return RCLASS_WRITABLE_FIELDS_OBJ(obj);
1417
1418 case T_DATA:
1419 return rbimpl_atomic_value_load(&RTYPEDDATA(obj)->fields_obj, RBIMPL_ATOMIC_ACQUIRE);
1420
1421 case T_STRUCT:
1422 return RSTRUCT_FIELDS_OBJ(obj);
1423
1424 default:
1425 {
1426 VALUE fields_obj = 0;
1427
1428 if (rb_obj_shape_has_fields(obj)) {
1429 rb_execution_context_t *ec = GET_EC();
1430 if (ec->gen_fields_cache.obj == obj && !UNDEF_P(ec->gen_fields_cache.fields_obj) && rb_imemo_fields_owner(ec->gen_fields_cache.fields_obj) == obj) {
1431 fields_obj = ec->gen_fields_cache.fields_obj;
1432 RUBY_ASSERT(fields_obj == rb_obj_fields_generic_uncached(obj));
1433 }
1434 else {
1435 fields_obj = rb_obj_fields_generic_uncached(obj);
1436 ec->gen_fields_cache.fields_obj = fields_obj;
1437 ec->gen_fields_cache.obj = obj;
1438 }
1439 }
1440
1441 return fields_obj;
1442 }
1443 }
1444}
1445
1446VALUE
1447rb_obj_fields(VALUE obj, ID field_name)
1448{
1449 ivar_ractor_assert(obj, field_name);
1450 return obj_fields_get(obj);
1451}
1452
1453static VALUE
1454obj_fields(VALUE obj, shape_id_t shape_id)
1455{
1456#if RUBY_DEBUG
1457 ivar_ractor_assert(obj, RSHAPE_EDGE_NAME(shape_id));
1458#endif
1459 return obj_fields_get(obj);
1460}
1461
1462void
1464{
1465 if (rb_obj_gen_fields_p(obj)) {
1466 st_data_t key = (st_data_t)obj, value;
1467 switch (BUILTIN_TYPE(obj)) {
1468 case T_DATA:
1469 RB_OBJ_WRITE(obj, &RTYPEDDATA(obj)->fields_obj, 0);
1470 break;
1471 case T_STRUCT:
1472 RSTRUCT_SET_FIELDS_OBJ(obj, 0);
1473 break;
1474
1475 default:
1476 {
1477 // Other EC may have stale caches, so fields_obj should be
1478 // invalidated and the GC will replace with Qundef
1479 rb_execution_context_t *ec = GET_EC();
1480 if (ec->gen_fields_cache.obj == obj) {
1481 ec->gen_fields_cache.obj = Qundef;
1482 ec->gen_fields_cache.fields_obj = Qundef;
1483 }
1484 /* A write from the mutator or from a local GC sweep (the host's
1485 * obj_free), taking the table's mutex; never from a global GC sweep
1486 * (the during_global_gc guard below). */
1487 if (rb_gc_during_global_gc_p() || ruby_vm_during_cleanup) {
1488 /* Leave dead keys to the weak pass's drain (same reasoning as the
1489 * skip in rb_mark_generic_ivar); VM destruct's free-at-exit walk
1490 * discards the whole table, needing no per-entry removal either. */
1491 break;
1492 }
1493 int deleted = 0;
1494 gf_lock();
1495 deleted = st_delete(generic_fields_tbl_, &key, &value);
1496 gf_unlock();
1497 if (!deleted) {
1498 rb_bug("Object is missing entry in generic_fields_tbl");
1499 }
1500 }
1501 }
1502 RBASIC_SET_SHAPE_ID(obj, ROOT_SHAPE_ID);
1503 }
1504}
1505
1506static void
1507rb_obj_set_fields(VALUE obj, VALUE fields_obj, ID field_name, VALUE original_fields_obj)
1508{
1509 ivar_ractor_assert(obj, field_name);
1510
1511 if (!fields_obj) {
1512 RUBY_ASSERT(original_fields_obj);
1514 rb_imemo_fields_clear(original_fields_obj);
1515 return;
1516 }
1517
1518 RUBY_ASSERT(IMEMO_TYPE_P(fields_obj, imemo_fields));
1519 RUBY_ASSERT(!original_fields_obj || IMEMO_TYPE_P(original_fields_obj, imemo_fields) || RB_TYPE_P(original_fields_obj, T_OBJECT));
1520
1521 int type = BUILTIN_TYPE(obj);
1522 if (fields_obj != original_fields_obj) {
1523 switch (type) {
1524 case T_OBJECT:
1525 RUBY_ASSERT(obj != fields_obj);
1526 ROBJECT_SET_EXTENDED(obj, fields_obj);
1527 break;
1528 case T_DATA:
1529 RB_OBJ_ATOMIC_WRITE(obj, &RTYPEDDATA(obj)->fields_obj, fields_obj);
1530 break;
1531 case T_STRUCT:
1532 RSTRUCT_SET_FIELDS_OBJ(obj, fields_obj);
1533 break;
1534
1535 default:
1536 {
1537 /* st_insert may malloc: disable this Ractor's GC first, or our own
1538 * local GC's marking takes gf_lock again and self-deadlocks. Growing
1539 * can still raise NoMemoryError, and leaking gf_lock hangs every later
1540 * generic-fields access: unwind through a tag. */
1541 bool gc_disabled = RTEST(rb_gc_local_disable_no_rest());
1542 rb_execution_context_t *insert_ec = GET_EC();
1543 enum ruby_tag_type state;
1544 gf_lock();
1545 EC_PUSH_TAG(insert_ec);
1546 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1547 st_insert(generic_fields_tbl_, (st_data_t)obj, (st_data_t)fields_obj);
1548 }
1549 EC_POP_TAG();
1550 gf_unlock();
1551 if (!gc_disabled) rb_gc_local_enable();
1552 if (state != TAG_NONE) EC_JUMP_TAG(insert_ec, state);
1553 RB_OBJ_WRITTEN(obj, original_fields_obj, fields_obj);
1554
1555 rb_execution_context_t *ec = GET_EC();
1556 if (ec->gen_fields_cache.fields_obj != fields_obj) {
1557 ec->gen_fields_cache.obj = obj;
1558 ec->gen_fields_cache.fields_obj = fields_obj;
1559 }
1560 }
1561 }
1562
1563 if (original_fields_obj && original_fields_obj != obj) {
1564 // Clear root shape to avoid triggering cleanup such as free_object_id.
1565 rb_imemo_fields_clear(original_fields_obj);
1566 }
1567 }
1568
1569 if (type == T_OBJECT) {
1570 RBASIC_SET_SHAPE_ID_WITH_LAYOUT(obj, RBASIC_SHAPE_ID(fields_obj), SHAPE_ID_LAYOUT_EXTENDED);
1571 }
1572 else {
1573 RBASIC_SET_SHAPE_ID(obj, RBASIC_SHAPE_ID(fields_obj));
1574 }
1575}
1576
1577void
1578rb_obj_replace_fields(VALUE obj, VALUE fields_obj)
1579{
1580 if (obj_use_generic_fields_tbl_p(obj)) {
1581 // We'll first lookup the generic fields table and then insert
1582 // into it, so lock once for both operations.
1583 RB_VM_LOCKING() {
1584 VALUE original_fields_obj = rb_obj_fields_no_ractor_check(obj);
1585 rb_obj_set_fields(obj, fields_obj, 0, original_fields_obj);
1586 }
1587 }
1588 else {
1589 VALUE original_fields_obj = rb_obj_fields_no_ractor_check(obj);
1590 rb_obj_set_fields(obj, fields_obj, 0, original_fields_obj);
1591 }
1592}
1593
1594VALUE
1595rb_imemo_fields_field_get(VALUE fields_obj, shape_id_t target_shape_id)
1596{
1597 RUBY_ASSERT(RSHAPE_TYPE_P(target_shape_id, SHAPE_IVAR) || RSHAPE_TYPE_P(target_shape_id, SHAPE_OBJ_ID));
1598
1599 if (UNLIKELY(rb_shape_complex_p(target_shape_id))) {
1600 st_table *fields_hash = rb_imemo_fields_complex_tbl(fields_obj);
1601 VALUE value = Qundef;
1602 st_lookup(fields_hash, RSHAPE_EDGE_NAME(target_shape_id), &value);
1603 RUBY_ASSERT(!UNDEF_P(value));
1604 return value;
1605 }
1606
1607 attr_index_t index = RSHAPE_INDEX(target_shape_id);
1608 return rb_imemo_fields_ptr(fields_obj)[index];
1609}
1610
1611VALUE
1612rb_obj_field_get(VALUE obj, shape_id_t target_shape_id)
1613{
1615
1616 return rb_imemo_fields_field_get(obj_fields(obj, target_shape_id), target_shape_id);
1617}
1618
1619VALUE
1620rb_ivar_lookup(VALUE obj, ID id, VALUE undef)
1621{
1622 if (SPECIAL_CONST_P(obj)) return undef;
1623
1624 int type = BUILTIN_TYPE(obj);
1625 bool is_class = type == T_CLASS || type == T_MODULE;
1626 VALUE fields_obj = rb_obj_fields(obj, is_class ? 0 : id);
1627
1628 if (!fields_obj) {
1629 return undef;
1630 }
1631
1632 shape_id_t shape_id = RBASIC_SHAPE_ID(fields_obj);
1633
1634 VALUE val = undef;
1635 if (UNLIKELY(rb_shape_complex_p(shape_id))) {
1636 st_table *iv_table = rb_imemo_fields_complex_tbl(fields_obj);
1637 if (!rb_st_lookup(iv_table, (st_data_t)id, (st_data_t *)&val)) {
1638 return undef;
1639 }
1640 }
1641 else {
1642 attr_index_t index = 0;
1643 if (!rb_shape_get_iv_index(shape_id, id, &index)) {
1644 return undef;
1645 }
1646 val = rb_imemo_fields_ptr(fields_obj)[index];
1647 }
1648
1649 if (is_class && val != undef && rb_is_instance_id(id)) {
1650 if (UNLIKELY(!rb_class_owned_p(obj)) && !rb_class_field_shareable_p(obj, val)) {
1651 rb_raise(
1652 rb_eRactorIsolationError,
1653 "can not get unshareable values from instance variables of classes/modules "
1654 "created by another Ractor (%"PRIsVALUE" from %"PRIsVALUE")",
1655 rb_id2str(id),
1656 rb_class_path(obj)
1657 );
1658 }
1659 }
1660
1661 return val;
1662}
1663
1664VALUE
1666{
1667 VALUE iv = rb_ivar_lookup(obj, id, Qnil);
1668 RB_DEBUG_COUNTER_INC(ivar_get_base);
1669 return iv;
1670}
1671
1672VALUE
1673rb_ivar_get_at(VALUE obj, attr_index_t index, ID id)
1674{
1676 // Used by JITs, but never for T_OBJECT.
1677
1678 switch (BUILTIN_TYPE(obj)) {
1679 case T_OBJECT:
1681 case T_CLASS:
1682 case T_MODULE:
1683 {
1684 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1685 VALUE val = rb_imemo_fields_ptr(fields_obj)[index];
1686
1687 if (UNLIKELY(!rb_class_owned_p(obj)) && !rb_class_field_shareable_p(obj, val)) {
1688 rb_raise(
1689 rb_eRactorIsolationError,
1690 "can not get unshareable values from instance variables of classes/modules "
1691 "created by another Ractor (%"PRIsVALUE" from %"PRIsVALUE")",
1692 rb_id2str(id),
1693 rb_class_path(obj)
1694 );
1695 }
1696
1697 return val;
1698 }
1699 default:
1700 {
1701 VALUE fields_obj = rb_obj_fields(obj, id);
1702 return rb_imemo_fields_ptr(fields_obj)[index];
1703 }
1704 }
1705}
1706
1707VALUE
1708rb_ivar_get_at_no_ractor_check(VALUE obj, attr_index_t index)
1709{
1710 // Used by JITs, but never for T_OBJECT.
1711
1712 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
1713 return rb_imemo_fields_ptr(fields_obj)[index];
1714}
1715
1716VALUE
1717rb_attr_get(VALUE obj, ID id)
1718{
1719 return rb_ivar_lookup(obj, id, Qnil);
1720}
1721
1722static VALUE imemo_fields_evacutate_to_complex(VALUE owner, VALUE source_fields_obj, shape_id_t shape_id, int extra_capa);
1723
1724static shape_id_t
1725rb_obj_convert_too_complex(VALUE obj, VALUE fields_obj, shape_id_t shape_id)
1726{
1728 RUBY_ASSERT(!rb_obj_shape_complex_p(obj));
1729
1730 shape_id = rb_shape_transition_complex(shape_id);
1731 VALUE new_fields_obj = imemo_fields_evacutate_to_complex(obj, fields_obj, shape_id, 1);
1732 ROBJECT_SET_EXTENDED(obj, new_fields_obj);
1733 RBASIC_SET_SHAPE_ID_WITH_LAYOUT(obj, shape_id, SHAPE_ID_LAYOUT_EXTENDED);
1734 return shape_id;
1735}
1736
1737static VALUE
1738rb_ivar_delete(VALUE obj, ID id, VALUE undef)
1739{
1740 rb_check_frozen(obj);
1741
1742 VALUE val = undef;
1743 bool concurrent = false;
1744 int type = BUILTIN_TYPE(obj);
1745
1746 if (type == T_CLASS || type == T_MODULE) {
1747 class_ivar_set_ractor_check(obj, id);
1748
1749 if (rb_multi_ractor_p()) {
1750 concurrent = true;
1751 }
1752 }
1753
1754 VALUE fields_obj = rb_obj_fields(obj, id);
1755 if (!fields_obj) {
1756 return undef;
1757 }
1758
1759 const VALUE original_fields_obj = fields_obj;
1760 if (concurrent) {
1761 fields_obj = rb_imemo_fields_clone(fields_obj);
1762 }
1763
1764 shape_id_t old_shape_id = RBASIC_SHAPE_ID(fields_obj);
1765 shape_id_t removed_shape_id;
1766 shape_id_t next_shape_id = rb_obj_shape_transition_remove_ivar(fields_obj, id, &removed_shape_id);
1767
1768 if (UNLIKELY(rb_shape_complex_p(next_shape_id))) {
1769 if (UNLIKELY(!rb_shape_complex_p(old_shape_id))) {
1770 fields_obj = imemo_fields_evacutate_to_complex(obj, fields_obj, next_shape_id, -1);
1771 }
1772 st_data_t key = id;
1773 if (!st_delete(rb_imemo_fields_complex_tbl(fields_obj), &key, (st_data_t *)&val)) {
1774 val = undef;
1775 }
1776 }
1777 else {
1778 if (next_shape_id == old_shape_id) {
1779 return undef;
1780 }
1781
1782 RUBY_ASSERT(removed_shape_id != INVALID_SHAPE_ID);
1783 RUBY_ASSERT(RSHAPE_LEN(next_shape_id) == RSHAPE_LEN(old_shape_id) - 1);
1784
1785 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
1786 attr_index_t removed_index = RSHAPE_INDEX(removed_shape_id);
1787 val = fields[removed_index];
1788
1789 attr_index_t new_fields_count = RSHAPE_LEN(next_shape_id);
1790 if (new_fields_count) {
1791 size_t trailing_fields = new_fields_count - removed_index;
1792
1793 MEMMOVE(&fields[removed_index], &fields[removed_index + 1], VALUE, trailing_fields);
1794 RBASIC_SET_SHAPE_ID(fields_obj, next_shape_id);
1795
1796 if (type == T_OBJECT && obj != fields_obj && new_fields_count == rb_shape_embedded_capacity(RBASIC_SHAPE_ID(obj))) {
1797 // Re-embed objects when instances become small enough
1798 // This is necessary because YJIT assumes that objects with the same shape
1799 // have the same embeddedness for efficiency (avoid extra checks)
1800 // Note: shapes have changed significantly since, we could not do this anymore.
1801 VALUE *embedded_fields = ROBJECT_EMBEDDED_FIELDS(obj);
1802 MEMCPY(embedded_fields, fields, VALUE, new_fields_count);
1803 for (attr_index_t i = 0; i < new_fields_count; i++) {
1804 RB_OBJ_WRITTEN(obj, Qundef, embedded_fields[i]);
1805 }
1806 fields_obj = 0;
1807 }
1808 }
1809 else {
1810 fields_obj = 0;
1812 }
1813 }
1814
1815 if (fields_obj != original_fields_obj) {
1816 switch (type) {
1817 case T_OBJECT:
1818 if (fields_obj && fields_obj != obj) {
1819 ROBJECT_SET_EXTENDED(obj, fields_obj);
1820 }
1821 break;
1822 case T_CLASS:
1823 case T_MODULE:
1824 RCLASS_WRITABLE_SET_FIELDS_OBJ(obj, fields_obj);
1825 break;
1826 default:
1827 rb_obj_set_fields(obj, fields_obj, id, original_fields_obj);
1828 break;
1829 }
1830 }
1831
1832 if (type == T_OBJECT) {
1833 if (!fields_obj || fields_obj == obj) {
1834 RBASIC_SET_SHAPE_ID_WITH_LAYOUT(obj, next_shape_id, SHAPE_ID_LAYOUT_ROBJECT);
1835 }
1836 else {
1837 RBASIC_SET_SHAPE_ID_WITH_LAYOUT(obj, next_shape_id, SHAPE_ID_LAYOUT_EXTENDED);
1838 }
1839 }
1840 else if (type == T_CLASS || type == T_MODULE) {
1841 RBASIC_SET_SHAPE_ID_ATOMIC(obj, next_shape_id);
1842 }
1843 else {
1844 RBASIC_SET_SHAPE_ID(obj, next_shape_id);
1845 }
1846
1847 return val;
1848}
1849
1850VALUE
1851rb_attr_delete(VALUE obj, ID id)
1852{
1853 return rb_ivar_delete(obj, id, Qnil);
1854}
1855
1856static int
1857imemo_fields_complex_from_obj_i(ID key, VALUE val, st_data_t arg)
1858{
1859 VALUE fields = (VALUE)arg;
1860 st_table *table = rb_imemo_fields_complex_tbl(fields);
1861
1862 RUBY_ASSERT(!st_lookup(table, (st_data_t)key, NULL));
1863 st_add_direct(table, (st_data_t)key, (st_data_t)val);
1864 RB_OBJ_WRITTEN(fields, Qundef, val);
1865
1866 return ST_CONTINUE;
1867}
1868
1869static int
1870imemo_fields_shref_i(ID key, VALUE val, st_data_t arg)
1871{
1872 VALUE fields_obj = (VALUE)arg;
1873 /* The fields_obj became shareable while this field value stayed unshareable (a
1874 * hidden [path, line] ivar, say, which make_shareable's traversal never reaches):
1875 * record a shref so the shareable -> unshareable edge is tracked. */
1876 if (!SPECIAL_CONST_P(val) && !RB_OBJ_SHAREABLE_P(val)) {
1877 rb_gc_writebarrier(fields_obj, val);
1878 }
1879 return ST_CONTINUE;
1880}
1881
1882/* Record shrefs for the values that are still unshareable in a fields imemo that has
1883 * just been promoted to shareable. */
1884void
1885rb_imemo_fields_record_shrefs(VALUE fields_obj)
1886{
1887 rb_field_foreach(fields_obj, imemo_fields_shref_i, (st_data_t)fields_obj, false);
1888}
1889
1890static VALUE
1891imemo_fields_complex_from_obj(VALUE owner, VALUE source, shape_id_t shape_id, bool ivar_only, int extra_capa)
1892{
1893 attr_index_t len = source ? RSHAPE_LEN(RBASIC_SHAPE_ID(source)) : 0;
1894 int capa = (len + extra_capa);
1895 RUBY_ASSERT(capa >= 0);
1896
1897 VALUE fields_obj = rb_imemo_fields_new_complex(owner, shape_id, capa, RB_OBJ_SHAREABLE_P(owner));
1898
1899 rb_field_foreach(source, imemo_fields_complex_from_obj_i, (st_data_t)fields_obj, ivar_only);
1900
1901 return fields_obj;
1902}
1903
1904static VALUE
1905imemo_fields_evacutate_to_complex(VALUE owner, VALUE source, shape_id_t shape_id, int extra_capa)
1906{
1907 return imemo_fields_complex_from_obj(owner, source, shape_id, false, extra_capa);
1908}
1909
1910VALUE
1911rb_obj_complex_fields_build(VALUE obj)
1912{
1913 return imemo_fields_complex_from_obj(obj, obj, ROOT_COMPLEX_SHAPE_ID, true, 0);
1914}
1915
1916static VALUE
1917imemo_fields_copy_append(VALUE owner, VALUE source_fields_obj, shape_id_t current_shape_id, shape_id_t target_shape_id, VALUE val)
1918{
1919 attr_index_t fields_count = RSHAPE_LEN(current_shape_id);
1920
1921 VALUE fields_obj = rb_imemo_fields_new(owner, target_shape_id, RB_OBJ_SHAREABLE_P(owner));
1922
1923 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
1924
1925 if (source_fields_obj) {
1926 MEMCPY(fields, rb_imemo_fields_ptr(source_fields_obj), VALUE, fields_count);
1927 for (attr_index_t i = 0; i < fields_count; i++) {
1928 RB_OBJ_WRITTEN(fields_obj, Qundef, fields[i]);
1929 }
1930 }
1931
1932 RB_OBJ_WRITE(fields_obj, &fields[fields_count], val);
1933
1934 return fields_obj;
1935}
1936
1937static VALUE
1938imemo_fields_set(VALUE owner, VALUE fields_obj, shape_id_t target_shape_id, ID field_name, VALUE val, bool concurrent)
1939{
1940 const VALUE original_fields_obj = fields_obj;
1941 shape_id_t current_shape_id = fields_obj ? RBASIC_SHAPE_ID(fields_obj) : ROOT_SHAPE_ID;
1942
1943 if (UNLIKELY(rb_shape_complex_p(target_shape_id))) {
1944 if (rb_shape_complex_p(current_shape_id)) {
1945 if (concurrent) {
1946 // In multi-ractor case, we must always work on a copy because
1947 // even if the field already exist, inserting in a st_table may
1948 // cause a rebuild.
1949 fields_obj = rb_imemo_fields_clone(fields_obj);
1950 }
1951 }
1952 else {
1953 fields_obj = imemo_fields_evacutate_to_complex(owner, original_fields_obj, target_shape_id, 1);
1954 current_shape_id = target_shape_id;
1955 }
1956
1957 st_table *table = rb_imemo_fields_complex_tbl(fields_obj);
1958
1959 RUBY_ASSERT(field_name);
1960 st_insert(table, (st_data_t)field_name, (st_data_t)val);
1961 RB_OBJ_WRITTEN(fields_obj, Qundef, val);
1962 RBASIC_SET_SHAPE_ID(fields_obj, target_shape_id);
1963 }
1964 else {
1965 attr_index_t index = RSHAPE_INDEX(target_shape_id);
1966 if (concurrent || index >= rb_shape_embedded_capacity(current_shape_id)) {
1967 return imemo_fields_copy_append(owner, original_fields_obj, current_shape_id, target_shape_id, val);
1968 }
1969
1970 VALUE *table = rb_imemo_fields_ptr(fields_obj);
1971 RB_OBJ_WRITE(fields_obj, &table[index], val);
1972
1973 if (index >= RSHAPE_LEN(current_shape_id)) {
1974 RBASIC_SET_SHAPE_ID(fields_obj, target_shape_id);
1975 }
1976 }
1977
1978 return fields_obj;
1979}
1980
1981static attr_index_t
1982generic_field_set(VALUE obj, shape_id_t target_shape_id, ID field_name, VALUE val)
1983{
1984 if (!field_name) {
1985 field_name = RSHAPE_EDGE_NAME(target_shape_id);
1986 RUBY_ASSERT(field_name);
1987 }
1988
1989 const VALUE original_fields_obj = rb_obj_fields(obj, field_name);
1990 // Readers of a shareable object's fields take no lock, so never mutate a published fields_obj.
1991 bool concurrent = rb_multi_ractor_p() && RB_OBJ_SHAREABLE_P(obj);
1992 VALUE fields_obj = imemo_fields_set(obj, original_fields_obj, target_shape_id, field_name, val, concurrent);
1993
1994 rb_obj_set_fields(obj, fields_obj, field_name, original_fields_obj);
1995 return rb_shape_complex_p(target_shape_id) ? ATTR_INDEX_NOT_SET : RSHAPE_INDEX(target_shape_id);
1996}
1997
1998static shape_id_t
1999generic_shape_ivar(VALUE obj, ID id, bool *new_ivar_out)
2000{
2001 bool new_ivar = false;
2002 shape_id_t current_shape_id = RBASIC_SHAPE_ID(obj);
2003 shape_id_t target_shape_id = current_shape_id;
2004
2005 if (!rb_shape_complex_p(current_shape_id)) {
2006 if (!rb_shape_find_ivar(current_shape_id, id, &target_shape_id)) {
2007 new_ivar = true;
2008 target_shape_id = rb_obj_shape_transition_add_ivar(obj, id);
2009 }
2010 }
2011
2012 *new_ivar_out = new_ivar;
2013 return target_shape_id;
2014}
2015
2016static attr_index_t
2017generic_ivar_set(VALUE obj, ID id, VALUE val)
2018{
2019 bool dontcare;
2020 shape_id_t target_shape_id = generic_shape_ivar(obj, id, &dontcare);
2021 return generic_field_set(obj, target_shape_id, id, val);
2022}
2023
2024static attr_index_t
2025obj_field_set(VALUE obj, shape_id_t target_shape_id, ID field_name, VALUE val)
2026{
2027 // may be T_OBJECT or imemo_fields
2028 VALUE fields_obj = ROBJECT_FIELDS_OBJ(obj);
2029 shape_id_t current_shape_id = RBASIC_SHAPE_ID(obj);
2030
2031 if (UNLIKELY(rb_shape_complex_p(target_shape_id))) {
2032 if (UNLIKELY(!rb_shape_complex_p(current_shape_id))) {
2033 current_shape_id = rb_obj_convert_too_complex(obj, fields_obj, current_shape_id);
2034 fields_obj = ROBJECT_FIELDS_OBJ(obj);
2035 }
2036
2037 RUBY_ASSERT(rb_obj_shape_complex_p(obj));
2038 RUBY_ASSERT(rb_obj_shape_complex_p(fields_obj));
2039
2040 if (!field_name) {
2041 field_name = RSHAPE_EDGE_NAME(target_shape_id);
2042 RUBY_ASSERT(field_name);
2043 }
2044
2045 st_insert(rb_imemo_fields_complex_tbl(fields_obj), (st_data_t)field_name, (st_data_t)val);
2046 RB_OBJ_WRITTEN(fields_obj, Qundef, val);
2047
2048 RBASIC_SET_SHAPE_ID(obj, target_shape_id);
2049 if (obj != fields_obj) {
2050 RBASIC_SET_SHAPE_ID(fields_obj, target_shape_id);
2051 }
2052
2053 return ATTR_INDEX_NOT_SET;
2054 }
2055 else {
2056 attr_index_t index = RSHAPE_INDEX(target_shape_id);
2057
2058 if (index < RSHAPE_LEN(current_shape_id)) {
2059 // Replace existing value;
2060 RB_OBJ_WRITE(fields_obj, &rb_imemo_fields_ptr(fields_obj)[index], val);
2061 return index;
2062 }
2063
2064 RUBY_ASSERT(index == RSHAPE_LEN(current_shape_id));
2065
2066 if (UNLIKELY(index >= RSHAPE_CAPACITY(current_shape_id))) {
2067 fields_obj = imemo_fields_copy_append(obj, fields_obj, current_shape_id, target_shape_id, val);
2068 ROBJECT_SET_EXTENDED(obj, fields_obj);
2069 RBASIC_SET_FULL_SHAPE_ID(obj, rb_shape_transition_layout(target_shape_id, SHAPE_ID_LAYOUT_EXTENDED));
2070 }
2071 else {
2072 RB_OBJ_WRITE(fields_obj, &rb_imemo_fields_ptr(fields_obj)[index], val);
2073 RBASIC_SET_SHAPE_ID(obj, target_shape_id);
2074 }
2075
2076 if (obj != fields_obj) {
2077 RBASIC_SET_SHAPE_ID(fields_obj, target_shape_id);
2078 }
2079
2080 return index;
2081 }
2082}
2083
2084static attr_index_t
2085obj_ivar_set(VALUE obj, ID id, VALUE val)
2086{
2087 bool dontcare;
2088 shape_id_t target_shape_id = generic_shape_ivar(obj, id, &dontcare);
2089 return obj_field_set(obj, target_shape_id, id, val);
2090}
2091
2092void
2093rb_check_ivar_modifiable(VALUE obj)
2094{
2095 if (UNLIKELY(!RB_FL_ABLE(obj) || rb_shape_frozen_p(RBASIC_SHAPE_ID(obj)))) {
2096 rb_check_frozen(obj);
2097
2098 RUBY_ASSERT(RB_OBJ_SHAREABLE_P(obj), "unfrozen object with a frozen shape must be shareable");
2099
2100 rb_raise(rb_eRactorIsolationError,
2101 "can't modify instance variables of a shareable %"PRIsVALUE,
2102 rb_obj_class(obj));
2103 }
2104 else if (UNLIKELY(CHILLED_STRING_P(obj))) {
2105 CHILLED_STRING_MUTATED(obj);
2106 }
2107
2108 RUBY_ASSERT(!RB_OBJ_FROZEN_RAW(obj), "frozen object with an unfrozen shape");
2109}
2110
2111/* Set the instance variable +val+ on object +obj+ at ivar name +id+.
2112 * This function only works with T_OBJECT objects, so make sure
2113 * +obj+ is of type T_OBJECT before using this function.
2114 */
2115VALUE
2116rb_vm_set_ivar_id(VALUE obj, ID id, VALUE val)
2117{
2118 rb_check_ivar_modifiable(obj);
2119 obj_ivar_set(obj, id, val);
2120 return val;
2121}
2122
2123void
2125{
2126 if (RB_FL_ABLE(x)) {
2128 if (TYPE(x) == T_STRING) {
2129 RB_FL_UNSET_RAW(x, FL_USER2); // STR_CHILLED
2130 }
2131
2132 // rb_obj_freeze_inline(String)
2133 shape_id_t shape_id = rb_obj_shape_transition_frozen(x);
2134 switch (BUILTIN_TYPE(x)) {
2135 case T_CLASS:
2136 case T_MODULE:
2137 {
2138 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(x);
2139 if (fields_obj) {
2140 rb_obj_freeze_inline(fields_obj);
2141 }
2142 else {
2143 fields_obj = rb_imemo_fields_new(x, ROOT_SHAPE_ID, true);
2144 rb_obj_freeze_inline(fields_obj);
2145 RCLASS_WRITABLE_SET_FIELDS_OBJ(x, fields_obj);
2146 }
2147 }
2148 // FIXME: How to do multi-shape?
2149 RBASIC_SET_SHAPE_ID(x, shape_id);
2150 break;
2151 default:
2152 RBASIC_SET_SHAPE_ID(x, shape_id);
2153 break;
2154 }
2155
2156 if (RBASIC_CLASS(x) && RCLASS_SINGLETON_P(RBASIC_CLASS(x))) {
2158 }
2159 }
2160}
2161
2162static attr_index_t class_ivar_set(VALUE obj, ID id, VALUE val, bool *new_ivar);
2163
2164static attr_index_t
2165ivar_set(VALUE obj, ID id, VALUE val)
2166{
2167 RB_DEBUG_COUNTER_INC(ivar_set_base);
2168
2169 switch (BUILTIN_TYPE(obj)) {
2170 case T_OBJECT:
2171 return obj_ivar_set(obj, id, val);
2172 case T_CLASS:
2173 case T_MODULE:
2174 {
2175 class_ivar_set_ractor_check(obj, id);
2176 bool dontcare;
2177 return class_ivar_set(obj, id, val, &dontcare);
2178 }
2179 default:
2180 return generic_ivar_set(obj, id, val);
2181 }
2182}
2183
2184VALUE
2186{
2187 rb_check_ivar_modifiable(obj);
2188 ivar_set(obj, id, val);
2189 return val;
2190}
2191
2192attr_index_t
2193rb_ivar_set_index(VALUE obj, ID id, VALUE val)
2194{
2195 return ivar_set(obj, id, val);
2196}
2197
2198void
2199rb_ivar_set_internal(VALUE obj, ID id, VALUE val)
2200{
2201 // should be internal instance variable name (no @ prefix)
2202 VM_ASSERT(!rb_is_instance_id(id));
2203
2204 ivar_set(obj, id, val);
2205}
2206
2207attr_index_t
2208rb_obj_field_set(VALUE obj, shape_id_t target_shape_id, ID field_name, VALUE val)
2209{
2210 switch (BUILTIN_TYPE(obj)) {
2211 case T_OBJECT:
2212 return obj_field_set(obj, target_shape_id, field_name, val);
2213 case T_CLASS:
2214 case T_MODULE:
2215 // The only field is object_id and T_CLASS handle it differently.
2216 rb_bug("Unreachable");
2217 break;
2218 default:
2219 return generic_field_set(obj, target_shape_id, field_name, val);
2220 }
2221}
2222
2223static VALUE
2224ivar_defined0(VALUE obj, ID id)
2225{
2226 if (rb_obj_shape_complex_p(obj)) {
2227 // defined? doesn't require ractor checks
2228 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2229 st_table *table = rb_imemo_fields_complex_tbl(fields_obj);
2230
2231 VALUE idx;
2232 if (!table || !rb_st_lookup(table, id, &idx)) {
2233 return Qfalse;
2234 }
2235
2236 return Qtrue;
2237 }
2238 else {
2239 attr_index_t index;
2240 return RBOOL(rb_shape_get_iv_index(RBASIC_SHAPE_ID(obj), id, &index));
2241 }
2242}
2243
2244VALUE
2246{
2247 if (SPECIAL_CONST_P(obj)) return Qfalse;
2248
2249 VALUE defined = Qfalse;
2250 switch (BUILTIN_TYPE(obj)) {
2251 case T_CLASS:
2252 case T_MODULE:
2253 {
2254 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
2255 if (fields_obj) {
2256 defined = ivar_defined0(fields_obj, id);
2257 }
2258 }
2259 break;
2260 default:
2261 defined = ivar_defined0(obj, id);
2262 break;
2263 }
2264 return defined;
2265}
2266
2268 VALUE obj;
2269 struct gen_fields_tbl *fields_tbl;
2270 st_data_t arg;
2271 rb_ivar_foreach_callback_func *func;
2272 VALUE *fields;
2273 shape_id_t shape_id;
2274 bool ivar_only;
2275};
2276
2277static int
2278iterate_over_shapes_callback(shape_id_t shape_id, void *data)
2279{
2280 struct iv_itr_data *itr_data = data;
2281
2282 if (itr_data->ivar_only && !RSHAPE_TYPE_P(shape_id, SHAPE_IVAR)) {
2283 return ST_CONTINUE;
2284 }
2285
2286 VALUE *fields;
2287 switch (BUILTIN_TYPE(itr_data->obj)) {
2288 case T_OBJECT:
2289 RUBY_ASSERT(!rb_obj_shape_complex_p(itr_data->obj));
2290 fields = ROBJECT_FIELDS(itr_data->obj);
2291 break;
2292 case T_IMEMO:
2293 RUBY_ASSERT(IMEMO_TYPE_P(itr_data->obj, imemo_fields));
2294 RUBY_ASSERT(!rb_obj_shape_complex_p(itr_data->obj));
2295
2296 fields = rb_imemo_fields_ptr(itr_data->obj);
2297 break;
2298 default:
2299 rb_bug("Unreachable");
2300 }
2301
2302 RUBY_ASSERT(itr_data->shape_id == RBASIC_SHAPE_ID(itr_data->obj));
2303
2304 VALUE val = fields[RSHAPE_INDEX(shape_id)];
2305 int ret = itr_data->func(RSHAPE_EDGE_NAME(shape_id), val, itr_data->arg);
2306
2307 RUBY_ASSERT(itr_data->shape_id == RBASIC_SHAPE_ID(itr_data->obj));
2308
2309 return ret;
2310}
2311
2312/*
2313 * Returns a flag to stop iterating depending on the result of +callback+.
2314 */
2315static void
2316iterate_over_shapes(shape_id_t shape_id, rb_ivar_foreach_callback_func *callback, struct iv_itr_data *itr_data)
2317{
2318 rb_shape_foreach_field(shape_id, iterate_over_shapes_callback, itr_data);
2319}
2320
2321static int
2322each_hash_iv(st_data_t id, st_data_t val, st_data_t data)
2323{
2324 struct iv_itr_data * itr_data = (struct iv_itr_data *)data;
2325 rb_ivar_foreach_callback_func *callback = itr_data->func;
2326 if ((ID)id == rb_shape_tree.id_object_id) {
2327 return ST_CONTINUE;
2328 }
2329 return callback((ID)id, (VALUE)val, itr_data->arg);
2330}
2331
2332static void
2333obj_fields_each(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only)
2334{
2335 struct iv_itr_data itr_data = {
2336 .obj = obj,
2337 .arg = arg,
2338 .func = func,
2339 .ivar_only = ivar_only,
2340 };
2341
2342 VALUE fields_obj = ROBJECT_FIELDS_OBJ(obj);
2343 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
2344
2345 if (rb_shape_complex_p(shape_id)) {
2346 st_foreach_safe(rb_imemo_fields_complex_tbl(fields_obj), each_hash_iv, (st_data_t)&itr_data);
2347 }
2348 else {
2349 itr_data.fields = rb_imemo_fields_ptr(fields_obj);
2350 itr_data.shape_id = shape_id;
2351 iterate_over_shapes(shape_id, func, &itr_data);
2352 }
2353}
2354
2355static void
2356imemo_fields_each(VALUE fields_obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only)
2357{
2358 IMEMO_TYPE_P(fields_obj, imemo_fields);
2359
2360 struct iv_itr_data itr_data = {
2361 .obj = fields_obj,
2362 .arg = arg,
2363 .func = func,
2364 .ivar_only = ivar_only,
2365 };
2366
2367 shape_id_t shape_id = RBASIC_SHAPE_ID(fields_obj);
2368 if (rb_shape_complex_p(shape_id)) {
2369 rb_st_foreach(rb_imemo_fields_complex_tbl(fields_obj), each_hash_iv, (st_data_t)&itr_data);
2370 }
2371 else {
2372 itr_data.fields = rb_imemo_fields_ptr(fields_obj);
2373 itr_data.shape_id = shape_id;
2374 iterate_over_shapes(shape_id, func, &itr_data);
2375 }
2376}
2377
2378void
2380{
2381 VALUE new_fields_obj;
2382
2383 rb_check_frozen(dest);
2384
2385 if (!rb_obj_gen_fields_p(obj)) {
2386 return;
2387 }
2388
2389 shape_id_t src_shape_id = rb_obj_shape_id(obj);
2390
2391 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2392 if (fields_obj) {
2393 unsigned long src_num_ivs = rb_ivar_count(fields_obj);
2394 if (!src_num_ivs) {
2396 return;
2397 }
2398
2399 shape_id_t initial_shape_id = rb_obj_shape_id(dest);
2400 shape_id_t dest_shape_id = rb_shape_rebuild(initial_shape_id, src_shape_id);
2401
2402 if (UNLIKELY(rb_shape_complex_p(dest_shape_id))) {
2403 rb_obj_replace_fields(dest, rb_obj_complex_fields_build(obj));
2404 return;
2405 }
2406
2407 if (!RSHAPE_LEN(dest_shape_id)) {
2408 RBASIC_SET_SHAPE_ID(dest, dest_shape_id);
2409 return;
2410 }
2411
2412 new_fields_obj = rb_imemo_fields_new(dest, dest_shape_id, RB_OBJ_SHAREABLE_P(dest));
2413 VALUE *src_buf = rb_imemo_fields_ptr(fields_obj);
2414 VALUE *dest_buf = rb_imemo_fields_ptr(new_fields_obj);
2415 rb_shape_copy_fields(new_fields_obj, dest_buf, dest_shape_id, src_buf, src_shape_id);
2416
2417 rb_obj_replace_fields(dest, new_fields_obj);
2418 }
2419}
2420
2421/* Reference updating for compaction: walk the generic_fields table under the lock,
2422 * from a local GC's update phase, because moving a host in our own objspace leaves the
2423 * table's keys and values stale. This only updates; it never decides liveness. */
2424void
2425rb_generic_fields_shared_table_foreach(void (*cb)(struct st_table *tbl, void *arg), void *arg)
2426{
2427 rb_native_mutex_lock(&GET_VM()->ractor.generic_fields_lock);
2428 if (generic_fields_tbl_ != NULL) {
2429 cb(generic_fields_tbl_, arg);
2430 }
2431 rb_native_mutex_unlock(&GET_VM()->ractor.generic_fields_lock);
2432}
2433
2434/* Call cb(tbl, arg) for the single global generic_fields table. Used by the global
2435 * GC's weak pass and by compaction's reference update; both run under the barrier, so
2436 * the walk needs no lock. */
2437void
2438rb_generic_fields_tables_foreach(void (*cb)(struct st_table *tbl, void *arg), void *arg)
2439{
2440 if (generic_fields_tbl_ != NULL) {
2441 cb(generic_fields_tbl_, arg);
2442 }
2443}
2444
2445void
2446rb_field_foreach(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg, bool ivar_only)
2447{
2448 if (SPECIAL_CONST_P(obj)) return;
2449 switch (BUILTIN_TYPE(obj)) {
2450 case T_IMEMO:
2451 if (IMEMO_TYPE_P(obj, imemo_fields)) {
2452 imemo_fields_each(obj, func, arg, ivar_only);
2453 }
2454 break;
2455 case T_OBJECT:
2456 obj_fields_each(obj, func, arg, ivar_only);
2457 break;
2458 case T_CLASS:
2459 case T_MODULE:
2460 {
2461 // No owner check: every caller of this walk uses the names only for a
2462 // class/module. Values are checked where they are read (rb_ivar_lookup).
2463 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
2464 if (fields_obj) {
2465 imemo_fields_each(fields_obj, func, arg, ivar_only);
2466 }
2467 }
2468 break;
2469 default:
2470 {
2471 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2472 if (fields_obj) {
2473 imemo_fields_each(fields_obj, func, arg, ivar_only);
2474 }
2475 }
2476 break;
2477 }
2478}
2479
2481 ID name;
2482 VALUE val;
2483};
2484
2485static int
2486collect_ivar_i(ID id, VALUE val, st_data_t arg)
2487{
2488 struct ivar_buf_entry **pos = (struct ivar_buf_entry **)arg;
2489 (*pos)->name = id;
2490 (*pos)->val = val;
2491 (*pos)++;
2492 return ST_CONTINUE;
2493}
2494
2495void
2496rb_ivar_foreach(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg)
2497{
2498 rb_field_foreach(obj, func, arg, true);
2499}
2500
2501void
2502rb_ivar_foreach_buffered(VALUE obj, rb_ivar_foreach_callback_func *func, st_data_t arg)
2503{
2504 st_index_t count = rb_ivar_count(obj);
2505 if (count == 0) return;
2506
2507 VALUE tmpbuf;
2508 struct ivar_buf_entry *buf = ALLOCV_N(struct ivar_buf_entry, tmpbuf, count);
2509 struct ivar_buf_entry *pos = buf;
2510
2511 rb_field_foreach(obj, collect_ivar_i, (st_data_t)&pos, true);
2512 RUBY_ASSERT((st_index_t)(pos - buf) == count);
2513
2514 for (st_index_t i = 0; i < count; i++) {
2515 if (func(buf[i].name, buf[i].val, arg) == ST_STOP) break;
2516 }
2517
2518 ALLOCV_END(tmpbuf);
2519}
2520
2521st_index_t
2523{
2524 if (SPECIAL_CONST_P(obj)) return 0;
2525
2526 st_index_t iv_count = 0;
2527 VALUE fields_obj = rb_obj_fields_no_ractor_check(obj);
2528
2529 if (fields_obj) {
2530 if (rb_obj_shape_complex_p(fields_obj)) {
2531 iv_count = rb_st_table_size(rb_imemo_fields_complex_tbl(fields_obj));
2532 }
2533 else {
2534 iv_count = RBASIC_FIELDS_COUNT(obj);
2535 }
2536 }
2537
2538 if (rb_obj_shape_has_id(obj)) {
2539 iv_count--;
2540 }
2541
2542 return iv_count;
2543}
2544
2545static int
2546ivar_i(ID key, VALUE v, st_data_t a)
2547{
2548 VALUE ary = (VALUE)a;
2549
2550 if (rb_is_instance_id(key)) {
2551 rb_ary_push(ary, ID2SYM(key));
2552 }
2553 return ST_CONTINUE;
2554}
2555
2556/*
2557 * call-seq:
2558 * obj.instance_variables -> array
2559 *
2560 * Returns an array of instance variable names for the receiver. Note
2561 * that simply defining an accessor does not create the corresponding
2562 * instance variable.
2563 *
2564 * class Fred
2565 * attr_accessor :a1
2566 * def initialize
2567 * @iv = 3
2568 * end
2569 * end
2570 * Fred.new.instance_variables #=> [:@iv]
2571 */
2572
2573VALUE
2575{
2577 rb_ivar_foreach(obj, ivar_i, ary);
2578 return ary;
2579}
2580
2581#define rb_is_constant_id rb_is_const_id
2582#define rb_is_constant_name rb_is_const_name
2583#define id_for_var(obj, name, part, type) \
2584 id_for_var_message(obj, name, type, "'%1$s' is not allowed as "#part" "#type" variable name")
2585#define id_for_var_message(obj, name, type, message) \
2586 check_id_type(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
2587static ID
2588check_id_type(VALUE obj, VALUE *pname,
2589 int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
2590 const char *message, size_t message_len)
2591{
2592 ID id = rb_check_id(pname);
2593 VALUE name = *pname;
2594
2595 if (id ? !valid_id_p(id) : !valid_name_p(name)) {
2596 rb_name_err_raise_str(rb_fstring_new(message, message_len),
2597 obj, name);
2598 }
2599 return id;
2600}
2601
2602/*
2603 * call-seq:
2604 * obj.remove_instance_variable(symbol) -> obj
2605 * obj.remove_instance_variable(string) -> obj
2606 *
2607 * Removes the named instance variable from <i>obj</i>, returning that
2608 * variable's value. The name can be passed as a symbol or as a string.
2609 *
2610 * class Dummy
2611 * attr_reader :var
2612 * def initialize
2613 * @var = 99
2614 * end
2615 * def remove
2616 * remove_instance_variable(:@var)
2617 * end
2618 * end
2619 * d = Dummy.new
2620 * d.var #=> 99
2621 * d.remove #=> 99
2622 * d.var #=> nil
2623 */
2624
2625VALUE
2627{
2628 const ID id = id_for_var(obj, name, an, instance);
2629
2630 // Frozen check comes here because it's expected that we raise a
2631 // NameError (from the id_for_var check) before we raise a FrozenError
2632 rb_check_frozen(obj);
2633
2634 if (id) {
2635 VALUE val = rb_ivar_delete(obj, id, Qundef);
2636
2637 if (!UNDEF_P(val)) return val;
2638 }
2639
2640 rb_name_err_raise("instance variable %1$s not defined",
2641 obj, name);
2643}
2644
2645NORETURN(static void uninitialized_constant(VALUE, VALUE));
2646static void
2647uninitialized_constant(VALUE klass, VALUE name)
2648{
2649 if (klass && rb_class_real(klass) != rb_cObject)
2650 rb_name_err_raise("uninitialized constant %2$s::%1$s",
2651 klass, name);
2652 else
2653 rb_name_err_raise("uninitialized constant %1$s",
2654 klass, name);
2655}
2656
2657VALUE
2658rb_const_missing(VALUE klass, VALUE name)
2659{
2660 VALUE value = rb_funcallv(klass, idConst_missing, 1, &name);
2661 rb_vm_inc_const_missing_count();
2662 return value;
2663}
2664
2665
2666/*
2667 * call-seq:
2668 * mod.const_missing(sym) -> obj
2669 *
2670 * Invoked when a reference is made to an undefined constant in
2671 * <i>mod</i>. It is passed a symbol for the undefined constant, and
2672 * returns a value to be used for that constant. For example, consider:
2673 *
2674 * def Foo.const_missing(name)
2675 * name # return the constant name as Symbol
2676 * end
2677 *
2678 * Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned
2679 *
2680 * As the example above shows, +const_missing+ is not required to create the
2681 * missing constant in <i>mod</i>, though that is often a side-effect. The
2682 * caller gets its return value when triggered. If the constant is also defined,
2683 * further lookups won't hit +const_missing+ and will return the value stored in
2684 * the constant as usual. Otherwise, +const_missing+ will be invoked again.
2685 *
2686 * In the next example, when a reference is made to an undefined constant,
2687 * +const_missing+ attempts to load a file whose path is the lowercase version
2688 * of the constant name (thus class <code>Fred</code> is assumed to be in file
2689 * <code>fred.rb</code>). If defined as a side-effect of loading the file, the
2690 * method returns the value stored in the constant. This implements an autoload
2691 * feature similar to Kernel#autoload and Module#autoload, though it differs in
2692 * important ways.
2693 *
2694 * def Object.const_missing(name)
2695 * @looked_for ||= {}
2696 * str_name = name.to_s
2697 * raise "Constant not found: #{name}" if @looked_for[str_name]
2698 * @looked_for[str_name] = 1
2699 * file = str_name.downcase
2700 * require file
2701 * const_get(name, false)
2702 * end
2703 *
2704 */
2705
2706VALUE
2707rb_mod_const_missing(VALUE klass, VALUE name)
2708{
2709 rb_execution_context_t *ec = GET_EC();
2710 VALUE ref = ec->private_const_reference;
2711 rb_vm_pop_cfunc_frame();
2712 if (ref) {
2713 ec->private_const_reference = 0;
2714 rb_name_err_raise("private constant %2$s::%1$s referenced", ref, name);
2715 }
2716 uninitialized_constant(klass, name);
2717
2719}
2720
2721// Every autoload constant has exactly one instance of autoload_const, stored in `autoload_features`. Since multiple autoload constants can refer to the same file, every `autoload_const` refers to a de-duplicated `autoload_data`.
2723 // The linked list node of all constants which are loaded by the related autoload feature.
2724 struct ccan_list_node cnode; /* <=> autoload_data.constants */
2725
2726 // The shared "autoload_data" if multiple constants are defined from the same feature.
2727 VALUE autoload_data_value;
2728
2729 // The box object when the autoload is called in a user box
2730 // Otherwise, Qnil means the root box
2731 VALUE box_value;
2732
2733 // The module we are loading a constant into.
2734 VALUE module;
2735
2736 // The file that called autoload
2737 VALUE autoload_call_file;
2738
2739 // The name of the constant we are loading.
2740 ID name;
2741
2742 // The value of the constant (after it's loaded).
2743 VALUE value;
2744
2745 // The constant entry flags which need to be re-applied after autoloading the feature.
2746 rb_const_flag_t flag;
2747
2748 // The source file and line number that defined this constant (different from feature path).
2749 VALUE file;
2750 int line;
2751};
2752
2753// Each `autoload_data` uniquely represents a specific feature which can be loaded, and a list of constants which it is able to define. We use a mutex to coordinate multiple threads trying to load the same feature.
2755 // The feature path to require to load this constant.
2756 VALUE feature;
2757
2758 // The mutex which is protecting autoloading this feature.
2759 VALUE mutex;
2760
2761 // The process fork serial number since the autoload mutex will become invalid on fork.
2762 rb_serial_t fork_gen;
2763
2764 // The linked list of all constants that are going to be loaded by this autoload.
2765 struct ccan_list_head constants; /* <=> autoload_const.cnode */
2766};
2767
2768static void
2769autoload_data_mark_and_move(void *ptr)
2770{
2771 struct autoload_data *p = ptr;
2772
2773 rb_gc_mark_and_move(&p->feature);
2774 rb_gc_mark_and_move(&p->mutex);
2775}
2776
2777static void
2778autoload_data_free(void *ptr)
2779{
2780 struct autoload_data *p = ptr;
2781
2782 struct autoload_const *autoload_const, *next;
2783 ccan_list_for_each_safe(&p->constants, autoload_const, next, cnode) {
2784 ccan_list_del_init(&autoload_const->cnode);
2785 }
2786
2787 SIZED_FREE(p);
2788}
2789
2790static size_t
2791autoload_data_memsize(const void *ptr)
2792{
2793 return sizeof(struct autoload_data);
2794}
2795
2796static const rb_data_type_t autoload_data_type = {
2797 "autoload_data",
2798 {autoload_data_mark_and_move, autoload_data_free, autoload_data_memsize, autoload_data_mark_and_move},
2799 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
2800};
2801
2802static void
2803autoload_const_mark_and_move(void *ptr)
2804{
2805 struct autoload_const *ac = ptr;
2806
2807 rb_gc_mark_and_move(&ac->module);
2808 rb_gc_mark_and_move(&ac->autoload_call_file);
2809 rb_gc_mark_and_move(&ac->autoload_data_value);
2810 rb_gc_mark_and_move(&ac->value);
2811 rb_gc_mark_and_move(&ac->file);
2812 rb_gc_mark_and_move(&ac->box_value);
2813}
2814
2815static size_t
2816autoload_const_memsize(const void *ptr)
2817{
2818 return sizeof(struct autoload_const);
2819}
2820
2821static void
2822autoload_const_free(void *ptr)
2823{
2824 struct autoload_const *autoload_const = ptr;
2825
2826 ccan_list_del(&autoload_const->cnode);
2827 SIZED_FREE(autoload_const);
2828}
2829
2830static const rb_data_type_t autoload_const_type = {
2831 "autoload_const",
2832 {autoload_const_mark_and_move, autoload_const_free, autoload_const_memsize, autoload_const_mark_and_move,},
2833 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
2834};
2835
2836static struct autoload_data *
2837get_autoload_data(VALUE autoload_const_value, struct autoload_const **autoload_const_pointer)
2838{
2839 struct autoload_const *autoload_const = rb_check_typeddata(autoload_const_value, &autoload_const_type);
2840
2841 VALUE autoload_data_value = autoload_const->autoload_data_value;
2842 struct autoload_data *autoload_data = rb_check_typeddata(autoload_data_value, &autoload_data_type);
2843
2844 /* do not reach across stack for ->state after forking: */
2845 if (autoload_data && autoload_data->fork_gen != GET_VM()->fork_gen) {
2846 RB_OBJ_WRITE(autoload_data_value, &autoload_data->mutex, Qnil);
2847 autoload_data->fork_gen = 0;
2848 }
2849
2850 if (autoload_const_pointer) *autoload_const_pointer = autoload_const;
2851
2852 return autoload_data;
2853}
2854
2855// The autoload entry of the constant `id` of `mod`, or 0.
2856static VALUE
2857autoload_entry(VALUE mod, ID id)
2858{
2859 rb_const_entry_t *ce = rb_const_lookup(mod, id);
2860 if (!ce || !UNDEF_P(ce->value)) return 0;
2861 VM_ASSERT(rb_typeddata_is_kind_of(ce->u.autoload_const, &autoload_const_type));
2862 return ce->u.autoload_const;
2863}
2864
2865
2866static void const_set(VALUE klass, ID id, VALUE val);
2867static void const_added(VALUE klass, ID const_name);
2868
2870 VALUE module;
2871 ID name;
2872 VALUE feature;
2873 VALUE box_value;
2874};
2875
2876static VALUE
2877autoload_feature_lookup_or_create(VALUE feature, struct autoload_data **autoload_data_pointer)
2878{
2879 RUBY_ASSERT_MUTEX_OWNED(autoload_mutex);
2880 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
2881
2882 VALUE autoload_data_value = rb_hash_aref(autoload_features, feature);
2884
2885 if (NIL_P(autoload_data_value)) {
2886 autoload_data_value = TypedData_Make_Struct(0, struct autoload_data, &autoload_data_type, autoload_data);
2887 RB_OBJ_WRITE(autoload_data_value, &autoload_data->feature, feature);
2888 RB_OBJ_WRITE(autoload_data_value, &autoload_data->mutex, Qnil);
2889 ccan_list_head_init(&autoload_data->constants);
2890
2891 if (autoload_data_pointer) *autoload_data_pointer = autoload_data;
2892
2893 rb_hash_aset(autoload_features, feature, autoload_data_value);
2894 }
2895 else if (autoload_data_pointer) {
2896 *autoload_data_pointer = rb_check_typeddata(autoload_data_value, &autoload_data_type);
2897 }
2898
2899 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
2900 return autoload_data_value;
2901}
2902
2903static VALUE
2904autoload_synchronized(VALUE _arguments)
2905{
2906 struct autoload_arguments *arguments = (struct autoload_arguments *)_arguments;
2907
2908 rb_const_entry_t *constant_entry = rb_const_lookup(arguments->module, arguments->name);
2909 if (constant_entry && !UNDEF_P(constant_entry->value)) {
2910 return Qfalse;
2911 }
2912
2913 // Reset any state associated with any previous constant:
2914 const_set(arguments->module, arguments->name, Qundef);
2915 constant_entry = rb_const_lookup(arguments->module, arguments->name);
2916
2917 // Ensure the string is uniqued since we use an identity lookup:
2918 VALUE feature = rb_fstring(arguments->feature);
2919
2921 VALUE autoload_data_value = autoload_feature_lookup_or_create(feature, &autoload_data);
2922
2923 {
2925 VALUE autoload_const_value = TypedData_Make_Struct(0, struct autoload_const, &autoload_const_type, autoload_const);
2926 RB_OBJ_WRITE(autoload_const_value, &autoload_const->box_value, arguments->box_value);
2927 RB_OBJ_WRITE(autoload_const_value, &autoload_const->module, arguments->module);
2928 RB_OBJ_WRITE(autoload_const_value, &autoload_const->autoload_call_file, constant_entry->u.file);
2929 autoload_const->name = arguments->name;
2930 autoload_const->value = Qundef;
2931 autoload_const->flag = CONST_PUBLIC;
2932 RB_OBJ_WRITE(autoload_const_value, &autoload_const->autoload_data_value, autoload_data_value);
2933 ccan_list_add_tail(&autoload_data->constants, &autoload_const->cnode);
2934 RB_OBJ_WRITE(arguments->module, &constant_entry->u.autoload_const, autoload_const_value);
2935 }
2936
2937 return Qtrue;
2938}
2939
2940void
2941rb_autoload_str(VALUE module, ID name, VALUE feature)
2942{
2943 const rb_box_t *box = rb_current_box();
2944 VALUE current_box_value = rb_get_box_object((rb_box_t *)box);
2945
2946 if (!rb_is_const_id(name)) {
2947 rb_raise(rb_eNameError, "autoload must be constant name: %"PRIsVALUE"", QUOTE_ID(name));
2948 }
2949
2950 rb_class_owner_check(module);
2951
2952 Check_Type(feature, T_STRING);
2953 if (!RSTRING_LEN(feature)) {
2954 rb_raise(rb_eArgError, "empty feature name");
2955 }
2956
2957 struct autoload_arguments arguments = {
2958 .module = module,
2959 .name = name,
2960 .feature = feature,
2961 .box_value = current_box_value,
2962 };
2963
2964 VALUE result = rb_mutex_synchronize(autoload_mutex, autoload_synchronized, (VALUE)&arguments);
2965
2966 if (result == Qtrue) {
2967 const_added(module, name);
2968 }
2969}
2970
2971static void
2972autoload_delete(VALUE autoload_const_value)
2973{
2974 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
2975
2976 VM_ASSERT(rb_typeddata_is_kind_of(autoload_const_value, &autoload_const_type));
2977
2979 struct autoload_data *autoload_data = get_autoload_data(autoload_const_value, &autoload_const);
2980
2981 VM_ASSERT(autoload_data);
2982
2983 /*
2984 * we must delete here to avoid "already initialized" warnings
2985 * with parallel autoload. Using list_del_init here so list_del
2986 * works in autoload_const_free
2987 */
2988 ccan_list_del_init(&autoload_const->cnode);
2989
2990 if (ccan_list_empty(&autoload_data->constants)) {
2991 rb_hash_delete(autoload_features, autoload_data->feature);
2992 }
2993
2994 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
2995}
2996
2997static int
2998autoload_by_someone_else(struct autoload_data *ele)
2999{
3000 return ele->mutex != Qnil && RTEST(rb_mutex_locked_p(ele->mutex)) && !rb_mutex_owned_p(ele->mutex);
3001}
3002
3003static VALUE
3004check_autoload_required(VALUE mod, ID id, const char **loadingpath)
3005{
3006 VALUE autoload_const_value = autoload_entry(mod, id);
3008 const char *loading;
3009
3010 if (!autoload_const_value || !(autoload_data = get_autoload_data(autoload_const_value, 0))) {
3011 return 0;
3012 }
3013
3014 VALUE feature = autoload_data->feature;
3015
3016 /*
3017 * if somebody else is autoloading, we MUST wait for them, since
3018 * rb_provide_feature can provide a feature before autoload_const_set
3019 * completes. We must wait until autoload_const_set finishes in
3020 * the other thread.
3021 */
3022 if (autoload_by_someone_else(autoload_data)) {
3023 return autoload_const_value;
3024 }
3025
3026 loading = RSTRING_PTR(feature);
3027
3028 if (!rb_feature_provided(loading, &loading)) {
3029 return autoload_const_value;
3030 }
3031
3032 if (loadingpath && loading) {
3033 *loadingpath = loading;
3034 return autoload_const_value;
3035 }
3036
3037 return 0;
3038}
3039
3040static struct autoload_const *autoloading_const_entry(VALUE mod, ID id);
3041
3042int
3043rb_autoloading_value(VALUE mod, ID id, VALUE* value, rb_const_flag_t *flag)
3044{
3045 struct autoload_const *ac = autoloading_const_entry(mod, id);
3046 if (!ac) return FALSE;
3047
3048 if (value) {
3049 *value = ac->value;
3050 }
3051
3052 if (flag) {
3053 *flag = ac->flag;
3054 }
3055
3056 return TRUE;
3057}
3058
3059static int
3060autoload_by_current(struct autoload_data *ele)
3061{
3062 return ele->mutex != Qnil && rb_mutex_owned_p(ele->mutex);
3063}
3064
3065// If there is an autoloading constant and it has been set by the current
3066// execution context, return it. This allows threads which are loading code to
3067// refer to their own autoloaded constants.
3068struct autoload_const *
3069autoloading_const_entry(VALUE mod, ID id)
3070{
3071 VALUE load = autoload_entry(mod, id);
3072 struct autoload_data *ele;
3073 struct autoload_const *ac;
3074
3075 // Find the autoloading state:
3076 if (!load || !(ele = get_autoload_data(load, &ac))) {
3077 // Couldn't be found:
3078 return 0;
3079 }
3080
3081 // Check if it's being loaded by the current thread/fiber:
3082 if (autoload_by_current(ele)) {
3083 if (!UNDEF_P(ac->value)) {
3084 return ac;
3085 }
3086 }
3087
3088 return 0;
3089}
3090
3091static int
3092autoload_defined_p(VALUE mod, ID id)
3093{
3094 rb_const_entry_t *ce = rb_const_lookup(mod, id);
3095
3096 // If there is no constant or the constant is not undefined (special marker for autoloading):
3097 if (!ce || !UNDEF_P(ce->value)) {
3098 // We are not autoloading:
3099 return 0;
3100 }
3101
3102 // Otherwise check if there is an autoload in flight right now:
3103 return !rb_autoloading_value(mod, id, NULL, NULL);
3104}
3105
3106/* const_tbl_update() runs under the VM lock, where it can neither warn nor
3107 * build the message: rb_warn() dispatches Warning.warn and writes to $stderr,
3108 * and formatting a "%"PRIsVALUE" calls #to_s. It records what to warn about
3109 * instead, and the caller warns once the lock is released. */
3111 ID id; /* 0 when there is nothing to warn about */
3112 VALUE module;
3113 VALUE file;
3114 int line;
3115};
3116
3117static void const_tbl_update(struct autoload_const *, int, struct const_warning *);
3118
3119static void
3120const_warning_emit(const struct const_warning *warning)
3121{
3122 if (!warning->id) return;
3123
3124 VALUE name = QUOTE_ID(warning->id);
3125 VALUE previous = Qnil;
3126
3127 if (!NIL_P(warning->file) && warning->line) {
3128 previous = rb_sprintf("\n%"PRIsVALUE":%d: warning: previous definition of %"PRIsVALUE" was here",
3129 warning->file, warning->line, name);
3130 }
3131
3132 if (warning->module == rb_cObject) {
3133 rb_warn("already initialized constant %"PRIsVALUE"%"PRIsVALUE"", name, previous);
3134 }
3135 else {
3136 rb_warn("already initialized constant %"PRIsVALUE"::%"PRIsVALUE"%"PRIsVALUE"",
3137 rb_class_name(warning->module), name, previous);
3138 }
3139}
3140
3142 VALUE module;
3143 ID name;
3144 int flag;
3145
3146 VALUE mutex;
3147
3148 // The specific constant which triggered the autoload code to fire:
3149 struct autoload_const *autoload_const;
3150
3151 // The parent autoload data which is shared between multiple constants:
3152 struct autoload_data *autoload_data;
3153};
3154
3155static VALUE
3156autoload_const_set(struct autoload_const *ac)
3157{
3158 check_before_mod_set(ac->module, ac->name, ac->value, "constant");
3159
3160 struct const_warning warning = {0};
3161 RB_VM_LOCKING() {
3162 const_tbl_update(ac, true, &warning);
3163 }
3164 const_warning_emit(&warning);
3165
3166 return 0; /* ignored */
3167}
3168
3169static VALUE
3170autoload_load_needed(VALUE _arguments)
3171{
3172 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3173
3174 const char *loading = 0, *src;
3175
3176 if (!autoload_defined_p(arguments->module, arguments->name)) {
3177 return Qfalse;
3178 }
3179
3180 VALUE autoload_const_value = check_autoload_required(arguments->module, arguments->name, &loading);
3181 if (!autoload_const_value) {
3182 return Qfalse;
3183 }
3184
3185 src = rb_sourcefile();
3186 if (src && loading && strcmp(src, loading) == 0) {
3187 return Qfalse;
3188 }
3189
3192 if (!(autoload_data = get_autoload_data(autoload_const_value, &autoload_const))) {
3193 return Qfalse;
3194 }
3195
3196 if (NIL_P(autoload_data->mutex)) {
3197 RB_OBJ_WRITE(autoload_const->autoload_data_value, &autoload_data->mutex, rb_mutex_new());
3198 autoload_data->fork_gen = GET_VM()->fork_gen;
3199 }
3200 else if (rb_mutex_owned_p(autoload_data->mutex)) {
3201 return Qfalse;
3202 }
3203
3204 arguments->mutex = autoload_data->mutex;
3205 arguments->autoload_const = autoload_const;
3206
3207 return autoload_const_value;
3208}
3209
3210static VALUE
3211autoload_apply_constants(VALUE _arguments)
3212{
3213 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
3214
3215 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3216
3217 struct autoload_const *autoload_const = 0; // for ccan_container_off_var()
3218 struct autoload_const *next;
3219
3220 // We use safe iteration here because `autoload_const_set` will eventually invoke
3221 // `autoload_delete` which will remove the constant from the linked list. In theory, once
3222 // the `autoload_data->constants` linked list is empty, we can remove it.
3223
3224 // Iterate over all constants and assign them:
3225 ccan_list_for_each_safe(&arguments->autoload_data->constants, autoload_const, next, cnode) {
3226 if (!UNDEF_P(autoload_const->value)) {
3227 autoload_const_set(autoload_const);
3228 }
3229 }
3230
3231 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
3232
3233 return Qtrue;
3234}
3235
3236// Require the feature and set the constants of the autoload.
3237static VALUE
3238autoload_require_and_apply(VALUE receiver, VALUE _arguments)
3239{
3240 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3241
3242 VALUE result = rb_funcall(receiver, rb_intern("require"), 1, arguments->autoload_data->feature);
3243 if (RTEST(result)) {
3244 return rb_mutex_synchronize(autoload_mutex, autoload_apply_constants, _arguments);
3245 }
3246 return result;
3247}
3248
3249static VALUE
3250autoload_feature_require_in_box(VALUE receiver, VALUE _arguments)
3251{
3252 rb_vm_frame_flag_set_box_require(GET_EC());
3253
3254 return autoload_require_and_apply(receiver, _arguments);
3255}
3256
3257static VALUE
3258autoload_feature_require(VALUE _arguments)
3259{
3260 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3261
3262 struct autoload_const *autoload_const = arguments->autoload_const;
3263 VALUE autoload_box_value = autoload_const->box_value;
3264
3265 // We save this for later use in autoload_apply_constants:
3266 arguments->autoload_data = rb_check_typeddata(autoload_const->autoload_data_value, &autoload_data_type);
3267
3268 /*
3269 * Clear the global cc cache table because the require method can be different from the current
3270 * box's one and it may cause inconsistent cc-cme states.
3271 * For example, the assertion below may fail in gccct_method_search();
3272 * VM_ASSERT(vm_cc_check_cme(cc, rb_callable_method_entry(klass, mid)))
3273 */
3274 rb_gccct_clear_table();
3275
3276 VALUE feature = arguments->autoload_data->feature;
3277 rb_box_t *box = NULL;
3278 if (rb_box_available() && BOX_OBJ_P(autoload_box_value)) {
3279 box = rb_get_box_t(autoload_box_value);
3280 }
3281
3282 if (box && box->top_self) {
3283 /*
3284 * Call `require` on the top self of the box that registered the autoload, in a frame
3285 * running in that box, so that `Kernel#require` decorations in the box (RubyGems,
3286 * Zeitwerk, etc.) are dispatched and the feature is loaded into that box.
3287 */
3288 return rb_vm_call_cfunc_in_box(box->top_self, autoload_feature_require_in_box,
3289 box->top_self, _arguments, feature, box);
3290 }
3291 return autoload_require_and_apply(rb_vm_top_self(), _arguments);
3292}
3293
3294static rb_const_entry_t *const_lookup(struct rb_id_table *tbl, ID id);
3295
3296// The box in which the feature of the autoload is required.
3297static const rb_box_t *
3298autoload_box(const struct autoload_const *ac)
3299{
3300 if (rb_box_available() && BOX_OBJ_P(ac->box_value)) {
3301 const rb_box_t *box = rb_get_box_t(ac->box_value);
3302 if (box->top_self) return box;
3303 }
3304 return rb_current_box();
3305}
3306
3307// The constant entry `id` of `mod` in the view of `box`.
3308static rb_const_entry_t *
3309const_lookup_in_box(VALUE mod, ID id, const rb_box_t *box)
3310{
3311 return const_lookup(RCLASSEXT_CONST_TBL(RCLASS_EXT_READABLE_IN_BOX(mod, box)), id);
3312}
3313
3314static VALUE
3315autoload_try_load(VALUE _arguments)
3316{
3317 struct autoload_load_arguments *arguments = (struct autoload_load_arguments*)_arguments;
3318
3319 // Load the feature and set the constants in the box that registered the autoload:
3320 VALUE result = autoload_feature_require(_arguments);
3321
3322 // After we loaded the feature, if the constant is not defined, we remove it completely:
3323 rb_const_entry_t *ce = rb_const_lookup(arguments->module, arguments->name);
3324
3325 // Copy the constant from the box that registered the autoload into the current box.
3326 // E.g., after a box B1 triggers the autoload, another box B2 with its own copy of the
3327 // module still has it; referring to it in B2 comes here too, as the require does nothing.
3328 if (ce && UNDEF_P(ce->value)) {
3329 rb_const_entry_t *loaded = const_lookup_in_box(arguments->module, arguments->name,
3330 autoload_box(arguments->autoload_const));
3331 if (loaded && !UNDEF_P(loaded->value)) {
3332 RB_VM_LOCKING() {
3333 ce->flag = loaded->flag;
3334 RB_OBJ_WRITE(arguments->module, &ce->value, loaded->value);
3335 RB_OBJ_WRITE(arguments->module, &ce->u.file, loaded->u.file);
3336 ce->line = loaded->line;
3337 rb_clear_constant_cache_for_id(arguments->name);
3338 }
3339 result = Qtrue;
3340 }
3341 }
3342
3343 if (!ce || UNDEF_P(ce->value)) {
3344 result = Qfalse;
3345
3346 rb_const_remove(arguments->module, arguments->name);
3347
3348 if (arguments->module == rb_cObject) {
3349 rb_warning(
3350 "Expected %"PRIsVALUE" to define %"PRIsVALUE" but it didn't",
3351 arguments->autoload_data->feature,
3352 ID2SYM(arguments->name)
3353 );
3354 }
3355 else {
3356 rb_warning(
3357 "Expected %"PRIsVALUE" to define %"PRIsVALUE"::%"PRIsVALUE" but it didn't",
3358 arguments->autoload_data->feature,
3359 arguments->module,
3360 ID2SYM(arguments->name)
3361 );
3362 }
3363 }
3364 else {
3365 // Otherwise, it was loaded, copy the flags from the autoload constant:
3366 ce->flag |= arguments->flag;
3367 }
3368
3369 return result;
3370}
3371
3372VALUE
3374{
3375 rb_const_entry_t *ce = rb_const_lookup(module, name);
3376
3377 // We bail out as early as possible without any synchronisation:
3378 if (!ce || !UNDEF_P(ce->value)) {
3379 return Qfalse;
3380 }
3381
3382 // At this point, we assume there might be autoloading, so fail if it's ractor:
3383 if (UNLIKELY(!rb_ractor_main_p())) {
3384 return rb_ractor_autoload_load(module, name);
3385 }
3386
3387 // This state is stored on the stack and is used during the autoload process.
3388 struct autoload_load_arguments arguments = {.module = module, .name = name, .mutex = Qnil};
3389
3390 // Figure out whether we can autoload the named constant:
3391 VALUE autoload_const_value = rb_mutex_synchronize(autoload_mutex, autoload_load_needed, (VALUE)&arguments);
3392
3393 // This confirms whether autoloading is required or not:
3394 if (autoload_const_value == Qfalse) return autoload_const_value;
3395
3396 arguments.flag = ce->flag & (CONST_DEPRECATED | CONST_VISIBILITY_MASK);
3397
3398 // Only one thread will enter here at a time:
3399 VALUE result = rb_mutex_synchronize(arguments.mutex, autoload_try_load, (VALUE)&arguments);
3400
3401 // If you don't guard this value, it's possible for the autoload constant to
3402 // be freed by another thread which loads multiple constants, one of which
3403 // resolves to the constant this thread is trying to load, so proteect this
3404 // so that it is not freed until we are done with it in `autoload_try_load`:
3405 RB_GC_GUARD(autoload_const_value);
3406
3407 return result;
3408}
3409
3410VALUE
3412{
3413 return rb_autoload_at_p(mod, id, TRUE);
3414}
3415
3416VALUE
3417rb_autoload_at_p(VALUE mod, ID id, int recur)
3418{
3419 VALUE load;
3420 struct autoload_data *ele;
3421
3422 while (!autoload_defined_p(mod, id)) {
3423 if (!recur) return Qnil;
3424 mod = RCLASS_SUPER(mod);
3425 if (!mod) return Qnil;
3426 }
3427 load = check_autoload_required(mod, id, 0);
3428 if (!load) return Qnil;
3429 return (ele = get_autoload_data(load, 0)) ? ele->feature : Qnil;
3430}
3431
3432void
3433rb_const_warn_if_deprecated(const rb_const_entry_t *ce, VALUE klass, ID id)
3434{
3435 if (RB_CONST_DEPRECATED_P(ce) &&
3436 rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) {
3437 if (klass == rb_cObject) {
3438 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "constant ::%"PRIsVALUE" is deprecated", QUOTE_ID(id));
3439 }
3440 else {
3441 rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "constant %"PRIsVALUE"::%"PRIsVALUE" is deprecated",
3442 rb_class_name(klass), QUOTE_ID(id));
3443 }
3444 }
3445}
3446
3447void
3448rb_const_unshareable_error(VALUE klass, ID id)
3449{
3450 rb_raise(rb_eRactorIsolationError, "can not access non-shareable objects in constant %"PRIsVALUE"::%"PRIsVALUE" of a class/module created by another Ractor.", rb_class_path(klass), rb_id2str(id));
3451}
3452
3453static VALUE
3454rb_const_get_0(VALUE klass, ID id, int exclude, int recurse, int visibility)
3455{
3456 VALUE found_in;
3457 VALUE c = rb_const_search(klass, id, exclude, recurse, visibility, &found_in);
3458 if (!UNDEF_P(c)) {
3459 return c; // rb_const_search_from checked a foreign class's value
3460 }
3461 return rb_const_missing(klass, ID2SYM(id));
3462}
3463
3464static VALUE
3465rb_const_search_from(VALUE klass, ID id, int exclude, int recurse, int visibility, VALUE *found_in)
3466{
3467 VALUE value, current;
3468 bool first_iteration = true;
3469
3470 for (current = klass;
3471 RTEST(current);
3472 current = RCLASS_SUPER(current), first_iteration = false) {
3473 VALUE tmp;
3474 VALUE am = 0;
3475 rb_const_entry_t entry, *ce = &entry;
3476
3477 if (!first_iteration && RCLASS_ORIGIN(current) != current) {
3478 // This item in the super chain has an origin iclass
3479 // that comes later in the chain. Skip this item so
3480 // prepended modules take precedence.
3481 continue;
3482 }
3483
3484 // Do lookup in original class or module in case we are at an origin
3485 // iclass in the chain.
3486 tmp = current;
3487 if (BUILTIN_TYPE(tmp) == T_ICLASS) tmp = RBASIC(tmp)->klass;
3488
3489 // Do the lookup. Loop in case of autoload.
3490 while (rb_const_lookup_copy(tmp, id, ce)) {
3491 if (visibility && RB_CONST_PRIVATE_P(ce)) {
3492 GET_EC()->private_const_reference = tmp;
3493 return Qundef;
3494 }
3495 value = ce->value;
3496 // before the warning, which may run Ruby: only this stack holds value until the owner has it
3497 if (!UNDEF_P(value) && UNLIKELY(!rb_class_owned_p(tmp)) && !rb_class_field_shareable_p(tmp, value)) {
3498 rb_const_warn_if_deprecated(ce, tmp, id);
3499 rb_const_unshareable_error(tmp, id);
3500 }
3501 rb_const_warn_if_deprecated(ce, tmp, id);
3502 if (UNDEF_P(value)) {
3503 struct autoload_const *ac;
3504 if (am == tmp) break;
3505 am = tmp;
3506 ac = autoloading_const_entry(tmp, id);
3507 if (ac) {
3508 if (found_in) { *found_in = tmp; }
3509 if (UNLIKELY(!rb_class_owned_p(tmp)) && !rb_class_field_shareable_p(tmp, ac->value)) {
3510 rb_const_unshareable_error(tmp, id);
3511 }
3512 return ac->value;
3513 }
3514 rb_autoload_load(tmp, id);
3515 continue;
3516 }
3517 if (exclude && tmp == rb_cObject) {
3518 goto not_found;
3519 }
3520 if (found_in) { *found_in = tmp; }
3521 return value;
3522 }
3523 if (!recurse) break;
3524 }
3525
3526 not_found:
3527 GET_EC()->private_const_reference = 0;
3528 return Qundef;
3529}
3530
3531static VALUE
3532rb_const_search(VALUE klass, ID id, int exclude, int recurse, int visibility, VALUE *found_in)
3533{
3534 VALUE value;
3535
3536 if (klass == rb_cObject) exclude = FALSE;
3537 value = rb_const_search_from(klass, id, exclude, recurse, visibility, found_in);
3538 if (!UNDEF_P(value)) return value;
3539 if (exclude) return value;
3540 if (BUILTIN_TYPE(klass) != T_MODULE) return value;
3541 /* search global const too, if klass is a module */
3542 return rb_const_search_from(rb_cObject, id, FALSE, recurse, visibility, found_in);
3543}
3544
3545VALUE
3547{
3548 return rb_const_get_0(klass, id, TRUE, TRUE, FALSE);
3549}
3550
3551VALUE
3553{
3554 return rb_const_get_0(klass, id, FALSE, TRUE, FALSE);
3555}
3556
3557VALUE
3559{
3560 return rb_const_get_0(klass, id, TRUE, FALSE, FALSE);
3561}
3562
3563VALUE
3564rb_public_const_get_from(VALUE klass, ID id)
3565{
3566 return rb_const_get_0(klass, id, TRUE, TRUE, TRUE);
3567}
3568
3569VALUE
3570rb_public_const_get_at(VALUE klass, ID id)
3571{
3572 return rb_const_get_0(klass, id, TRUE, FALSE, TRUE);
3573}
3574
3575NORETURN(static void undefined_constant(VALUE mod, VALUE name));
3576static void
3577undefined_constant(VALUE mod, VALUE name)
3578{
3579 rb_name_err_raise("constant %2$s::%1$s not defined",
3580 mod, name);
3581}
3582
3583static VALUE
3584rb_const_location_from(VALUE klass, ID id, int exclude, int recurse, int visibility)
3585{
3586 while (RTEST(klass)) {
3587 rb_const_entry_t entry, *ce = &entry;
3588
3589 while (rb_const_lookup_copy(klass, id, ce)) {
3590 if (visibility && RB_CONST_PRIVATE_P(ce)) {
3591 return Qnil;
3592 }
3593 if (exclude && klass == rb_cObject) {
3594 goto not_found;
3595 }
3596
3597 VALUE file = ce->u.file;
3598 VALUE autoload_const_value = autoload_entry(klass, id);
3599 if (autoload_const_value) {
3601 struct autoload_data *autoload_data = get_autoload_data(autoload_const_value, &autoload_const);
3602
3603 if (!UNDEF_P(autoload_const->value) && RTEST(rb_mutex_owned_p(autoload_data->mutex))) {
3604 return rb_assoc_new(autoload_const->file, INT2NUM(autoload_const->line));
3605 }
3606 file = autoload_const->autoload_call_file;
3607 }
3608
3609 if (NIL_P(file)) return rb_ary_new();
3610 return rb_assoc_new(file, INT2NUM(ce->line));
3611 }
3612 if (!recurse) break;
3613 klass = RCLASS_SUPER(klass);
3614 }
3615
3616 not_found:
3617 return Qnil;
3618}
3619
3620static VALUE
3621rb_const_location(VALUE klass, ID id, int exclude, int recurse, int visibility)
3622{
3623 VALUE loc;
3624
3625 if (klass == rb_cObject) exclude = FALSE;
3626 loc = rb_const_location_from(klass, id, exclude, recurse, visibility);
3627 if (!NIL_P(loc)) return loc;
3628 if (exclude) return loc;
3629 if (BUILTIN_TYPE(klass) != T_MODULE) return loc;
3630 /* search global const too, if klass is a module */
3631 return rb_const_location_from(rb_cObject, id, FALSE, recurse, visibility);
3632}
3633
3634VALUE
3635rb_const_source_location(VALUE klass, ID id)
3636{
3637 return rb_const_location(klass, id, FALSE, TRUE, FALSE);
3638}
3639
3640VALUE
3641rb_const_source_location_at(VALUE klass, ID id)
3642{
3643 return rb_const_location(klass, id, TRUE, FALSE, FALSE);
3644}
3645
3646/*
3647 * call-seq:
3648 * remove_const(sym) -> obj
3649 *
3650 * Removes the definition of the given constant, returning that
3651 * constant's previous value. If that constant referred to
3652 * a module, this will not change that module's name and can lead
3653 * to confusion.
3654 */
3655
3656VALUE
3658{
3659 const ID id = id_for_var(mod, name, a, constant);
3660
3661 if (!id) {
3662 undefined_constant(mod, name);
3663 }
3664 return rb_const_remove(mod, id);
3665}
3666
3667static rb_const_entry_t * const_lookup(struct rb_id_table *tbl, ID id);
3668
3669VALUE
3671{
3672 VALUE val;
3673 rb_const_entry_t *ce;
3674
3675 rb_check_frozen(mod);
3676 rb_class_owner_check(mod);
3677
3678 ce = rb_const_lookup(mod, id);
3679
3680 if (!ce) {
3681 if (rb_const_defined_at(mod, id)) {
3682 rb_name_err_raise("cannot remove %2$s::%1$s", mod, ID2SYM(id));
3683 }
3684
3685 undefined_constant(mod, ID2SYM(id));
3686 }
3687
3688 VALUE writable_ce = 0;
3689 bool found;
3690 RB_VM_LOCKING() { // see rb_const_lookup_copy
3691 found = rb_id_table_lookup(RCLASS_WRITABLE_CONST_TBL(mod), id, &writable_ce);
3692 if (found) rb_id_table_delete(RCLASS_WRITABLE_CONST_TBL(mod), id);
3693 }
3694 if (found && (rb_const_entry_t *)writable_ce != ce) {
3695 SIZED_FREE((rb_const_entry_t *)writable_ce);
3696 }
3697
3698 rb_const_warn_if_deprecated(ce, mod, id);
3700
3701 val = ce->value;
3702
3703 if (UNDEF_P(val)) {
3704 autoload_delete(ce->u.autoload_const);
3705 val = Qnil;
3706 }
3707
3708 if (ce != const_lookup(RCLASS_PRIME_CONST_TBL(mod), id)) {
3709 SIZED_FREE(ce);
3710 }
3711 // else - skip free'ing the ce because it still exists in the prime classext
3712
3713 return val;
3714}
3715
3716static int
3717cv_i_update(st_data_t *k, st_data_t *v, st_data_t a, int existing)
3718{
3719 if (existing) return ST_STOP;
3720 *v = a;
3721 return ST_CONTINUE;
3722}
3723
3724static enum rb_id_table_iterator_result
3725sv_i(ID key, VALUE v, void *a)
3726{
3727 rb_const_entry_t *ce = (rb_const_entry_t *)v;
3728 st_table *tbl = a;
3729
3730 if (rb_is_const_id(key)) {
3731 st_update(tbl, (st_data_t)key, cv_i_update, (st_data_t)ce);
3732 }
3733 return ID_TABLE_CONTINUE;
3734}
3735
3736static enum rb_id_table_iterator_result
3737rb_local_constants_i(ID const_name, VALUE const_value, void *ary)
3738{
3739 if (rb_is_const_id(const_name) && !RB_CONST_PRIVATE_P((rb_const_entry_t *)const_value)) {
3740 rb_ary_push((VALUE)ary, ID2SYM(const_name));
3741 }
3742 return ID_TABLE_CONTINUE;
3743}
3744
3745static VALUE
3746rb_local_constants(VALUE mod)
3747{
3748 struct rb_id_table *tbl = RCLASS_CONST_TBL(mod);
3749 VALUE ary;
3750
3751 if (!tbl) return rb_ary_new2(0);
3752
3753 RB_VM_LOCKING() {
3754 ary = rb_ary_new2(rb_id_table_size(tbl));
3755 rb_id_table_foreach(tbl, rb_local_constants_i, (void *)ary);
3756 }
3757
3758 return ary;
3759}
3760
3761void*
3762rb_mod_const_at(VALUE mod, void *data)
3763{
3764 st_table *tbl = data;
3765 if (!tbl) {
3766 tbl = st_init_numtable();
3767 }
3768 if (RCLASS_CONST_TBL(mod)) {
3769 RB_VM_LOCKING() {
3770 rb_id_table_foreach(RCLASS_CONST_TBL(mod), sv_i, tbl);
3771 }
3772 }
3773 return tbl;
3774}
3775
3776void*
3777rb_mod_const_of(VALUE mod, void *data)
3778{
3779 VALUE tmp = mod;
3780 for (;;) {
3781 data = rb_mod_const_at(tmp, data);
3782 tmp = RCLASS_SUPER(tmp);
3783 if (!tmp) break;
3784 if (tmp == rb_cObject && mod != rb_cObject) break;
3785 }
3786 return data;
3787}
3788
3789static int
3790list_i(st_data_t key, st_data_t value, VALUE ary)
3791{
3792 ID sym = (ID)key;
3793 rb_const_entry_t *ce = (rb_const_entry_t *)value;
3794 if (RB_CONST_PUBLIC_P(ce)) rb_ary_push(ary, ID2SYM(sym));
3795 return ST_CONTINUE;
3796}
3797
3798VALUE
3799rb_const_list(void *data)
3800{
3801 st_table *tbl = data;
3802 VALUE ary;
3803
3804 if (!tbl) return rb_ary_new2(0);
3805 ary = rb_ary_new2(tbl->num_entries);
3806 st_foreach_safe(tbl, list_i, ary);
3807 st_free_table(tbl);
3808
3809 return ary;
3810}
3811
3812/*
3813 * call-seq:
3814 * mod.constants(inherit=true) -> array
3815 *
3816 * Returns an array of the names of the constants accessible in
3817 * <i>mod</i>. This includes the names of constants in any included
3818 * modules (example at start of section), unless the <i>inherit</i>
3819 * parameter is set to <code>false</code>.
3820 *
3821 * The implementation makes no guarantees about the order in which the
3822 * constants are yielded.
3823 *
3824 * IO.constants.include?(:SYNC) #=> true
3825 * IO.constants(false).include?(:SYNC) #=> false
3826 *
3827 * Also see Module#const_defined?.
3828 */
3829
3830VALUE
3831rb_mod_constants(int argc, const VALUE *argv, VALUE mod)
3832{
3833 bool inherit = true;
3834
3835 if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
3836
3837 if (inherit) {
3838 return rb_const_list(rb_mod_const_of(mod, 0));
3839 }
3840 else {
3841 return rb_local_constants(mod);
3842 }
3843}
3844
3845static int
3846rb_const_defined_0(VALUE klass, ID id, int exclude, int recurse, int visibility)
3847{
3848 VALUE tmp;
3849 int mod_retry = 0;
3850 rb_const_entry_t entry, *ce = &entry;
3851
3852 tmp = klass;
3853 retry:
3854 while (tmp) {
3855 if (rb_const_lookup_copy(tmp, id, ce)) {
3856 if (visibility && RB_CONST_PRIVATE_P(ce)) {
3857 return (int)Qfalse;
3858 }
3859 if (UNDEF_P(ce->value) && !check_autoload_required(tmp, id, 0) &&
3860 !rb_autoloading_value(tmp, id, NULL, NULL))
3861 return (int)Qfalse;
3862
3863 if (exclude && tmp == rb_cObject && klass != rb_cObject) {
3864 return (int)Qfalse;
3865 }
3866
3867 return (int)Qtrue;
3868 }
3869 if (!recurse) break;
3870 tmp = RCLASS_SUPER(tmp);
3871 }
3872 if (!exclude && !mod_retry && BUILTIN_TYPE(klass) == T_MODULE) {
3873 mod_retry = 1;
3874 tmp = rb_cObject;
3875 goto retry;
3876 }
3877 return (int)Qfalse;
3878}
3879
3880int
3882{
3883 return rb_const_defined_0(klass, id, TRUE, TRUE, FALSE);
3884}
3885
3886int
3888{
3889 return rb_const_defined_0(klass, id, FALSE, TRUE, FALSE);
3890}
3891
3892int
3894{
3895 return rb_const_defined_0(klass, id, TRUE, FALSE, FALSE);
3896}
3897
3898int
3899rb_public_const_defined_from(VALUE klass, ID id)
3900{
3901 return rb_const_defined_0(klass, id, TRUE, TRUE, TRUE);
3902}
3903
3904static void
3905check_before_mod_set(VALUE klass, ID id, VALUE val, const char *dest)
3906{
3907 rb_check_frozen(klass);
3908}
3909
3910static void set_namespace_path(VALUE named_namespace, VALUE name);
3911
3912static enum rb_id_table_iterator_result
3913set_namespace_path_i(ID id, VALUE v, void *payload)
3914{
3915 rb_const_entry_t *ce = (rb_const_entry_t *)v;
3916 VALUE value = ce->value;
3917 VALUE parental_path = *((VALUE *) payload);
3918 if (!rb_is_const_id(id) || !rb_namespace_p(value)) {
3919 return ID_TABLE_CONTINUE;
3920 }
3921
3922 bool has_permanent_classpath;
3923 classname(value, &has_permanent_classpath);
3924 if (has_permanent_classpath) {
3925 return ID_TABLE_CONTINUE;
3926 }
3927 set_namespace_path(value, build_const_path(parental_path, id));
3928
3929 if (!RCLASS_PERMANENT_CLASSPATH_P(value)) {
3930 RCLASS_WRITE_CLASSPATH(value, 0, false);
3931 }
3932
3933 return ID_TABLE_CONTINUE;
3934}
3935
3936/*
3937 * Assign permanent classpaths to all namespaces that are directly or indirectly
3938 * nested under +named_namespace+. +named_namespace+ must have a permanent
3939 * classpath.
3940 */
3941static void
3942set_namespace_path(VALUE named_namespace, VALUE namespace_path)
3943{
3944 struct rb_id_table *const_table = RCLASS_CONST_TBL(named_namespace);
3945 RB_OBJ_SET_SHAREABLE(namespace_path);
3946
3947 RB_VM_LOCKING() {
3948 RCLASS_WRITE_CLASSPATH(named_namespace, namespace_path, true);
3949
3950 if (const_table) {
3951 rb_id_table_foreach(const_table, set_namespace_path_i, &namespace_path);
3952 }
3953 }
3954}
3955
3956static void
3957const_added(VALUE klass, ID const_name)
3958{
3959 if (GET_VM()->running) {
3960 VALUE arg = ID2SYM(const_name);
3961 rb_funcallv_uncached(klass, idConst_added, 1, &arg);
3962 }
3963}
3964
3965static void
3966const_set(VALUE klass, ID id, VALUE val)
3967{
3968 rb_const_entry_t *ce;
3969
3970 if (NIL_P(klass)) {
3971 rb_raise(rb_eTypeError, "no class/module to define constant %"PRIsVALUE"",
3972 QUOTE_ID(id));
3973 }
3974
3975 if (UNLIKELY(!rb_class_owned_p(klass))) {
3976 rb_raise(rb_eRactorIsolationError, "can not set constants of classes/modules created by another Ractor");
3977 }
3978
3979 check_before_mod_set(klass, id, val, "constant");
3980
3981 struct const_warning warning = {0};
3982 RB_VM_LOCKING() {
3983 struct rb_id_table *tbl = RCLASS_WRITABLE_CONST_TBL(klass);
3984 if (!tbl) {
3985 tbl = rb_id_table_create(0);
3986 RCLASS_WRITE_CONST_TBL(klass, tbl, false);
3988 ce = ZALLOC(rb_const_entry_t);
3989 rb_id_table_insert(tbl, id, (VALUE)ce);
3990 setup_const_entry(ce, klass, val, CONST_PUBLIC);
3991 }
3992 else {
3993 struct autoload_const ac = {
3994 .module = klass, .name = id,
3995 .value = val, .flag = CONST_PUBLIC,
3996 /* fill the rest with 0 */
3997 };
3998 ac.file = rb_source_location(&ac.line);
3999 const_tbl_update(&ac, false, &warning);
4000 }
4001 }
4002 const_warning_emit(&warning);
4003
4004 /*
4005 * Resolve and cache class name immediately to resolve ambiguity
4006 * and avoid order-dependency on const_tbl
4007 */
4008 if (rb_cObject && rb_namespace_p(val)) {
4009 bool val_path_permanent;
4010 VALUE val_path = classname(val, &val_path_permanent);
4011 if (NIL_P(val_path) || !val_path_permanent) {
4012 if (klass == rb_cObject) {
4013 set_namespace_path(val, rb_id2str(id));
4014 }
4015 else {
4016 bool parental_path_permanent;
4017 VALUE parental_path = classname(klass, &parental_path_permanent);
4018 if (NIL_P(parental_path)) {
4019 bool throwaway;
4020 parental_path = rb_tmp_class_path(klass, &throwaway, make_temporary_path);
4021 }
4022 if (parental_path_permanent && !val_path_permanent) {
4023 set_namespace_path(val, build_const_path(parental_path, id));
4024 }
4025 else if (!parental_path_permanent && NIL_P(val_path)) {
4026 VALUE path = build_const_path(parental_path, id);
4027 RCLASS_SET_CLASSPATH(val, path, false);
4028 }
4029 }
4030 }
4031 }
4032}
4033
4034void
4036{
4037 const_set(klass, id, val);
4038 const_added(klass, id);
4039}
4040
4041static VALUE
4042autoload_const_value_for_named_constant(VALUE module, ID name, struct autoload_const **autoload_const_pointer)
4043{
4044 VALUE autoload_const_value = autoload_entry(module, name);
4045 if (!autoload_const_value) return Qfalse;
4046
4047 struct autoload_data *autoload_data = get_autoload_data(autoload_const_value, autoload_const_pointer);
4048 if (!autoload_data) return Qfalse;
4049
4050 /* for autoloading thread, keep the defined value to autoloading storage */
4051 if (autoload_by_current(autoload_data)) {
4052 return autoload_const_value;
4053 }
4054
4055 return Qfalse;
4056}
4057
4058/* Records into *warning rather than warning itself; see struct const_warning. */
4059static void
4060const_tbl_update(struct autoload_const *ac, int autoload_force, struct const_warning *warning)
4061{
4062 ASSERT_vm_locking();
4063 VALUE value;
4064 VALUE klass = ac->module;
4065 VALUE val = ac->value;
4066 ID id = ac->name;
4067 struct rb_id_table *tbl = RCLASS_CONST_TBL(klass);
4068 rb_const_flag_t visibility = ac->flag;
4069 rb_const_entry_t *ce;
4070
4071 if (rb_id_table_lookup(tbl, id, &value)) {
4072 ce = (rb_const_entry_t *)value;
4073 if (UNDEF_P(ce->value)) {
4074 RUBY_ASSERT_CRITICAL_SECTION_ENTER();
4075 VALUE file = ac->file;
4076 int line = ac->line;
4077 VALUE autoload_const_value = autoload_const_value_for_named_constant(klass, id, &ac);
4078
4079 if (!autoload_force && autoload_const_value) {
4081
4082 RB_OBJ_WRITE(autoload_const_value, &ac->value, val);
4083 RB_OBJ_WRITE(autoload_const_value, &ac->file, rb_source_location(&ac->line));
4084 }
4085 else {
4086 /* otherwise autoloaded constant, allow to override */
4087 autoload_delete(ce->u.autoload_const);
4088 ce->flag = visibility;
4089 RB_OBJ_WRITE(klass, &ce->value, val);
4090 RB_OBJ_WRITE(klass, &ce->u.file, file);
4091 ce->line = line;
4092 }
4093 RUBY_ASSERT_CRITICAL_SECTION_LEAVE();
4094 return;
4095 }
4096 else {
4097 visibility = ce->flag;
4098
4099 warning->id = id;
4100 warning->module = klass;
4101 warning->file = ce->u.file;
4102 warning->line = ce->line;
4103 }
4105 setup_const_entry(ce, klass, val, visibility);
4106 }
4107 else {
4108 tbl = RCLASS_WRITABLE_CONST_TBL(klass);
4110
4111 ce = ZALLOC(rb_const_entry_t);
4112 rb_id_table_insert(tbl, id, (VALUE)ce);
4113 setup_const_entry(ce, klass, val, visibility);
4114 }
4115}
4116
4117static void
4118setup_const_entry(rb_const_entry_t *ce, VALUE klass, VALUE val,
4119 rb_const_flag_t visibility)
4120{
4121 ce->flag = visibility;
4122 RB_OBJ_WRITE(klass, &ce->value, val);
4123 RB_OBJ_WRITE(klass, &ce->u.file, rb_source_location(&ce->line));
4124}
4125
4126void
4127rb_define_const(VALUE klass, const char *name, VALUE val)
4128{
4129 ID id = rb_intern(name);
4130
4131 if (!rb_is_const_id(id)) {
4132 rb_warn("rb_define_const: invalid name '%s' for constant", name);
4133 }
4134 if (!RB_SPECIAL_CONST_P(val)) {
4135 rb_vm_register_global_object(val);
4136 }
4137 rb_const_set(klass, id, val);
4138}
4139
4140void
4141rb_define_global_const(const char *name, VALUE val)
4142{
4143 rb_define_const(rb_cObject, name, val);
4144}
4145
4146static void
4147set_const_visibility(VALUE mod, int argc, const VALUE *argv,
4148 rb_const_flag_t flag, rb_const_flag_t mask)
4149{
4150 int i;
4151 rb_const_entry_t *ce;
4152 ID id;
4153
4155 if (argc == 0) {
4156 rb_warning("%"PRIsVALUE" with no argument is just ignored",
4157 QUOTE_ID(rb_frame_callee()));
4158 return;
4159 }
4160
4161 for (i = 0; i < argc; i++) {
4162 struct autoload_const *ac;
4163 VALUE val = argv[i];
4164 id = rb_check_id(&val);
4165 if (!id) {
4166 undefined_constant(mod, val);
4167 }
4168 if ((ce = rb_const_lookup(mod, id))) {
4169 ce->flag &= ~mask;
4170 ce->flag |= flag;
4171 if (UNDEF_P(ce->value)) {
4172 if (autoload_const_value_for_named_constant(mod, id, &ac)) {
4173 ac->flag &= ~mask;
4174 ac->flag |= flag;
4175 }
4176 }
4178 }
4179 else {
4180 undefined_constant(mod, ID2SYM(id));
4181 }
4182 }
4183}
4184
4185void
4186rb_deprecate_constant(VALUE mod, const char *name)
4187{
4188 rb_const_entry_t *ce;
4189 ID id;
4190 long len = strlen(name);
4191
4193 if (!(id = rb_check_id_cstr(name, len, NULL))) {
4194 undefined_constant(mod, rb_fstring_new(name, len));
4195 }
4196 if (!(ce = rb_const_lookup(mod, id))) {
4197 undefined_constant(mod, ID2SYM(id));
4198 }
4199 ce->flag |= CONST_DEPRECATED;
4200}
4201
4202/*
4203 * call-seq:
4204 * mod.private_constant(symbol, ...) => mod
4205 *
4206 * Makes a list of existing constants private.
4207 */
4208
4209VALUE
4210rb_mod_private_constant(int argc, const VALUE *argv, VALUE obj)
4211{
4212 set_const_visibility(obj, argc, argv, CONST_PRIVATE, CONST_VISIBILITY_MASK);
4213 return obj;
4214}
4215
4216/*
4217 * call-seq:
4218 * mod.public_constant(symbol, ...) => mod
4219 *
4220 * Makes a list of existing constants public.
4221 */
4222
4223VALUE
4224rb_mod_public_constant(int argc, const VALUE *argv, VALUE obj)
4225{
4226 set_const_visibility(obj, argc, argv, CONST_PUBLIC, CONST_VISIBILITY_MASK);
4227 return obj;
4228}
4229
4230/*
4231 * call-seq:
4232 * mod.deprecate_constant(symbol, ...) => mod
4233 *
4234 * Makes a list of existing constants deprecated. Attempt
4235 * to refer to them will produce a warning.
4236 *
4237 * module HTTP
4238 * NotFound = Exception.new
4239 * NOT_FOUND = NotFound # previous version of the library used this name
4240 *
4241 * deprecate_constant :NOT_FOUND
4242 * end
4243 *
4244 * HTTP::NOT_FOUND
4245 * # warning: constant HTTP::NOT_FOUND is deprecated
4246 *
4247 */
4248
4249VALUE
4250rb_mod_deprecate_constant(int argc, const VALUE *argv, VALUE obj)
4251{
4252 set_const_visibility(obj, argc, argv, CONST_DEPRECATED, CONST_DEPRECATED);
4253 return obj;
4254}
4255
4256static VALUE
4257original_module(VALUE c)
4258{
4259 if (RB_TYPE_P(c, T_ICLASS))
4260 return RBASIC(c)->klass;
4261 return c;
4262}
4263
4264static int
4265cvar_lookup_at(VALUE klass, ID id, st_data_t *v)
4266{
4267 if (RB_TYPE_P(klass, T_ICLASS)) {
4268 if (RICLASS_IS_ORIGIN_P(klass)) {
4269 return 0;
4270 }
4271 else {
4272 // check the original module
4273 klass = RBASIC(klass)->klass;
4274 }
4275 }
4276
4277 VALUE n = rb_ivar_lookup(klass, id, Qundef);
4278 if (UNDEF_P(n)) return 0;
4279
4280 if (v) *v = n;
4281 return 1;
4282}
4283
4284static VALUE
4285cvar_front_klass(VALUE klass)
4286{
4287 if (RCLASS_SINGLETON_P(klass)) {
4288 VALUE obj = RCLASS_ATTACHED_OBJECT(klass);
4289 if (rb_namespace_p(obj)) {
4290 return obj;
4291 }
4292 }
4293 return RCLASS_SUPER(klass);
4294}
4295
4296static void
4297cvar_overtaken_check(VALUE front, VALUE target, ID id)
4298{
4299 if (front && target != front && original_module(front) != original_module(target)) {
4300 rb_raise(rb_eRuntimeError,
4301 "class variable % "PRIsVALUE" of %"PRIsVALUE" is overtaken by %"PRIsVALUE"",
4302 ID2SYM(id), rb_class_name(original_module(front)),
4303 rb_class_name(original_module(target)));
4304 }
4305}
4306
4307// the clean-up after cvar_overtaken_check
4308static void
4309cvar_overtaken(VALUE front, VALUE target, ID id)
4310{
4311 if (front && target != front) {
4312 if (BUILTIN_TYPE(front) == T_CLASS && rb_class_owned_p(front)) {
4313 // only clean-up, and reachable from reads: never write a foreign class
4314 rb_ivar_delete(front, id, Qundef);
4315 }
4316 }
4317}
4318
4319#define CVAR_FOREACH_ANCESTORS(klass, v, r) \
4320 for (klass = cvar_front_klass(klass); klass; klass = RCLASS_SUPER(klass)) { \
4321 if (cvar_lookup_at(klass, id, (v))) { \
4322 r; \
4323 } \
4324 }
4325
4326#define CVAR_LOOKUP(v,r) do {\
4327 if (cvar_lookup_at(klass, id, (v))) {r;}\
4328 CVAR_FOREACH_ANCESTORS(klass, v, r);\
4329} while(0)
4330
4331static VALUE
4332find_cvar(VALUE klass, VALUE * front, VALUE * target, ID id)
4333{
4334 VALUE v = Qundef;
4335 CVAR_LOOKUP(&v, {
4336 if (!*front) {
4337 *front = klass;
4338 }
4339 *target = klass;
4340 });
4341
4342 return v;
4343}
4344
4345void
4346rb_cvar_set(VALUE klass, ID id, VALUE val)
4347{
4348 VALUE tmp, front = 0, target = 0;
4349
4350 tmp = klass;
4351 CVAR_LOOKUP(0, {if (!front) front = klass; target = klass;});
4352 if (target) {
4353 cvar_overtaken_check(front, target, id);
4354 cvar_overtaken(front, target, id);
4355 }
4356 else {
4357 target = tmp;
4358 }
4359
4360 if (RB_TYPE_P(target, T_ICLASS)) {
4361 target = RBASIC(target)->klass;
4362 }
4363 cvar_set_ractor_check(target, id);
4364 check_before_mod_set(target, id, val, "class variable");
4365
4366 bool new_cvar = rb_class_ivar_set(target, id, val);
4367
4368 VALUE cvc_tbl = RCLASS_WRITABLE_CVC_TBL(target);
4369
4370 struct rb_cvar_class_tbl_entry *ent;
4371 VALUE ent_data;
4372
4373 if (!cvc_tbl || !rb_marked_id_table_lookup(cvc_tbl, id, &ent_data)) {
4374 ent = (struct rb_cvar_class_tbl_entry *)SHAREABLE_IMEMO_NEW(struct rb_cvar_class_tbl_entry, imemo_cvar_entry, 0);
4375 RB_OBJ_WRITE((VALUE)ent, &ent->class_value, target);
4376 RB_OBJ_WRITE((VALUE)ent, &ent->cref, 0);
4377 ent->global_cvar_state = GET_GLOBAL_CVAR_STATE();
4378
4379 VALUE new_cvc_tbl = cvc_tbl;
4380 if (!new_cvc_tbl) {
4381 new_cvc_tbl = rb_marked_id_table_new(2);
4382 }
4383 else if (rb_multi_ractor_p()) {
4384 new_cvc_tbl = rb_marked_id_table_dup(cvc_tbl);
4385 }
4386
4387 rb_marked_id_table_insert(new_cvc_tbl, id, (VALUE)ent);
4388 if (new_cvc_tbl != cvc_tbl) {
4389 RCLASS_WRITE_CVC_TBL(target, new_cvc_tbl);
4390 }
4391 RB_DEBUG_COUNTER_INC(cvar_inline_miss);
4392 }
4393 else {
4394 ent = (void *)ent_data;
4395 ent->global_cvar_state = GET_GLOBAL_CVAR_STATE();
4396 }
4397
4398 // Break the cvar cache if this is a new class variable.
4399 // Existing caches may have resolved this name to a different
4400 // location in the hierarchy, so we must invalidate globally.
4401 if (new_cvar) {
4402 ruby_vm_global_cvar_state++;
4403 }
4404}
4405
4406VALUE
4407rb_cvar_find(VALUE klass, ID id, VALUE *front)
4408{
4409 VALUE target = 0;
4410 VALUE value;
4411
4412 value = find_cvar(klass, front, &target, id);
4413 if (!target) {
4414 rb_name_err_raise("uninitialized class variable %1$s in %2$s",
4415 klass, ID2SYM(id));
4416 }
4417 cvar_overtaken_check(*front, target, id);
4418 // before the clean-up in cvar_overtaken, which may GC: only this stack holds value until the owner has it
4419 cvar_read_ractor_check(RB_TYPE_P(target, T_ICLASS) ? RBASIC(target)->klass : target, id, value);
4420 cvar_overtaken(*front, target, id);
4421 return value;
4422}
4423
4424VALUE
4426{
4427 VALUE front = 0;
4428 return rb_cvar_find(klass, id, &front);
4429}
4430
4431VALUE
4433{
4434 if (!klass) return Qfalse;
4435 CVAR_LOOKUP(0,return Qtrue);
4436 return Qfalse;
4437}
4438
4439static ID
4440cv_intern(VALUE klass, const char *name)
4441{
4442 ID id = rb_intern(name);
4443 if (!rb_is_class_id(id)) {
4444 rb_name_err_raise("wrong class variable name %1$s",
4445 klass, rb_str_new_cstr(name));
4446 }
4447 return id;
4448}
4449
4450void
4451rb_cv_set(VALUE klass, const char *name, VALUE val)
4452{
4453 ID id = cv_intern(klass, name);
4454 rb_cvar_set(klass, id, val);
4455}
4456
4457VALUE
4458rb_cv_get(VALUE klass, const char *name)
4459{
4460 ID id = cv_intern(klass, name);
4461 return rb_cvar_get(klass, id);
4462}
4463
4464void
4465rb_define_class_variable(VALUE klass, const char *name, VALUE val)
4466{
4467 rb_cv_set(klass, name, val);
4468}
4469
4470static int
4471cv_i(ID key, VALUE v, st_data_t a)
4472{
4473 st_table *tbl = (st_table *)a;
4474
4475 if (rb_is_class_id(key)) {
4476 st_update(tbl, (st_data_t)key, cv_i_update, 0);
4477 }
4478 return ST_CONTINUE;
4479}
4480
4481static void*
4482mod_cvar_at(VALUE mod, void *data)
4483{
4484 st_table *tbl = data;
4485 if (!tbl) {
4486 tbl = st_init_numtable();
4487 }
4488 mod = original_module(mod);
4489
4490 rb_ivar_foreach(mod, cv_i, (st_data_t)tbl);
4491 return tbl;
4492}
4493
4494static void*
4495mod_cvar_of(VALUE mod, void *data)
4496{
4497 VALUE tmp = mod;
4498 if (RCLASS_SINGLETON_P(mod)) {
4499 if (rb_namespace_p(RCLASS_ATTACHED_OBJECT(mod))) {
4500 data = mod_cvar_at(tmp, data);
4501 tmp = cvar_front_klass(tmp);
4502 }
4503 }
4504 for (;;) {
4505 data = mod_cvar_at(tmp, data);
4506 tmp = RCLASS_SUPER(tmp);
4507 if (!tmp) break;
4508 }
4509 return data;
4510}
4511
4512static int
4513cv_list_i(st_data_t key, st_data_t value, VALUE ary)
4514{
4515 ID sym = (ID)key;
4516 rb_ary_push(ary, ID2SYM(sym));
4517 return ST_CONTINUE;
4518}
4519
4520static VALUE
4521cvar_list(void *data)
4522{
4523 st_table *tbl = data;
4524 VALUE ary;
4525
4526 if (!tbl) return rb_ary_new2(0);
4527 ary = rb_ary_new2(tbl->num_entries);
4528 st_foreach_safe(tbl, cv_list_i, ary);
4529 st_free_table(tbl);
4530
4531 return ary;
4532}
4533
4534/*
4535 * call-seq:
4536 * mod.class_variables(inherit=true) -> array
4537 *
4538 * Returns an array of the names of class variables in <i>mod</i>.
4539 * This includes the names of class variables in any included
4540 * modules, unless the <i>inherit</i> parameter is set to
4541 * <code>false</code>.
4542 *
4543 * class One
4544 * @@var1 = 1
4545 * end
4546 * class Two < One
4547 * @@var2 = 2
4548 * end
4549 * One.class_variables #=> [:@@var1]
4550 * Two.class_variables #=> [:@@var2, :@@var1]
4551 * Two.class_variables(false) #=> [:@@var2]
4552 */
4553
4554VALUE
4555rb_mod_class_variables(int argc, const VALUE *argv, VALUE mod)
4556{
4557 bool inherit = true;
4558 st_table *tbl;
4559
4560 if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
4561 if (inherit) {
4562 tbl = mod_cvar_of(mod, 0);
4563 }
4564 else {
4565 tbl = mod_cvar_at(mod, 0);
4566 }
4567 return cvar_list(tbl);
4568}
4569
4570/*
4571 * call-seq:
4572 * remove_class_variable(sym) -> obj
4573 *
4574 * Removes the named class variable from the receiver, returning that
4575 * variable's value.
4576 *
4577 * class Example
4578 * @@var = 99
4579 * puts remove_class_variable(:@@var)
4580 * p(defined? @@var)
4581 * end
4582 *
4583 * <em>produces:</em>
4584 *
4585 * 99
4586 * nil
4587 */
4588
4589VALUE
4591{
4592 const ID id = id_for_var_message(mod, name, class, "wrong class variable name %1$s");
4593 st_data_t val;
4594
4595 if (!id) {
4596 goto not_defined;
4597 }
4598 rb_check_frozen(mod);
4599 cvar_set_ractor_check(mod, id);
4600 val = rb_ivar_delete(mod, id, Qundef);
4601 if (!UNDEF_P(val)) {
4602 ruby_vm_global_cvar_state++;
4603 return (VALUE)val;
4604 }
4605 if (rb_cvar_defined(mod, id)) {
4606 rb_name_err_raise("cannot remove %1$s for %2$s", mod, ID2SYM(id));
4607 }
4608 not_defined:
4609 rb_name_err_raise("class variable %1$s not defined for %2$s",
4610 mod, name);
4612}
4613
4614VALUE
4615rb_iv_get(VALUE obj, const char *name)
4616{
4617 ID id = rb_check_id_cstr(name, strlen(name), rb_usascii_encoding());
4618
4619 if (!id) {
4620 return Qnil;
4621 }
4622 return rb_ivar_get(obj, id);
4623}
4624
4625VALUE
4626rb_iv_set(VALUE obj, const char *name, VALUE val)
4627{
4628 ID id = rb_intern(name);
4629
4630 return rb_ivar_set(obj, id, val);
4631}
4632
4633static attr_index_t
4634class_fields_ivar_set(VALUE klass, VALUE fields_obj, ID id, VALUE val, bool concurrent, VALUE *new_fields_obj, bool *new_ivar_out)
4635{
4636 const VALUE original_fields_obj = fields_obj;
4637 fields_obj = original_fields_obj ? original_fields_obj : rb_imemo_fields_new(klass, ROOT_SHAPE_ID, true);
4638
4639 shape_id_t current_shape_id = RBASIC_SHAPE_ID(fields_obj);
4640 shape_id_t next_shape_id = current_shape_id; // for complex
4641 if (UNLIKELY(rb_shape_complex_p(current_shape_id))) {
4642 goto complex;
4643 }
4644
4645 bool new_ivar;
4646 next_shape_id = generic_shape_ivar(fields_obj, id, &new_ivar);
4647
4648 if (UNLIKELY(rb_shape_complex_p(next_shape_id))) {
4649 fields_obj = imemo_fields_evacutate_to_complex(klass, fields_obj, next_shape_id, 1);
4650 goto complex;
4651 }
4652
4653 attr_index_t index = RSHAPE_INDEX(next_shape_id);
4654 if (new_ivar && index >= RSHAPE_CAPACITY(current_shape_id)) {
4655 // We allocate a new fields_obj even when concurrency isn't a concern
4656 // so that we're embedded as long as possible.
4657 fields_obj = imemo_fields_copy_append(klass, fields_obj, current_shape_id, next_shape_id, val);
4658 }
4659 else {
4660 VALUE *fields = rb_imemo_fields_ptr(fields_obj);
4661
4662 if (concurrent && original_fields_obj == fields_obj) {
4663 // In the concurrent case, if we're mutating the existing
4664 // fields_obj, we must use an atomic write, because if we're
4665 // adding a new field, the shape_id must be written after the field
4666 // and if we're updating an existing field, we at least need a relaxed
4667 // write to avoid reaping.
4668 RB_OBJ_ATOMIC_WRITE(fields_obj, &fields[index], val);
4669 }
4670 else {
4671 RB_OBJ_WRITE(fields_obj, &fields[index], val);
4672 }
4673
4674 if (new_ivar) {
4675 RUBY_ASSERT(rb_shape_layout(next_shape_id) == SHAPE_ID_LAYOUT_ROBJECT);
4676 RBASIC_SET_SHAPE_ID(fields_obj, next_shape_id);
4677 }
4678 }
4679
4680 *new_fields_obj = fields_obj;
4681 *new_ivar_out = new_ivar;
4682 return index;
4683
4684complex:
4685 {
4686 if (concurrent && fields_obj == original_fields_obj) {
4687 // In multi-ractor case, we must always work on a copy because
4688 // even if the field already exist, inserting in a st_table may
4689 // cause a rebuild.
4690 fields_obj = rb_imemo_fields_clone(fields_obj);
4691 }
4692
4693 st_table *table = rb_imemo_fields_complex_tbl(fields_obj);
4694 new_ivar = !st_insert(table, (st_data_t)id, (st_data_t)val);
4695 RB_OBJ_WRITTEN(fields_obj, Qundef, val);
4696
4697 if (fields_obj != original_fields_obj) {
4698 RUBY_ASSERT(rb_shape_layout(next_shape_id) == SHAPE_ID_LAYOUT_ROBJECT);
4699 RBASIC_SET_SHAPE_ID(fields_obj, next_shape_id);
4700 }
4701 }
4702
4703 *new_fields_obj = fields_obj;
4704 *new_ivar_out = new_ivar;
4705 return ATTR_INDEX_NOT_SET;
4706}
4707
4708static attr_index_t
4709class_ivar_set(VALUE obj, ID id, VALUE val, bool *new_ivar)
4710{
4711 rb_class_ensure_writable(obj);
4712
4713 const VALUE original_fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
4714 VALUE new_fields_obj = 0;
4715
4716 attr_index_t index = class_fields_ivar_set(obj, original_fields_obj, id, val, rb_multi_ractor_p(), &new_fields_obj, new_ivar);
4717
4718 if (new_fields_obj != original_fields_obj) {
4719 RCLASS_WRITABLE_SET_FIELDS_OBJ(obj, new_fields_obj);
4720 }
4721
4722 // TODO: What should we set as the T_CLASS shape_id?
4723 // In most case we can replicate the single `fields_obj` shape
4724 // but in namespaced case? Perhaps INVALID_SHAPE_ID?
4725 RBASIC_SET_SHAPE_ID_ATOMIC(obj, RBASIC_SHAPE_ID(new_fields_obj));
4726 return index;
4727}
4728
4729bool
4730rb_class_ivar_set(VALUE obj, ID id, VALUE val)
4731{
4733 rb_check_frozen(obj);
4734
4735 bool new_ivar;
4736 class_ivar_set(obj, id, val, &new_ivar);
4737 return new_ivar;
4738}
4739
4740void
4741rb_fields_tbl_copy(VALUE dst, VALUE src)
4742{
4743 RUBY_ASSERT(rb_type(dst) == rb_type(src));
4745 RUBY_ASSERT(RSHAPE_TYPE_P(RBASIC_SHAPE_ID(dst), SHAPE_ROOT));
4746
4747 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(src);
4748 if (fields_obj) {
4749 VALUE dst_fields_obj = rb_imemo_fields_clone(fields_obj);
4750 // `dst` is a freshly allocated object, so it must not inherit `src`'s
4751 // frozen status. Callers that need it re-freeze `dst` themselves.
4752 shape_id_t shape_id = RBASIC_SHAPE_ID(dst_fields_obj) & ~SHAPE_ID_FL_FROZEN;
4753 RBASIC_SET_SHAPE_ID(dst_fields_obj, shape_id);
4754 RCLASS_WRITABLE_SET_FIELDS_OBJ(dst, dst_fields_obj);
4755 RBASIC_SET_SHAPE_ID(dst, shape_id);
4756 }
4757}
4758
4759static rb_const_entry_t *
4760const_lookup(struct rb_id_table *tbl, ID id)
4761{
4762 if (tbl) {
4763 VALUE val;
4764 bool r;
4765 RB_VM_LOCKING() {
4766 r = rb_id_table_lookup(tbl, id, &val);
4767 }
4768
4769 if (r) return (rb_const_entry_t *)val;
4770 }
4771 return NULL;
4772}
4773
4774rb_const_entry_t *
4775rb_const_lookup(VALUE klass, ID id)
4776{
4777 return const_lookup(RCLASS_CONST_TBL(klass), id);
4778}
4779
4780// For readers that may not own klass: rb_const_remove frees the entry once it is out of
4781// the table, so copy it while the VM lock keeps it in.
4782bool
4783rb_const_lookup_copy(VALUE klass, ID id, rb_const_entry_t *ce)
4784{
4785 bool found = false;
4786 RB_VM_LOCKING() {
4787 struct rb_id_table *tbl = RCLASS_CONST_TBL(klass);
4788 VALUE entry;
4789 if (tbl && rb_id_table_lookup(tbl, id, &entry)) {
4790 *ce = *(rb_const_entry_t *)entry;
4791 found = true;
4792 }
4793 }
4794 return found;
4795}
#define RUBY_EXTERN
Declaration of externally visible global variables.
Definition dllexport.h:45
static VALUE RB_OBJ_FROZEN_RAW(VALUE obj)
This is an implementation detail of RB_OBJ_FROZEN().
Definition fl_type.h:699
static bool RB_FL_ABLE(VALUE obj)
Checks if the object is flaggable.
Definition fl_type.h:384
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
Definition fl_type.h:544
void rb_obj_freeze_inline(VALUE obj)
Prevents further modifications to the given object.
Definition variable.c:2124
static void RB_FL_UNSET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_UNSET().
Definition fl_type.h:604
@ RUBY_FL_FREEZE
This flag has something to do with data immutability.
Definition fl_type.h:278
void rb_class_modify_check(VALUE klass)
Asserts that klass is not a frozen class.
Definition eval.c:445
void rb_freeze_singleton_class(VALUE attached_object)
This is an implementation detail of RB_OBJ_FREEZE().
Definition class.c:3024
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:3394
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1700
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:403
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition value_type.h:67
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define T_DATA
Old name of RUBY_T_DATA.
Definition value_type.h:60
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:405
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#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 rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define FL_USER2
Old name of RUBY_FL_USER2.
Definition fl_type.h:71
#define Qtrue
Old name of RUBY_Qtrue.
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#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 rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
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
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition error.c:2425
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
void rb_name_error_str(VALUE str, const char *fmt,...)
Identical to rb_name_error(), except it takes a VALUE instead of ID.
Definition error.c:2440
VALUE rb_eNameError
NameError exception.
Definition error.c:1462
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Identical to rb_typeddata_is_kind_of(), except it raises exceptions instead of returning false.
Definition error.c:1443
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:495
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_cModule
Module class.
Definition object.c:61
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition object.c:221
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#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.
rb_encoding * rb_usascii_encoding(void)
Queries the encoding that represents US-ASCII.
Definition encoding.c:1650
ID rb_check_id_cstr(const char *ptr, rb_len_t len, rb_encoding *enc)
Identical to rb_check_id(), except it takes a pointer to a memory region instead of Ruby's string.
Definition symbol.c:1394
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1149
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition vm_eval.c:1107
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_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
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
ID rb_frame_callee(void)
Identical to rb_frame_this_func(), except it returns the named used to call the method.
Definition eval.c:1236
#define st_foreach_safe
Just another name of rb_st_foreach_safe.
Definition hash.h:51
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
VALUE rb_backref_get(void)
Queries the last match, or Regexp.last_match, or the $~.
Definition vm.c:2171
int rb_is_instance_id(ID id)
Classifies the given ID, then sees if it is an instance variable.
Definition symbol.c:1266
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1248
int rb_is_class_id(ID id)
Classifies the given ID, then sees if it is a class variable.
Definition symbol.c:1254
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1586
VALUE rb_reg_nth_defined(int n, VALUE md)
Identical to rb_reg_nth_match(), except it just returns Boolean.
Definition re.c:2696
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:3300
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:3995
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1572
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2057
#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_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:1097
VALUE rb_mutex_new(void)
Creates a mutex.
VALUE rb_mutex_locked_p(VALUE mutex)
Queries if there are any threads that holds the lock.
VALUE rb_mutex_synchronize(VALUE mutex, VALUE(*func)(VALUE arg), VALUE arg)
Obtains the lock, runs the passed function, and releases the lock when it completes.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
Definition thread.c:5971
VALUE rb_mod_remove_cvar(VALUE mod, VALUE name)
Resembles Module#remove_class_variable.
Definition variable.c:4590
VALUE rb_obj_instance_variables(VALUE obj)
Resembles Object#instance_variables.
Definition variable.c:2574
VALUE rb_f_untrace_var(int argc, const VALUE *argv)
Deletes the passed tracer from the passed global variable, or if omitted, deletes everything.
Definition variable.c:958
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition variable.c:3552
VALUE rb_const_list(void *)
This is another mysterious API that comes with no documents at all.
Definition variable.c:3799
VALUE rb_path2class(const char *path)
Resolves a Q::W::E::R-style path string to the actual class it points.
Definition variable.c:511
VALUE rb_autoload_p(VALUE space, ID name)
Queries if an autoload is defined at a point.
Definition variable.c:3411
void rb_set_class_path(VALUE klass, VALUE space, const char *name)
Names a class.
Definition variable.c:458
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:2185
VALUE rb_mod_remove_const(VALUE space, VALUE name)
Resembles Module#remove_const.
Definition variable.c:3657
VALUE rb_class_path_cached(VALUE mod)
Just another name of rb_mod_name.
Definition variable.c:406
VALUE rb_f_trace_var(int argc, const VALUE *argv)
Traces a global variable.
Definition variable.c:912
void rb_cvar_set(VALUE klass, ID name, VALUE val)
Assigns a value to a class variable.
Definition variable.c:4346
VALUE rb_cvar_get(VALUE klass, ID name)
Obtains a value from a class variable.
Definition variable.c:4425
VALUE rb_mod_constants(int argc, const VALUE *argv, VALUE recv)
Resembles Module#constants.
Definition variable.c:3831
VALUE rb_cvar_find(VALUE klass, ID name, VALUE *front)
Identical to rb_cvar_get(), except it takes additional "front" pointer.
Definition variable.c:4407
VALUE rb_path_to_class(VALUE path)
Identical to rb_path2class(), except it accepts the path as Ruby's string instead of C's.
Definition variable.c:466
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1665
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:4035
VALUE rb_autoload_load(VALUE space, ID name)
Kicks the autoload procedure as if it was "touched".
Definition variable.c:3373
VALUE rb_mod_name(VALUE mod)
Queries the name of a module.
Definition variable.c:151
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:517
VALUE rb_const_get_at(VALUE space, ID name)
Identical to rb_const_defined_at(), except it returns the actual defined value.
Definition variable.c:3558
void rb_set_class_path_string(VALUE klass, VALUE space, VALUE name)
Identical to rb_set_class_path(), except it accepts the name as Ruby's string instead of C's.
Definition variable.c:440
void rb_alias_variable(ID dst, ID src)
Aliases a global variable.
Definition variable.c:1231
void rb_define_class_variable(VALUE, const char *, VALUE)
Just another name of rb_cv_set.
Definition variable.c:4465
VALUE rb_obj_remove_instance_variable(VALUE obj, VALUE name)
Resembles Object#remove_instance_variable.
Definition variable.c:2626
void * rb_mod_const_of(VALUE, void *)
This is a variant of rb_mod_const_at().
Definition variable.c:3777
st_index_t rb_ivar_count(VALUE obj)
Number of instance variables defined on an object.
Definition variable.c:2522
void * rb_mod_const_at(VALUE, void *)
This API is mysterious.
Definition variable.c:3762
VALUE rb_const_remove(VALUE space, ID name)
Identical to rb_mod_remove_const(), except it takes the name as ID instead of VALUE.
Definition variable.c:3670
VALUE rb_const_get_from(VALUE space, ID name)
Identical to rb_const_defined_at(), except it returns the actual defined value.
Definition variable.c:3546
VALUE rb_ivar_defined(VALUE obj, ID name)
Queries if the instance variable is defined at the object.
Definition variable.c:2245
VALUE rb_cv_get(VALUE klass, const char *name)
Identical to rb_cvar_get(), except it accepts C's string instead of ID.
Definition variable.c:4458
int rb_const_defined_at(VALUE space, ID name)
Identical to rb_const_defined(), except it doesn't look for parent classes.
Definition variable.c:3893
void rb_cv_set(VALUE klass, const char *name, VALUE val)
Identical to rb_cvar_set(), except it accepts C's string instead of ID.
Definition variable.c:4451
VALUE rb_mod_class_variables(int argc, const VALUE *argv, VALUE recv)
Resembles Module#class_variables.
Definition variable.c:4555
VALUE rb_f_global_variables(void)
Queries the list of global variables.
Definition variable.c:1198
VALUE rb_cvar_defined(VALUE klass, ID name)
Queries if the given class has the given class variable.
Definition variable.c:4432
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:397
int rb_const_defined_from(VALUE space, ID name)
Identical to rb_const_defined(), except it returns false for private constants.
Definition variable.c:3881
int rb_const_defined(VALUE space, ID name)
Queries if the constant is defined at the namespace.
Definition variable.c:3887
void rb_free_generic_ivar(VALUE obj)
Frees the list of instance variables.
Definition variable.c:1463
const char * rb_sourcefile(void)
Resembles __FILE__.
Definition vm.c:2208
void rb_clear_constant_cache_for_id(ID id)
Clears the inline constant caches associated with a particular ID.
Definition vm_method.c:334
int rb_obj_respond_to(VALUE obj, ID mid, int private_p)
Identical to rb_respond_to(), except it additionally takes the visibility parameter.
Definition vm_method.c:3749
VALUE rb_id2sym(ID id)
Allocates an instance of rb_cSymbol that has the given id.
Definition symbol.c:1141
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1302
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:16530
rb_gvar_setter_t rb_gvar_var_setter
Definition variable.h:119
rb_gvar_marker_t rb_gvar_var_marker
Definition variable.h:128
void rb_define_global_const(const char *name, VALUE val)
Identical to rb_define_const(), except it defines that of "global", i.e.
Definition variable.c:4141
VALUE rb_gv_get(const char *name)
Obtains a global variable.
Definition variable.c:1147
void rb_define_variable(const char *name, VALUE *var)
"Shares" a global variable between Ruby and C.
Definition variable.c:883
void rb_gvar_marker_t(VALUE *var)
Type that represents a global variable marker function.
Definition variable.h:53
void rb_deprecate_constant(VALUE mod, const char *name)
Asserts that the given constant is deprecated.
Definition variable.c:4186
void rb_gvar_setter_t(VALUE val, ID id, VALUE *data)
Type that represents a global variable setter function.
Definition variable.h:46
rb_gvar_setter_t rb_gvar_val_setter
This is the setter function that backs global variables defined from a ruby script.
Definition variable.h:94
rb_gvar_marker_t rb_gvar_undef_marker
Definition variable.h:80
void rb_define_readonly_variable(const char *name, const VALUE *var)
Identical to rb_define_variable(), except it does not allow Ruby programs to assign values to such gl...
Definition variable.c:889
rb_gvar_setter_t rb_gvar_readonly_setter
This function just raises rb_eNameError.
Definition variable.h:135
rb_gvar_getter_t rb_gvar_undef_getter
Definition variable.h:62
VALUE rb_gv_set(const char *name, VALUE val)
Assigns to a global variable.
Definition variable.c:1091
rb_gvar_marker_t rb_gvar_val_marker
This is the setter function that backs global variables defined from a ruby script.
Definition variable.h:101
VALUE rb_gvar_getter_t(ID id, VALUE *data)
Type that represents a global variable getter function.
Definition variable.h:37
VALUE rb_iv_get(VALUE obj, const char *name)
Obtains an instance variable.
Definition variable.c:4615
rb_gvar_setter_t rb_gvar_undef_setter
Definition variable.h:71
rb_gvar_getter_t rb_gvar_val_getter
This is the getter function that backs global variables defined from a ruby script.
Definition variable.h:87
VALUE rb_iv_set(VALUE obj, const char *name, VALUE val)
Assigns to an instance variable.
Definition variable.c:4626
rb_gvar_getter_t rb_gvar_var_getter
Definition variable.h:110
int capa
Designed capacity of the buffer.
Definition io.h:11
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SET_SHAREABLE(obj)
Wrapper of rb_obj_set_shareable().
Definition ractor.h:290
static bool rb_ractor_shareable_p(VALUE obj)
Queries if multiple Ractors can share the passed object or not.
Definition ractor.h:269
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:255
#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.
void rb_define_virtual_variable(const char *q, type *w, void_type *e)
Define a function-backended global variable.
void rb_ivar_foreach(VALUE q, int_type *w, VALUE e)
Iteration over each instance variable of the object.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c:2379
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:166
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:122
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 RTYPEDDATA(obj)
Convenient casting macro.
Definition rtypeddata.h:96
#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
const char * rb_class2name(VALUE klass)
Queries the name of the passed class.
Definition variable.c:523
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:532
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#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
C99 shim for <stdbool.h>.
Definition variable.c:2480
Internal header for Class.
Definition class.h:31
Definition variable.c:558
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
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 enum ruby_value_type rb_type(VALUE obj)
Identical to RB_BUILTIN_TYPE(), except it can also accept special constants.
Definition value_type.h:225
static enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition value_type.h:182
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