1 /**********************************************************************
2 
3   variable.c -
4 
5   $Author: usa $
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/encoding.h"
15 #include "ruby/st.h"
16 #include "ruby/util.h"
17 #include "internal.h"
18 #include "id_table.h"
19 #include "constant.h"
20 #include "id.h"
21 #include "ccan/list/list.h"
22 #include "id_table.h"
23 #include "debug_counter.h"
24 #include "vm_core.h"
25 #include "transient_heap.h"
26 
27 static struct rb_id_table *rb_global_tbl;
28 static ID autoload, classpath, tmp_classpath, classid;
29 static VALUE autoload_featuremap; /* feature => autoload_i */
30 
31 static void check_before_mod_set(VALUE, ID, VALUE, const char *);
32 static void setup_const_entry(rb_const_entry_t *, VALUE, VALUE, rb_const_flag_t);
33 static VALUE rb_const_search(VALUE klass, ID id, int exclude, int recurse, int visibility);
34 static st_table *generic_iv_tbl;
35 static st_table *generic_iv_tbl_compat;
36 
37 /* per-object */
38 struct gen_ivtbl {
39     uint32_t numiv;
40     VALUE ivptr[FLEX_ARY_LEN];
41 };
42 
43 struct ivar_update {
44     union {
45 	st_table *iv_index_tbl;
46 	struct gen_ivtbl *ivtbl;
47     } u;
48     st_data_t index;
49     int iv_extended;
50 };
51 
52 void
Init_var_tables(void)53 Init_var_tables(void)
54 {
55     rb_global_tbl = rb_id_table_create(0);
56     generic_iv_tbl = st_init_numtable();
57     autoload = rb_intern_const("__autoload__");
58     /* __classpath__: fully qualified class path */
59     classpath = rb_intern_const("__classpath__");
60     /* __tmp_classpath__: temporary class path which contains anonymous names */
61     tmp_classpath = rb_intern_const("__tmp_classpath__");
62     /* __classid__: name given to class/module under an anonymous namespace */
63     classid = rb_intern_const("__classid__");
64 }
65 
66 struct fc_result {
67     ID name, preferred;
68     VALUE klass;
69     VALUE path;
70     VALUE track;
71     struct fc_result *prev;
72 };
73 
74 static VALUE
fc_path(struct fc_result * fc,ID name)75 fc_path(struct fc_result *fc, ID name)
76 {
77     VALUE path, tmp;
78 
79     path = rb_id2str(name);
80     while (fc) {
81 	st_data_t n;
82 	if (fc->track == rb_cObject) break;
83 	if (RCLASS_IV_TBL(fc->track) &&
84 	    st_lookup(RCLASS_IV_TBL(fc->track), (st_data_t)classpath, &n)) {
85 	    tmp = rb_str_dup((VALUE)n);
86 	    rb_str_cat2(tmp, "::");
87 	    rb_str_append(tmp, path);
88 	    path = tmp;
89 	    break;
90 	}
91 	tmp = rb_str_dup(rb_id2str(fc->name));
92 	rb_str_cat2(tmp, "::");
93 	rb_str_append(tmp, path);
94 	path = tmp;
95 	fc = fc->prev;
96     }
97     OBJ_FREEZE(path);
98     return path;
99 }
100 
101 static enum rb_id_table_iterator_result
fc_i(ID key,VALUE v,void * a)102 fc_i(ID key, VALUE v, void *a)
103 {
104     rb_const_entry_t *ce = (rb_const_entry_t *)v;
105     struct fc_result *res = a;
106     VALUE value = ce->value;
107     if (!rb_is_const_id(key)) return ID_TABLE_CONTINUE;
108 
109     if (value == res->klass && (!res->preferred || key == res->preferred)) {
110 	res->path = fc_path(res, key);
111 	return ID_TABLE_STOP;
112     }
113     if (RB_TYPE_P(value, T_MODULE) || RB_TYPE_P(value, T_CLASS)) {
114 	if (!RCLASS_CONST_TBL(value)) return ID_TABLE_CONTINUE;
115 	else {
116 	    struct fc_result arg;
117 	    struct fc_result *list;
118 
119 	    list = res;
120 	    while (list) {
121 		if (list->track == value) return ID_TABLE_CONTINUE;
122 		list = list->prev;
123 	    }
124 
125 	    arg.name = key;
126 	    arg.preferred = res->preferred;
127 	    arg.path = 0;
128 	    arg.klass = res->klass;
129 	    arg.track = value;
130 	    arg.prev = res;
131 	    rb_id_table_foreach(RCLASS_CONST_TBL(value), fc_i, &arg);
132 	    if (arg.path) {
133 		res->path = arg.path;
134 		return ID_TABLE_STOP;
135 	    }
136 	}
137     }
138     return ID_TABLE_CONTINUE;
139 }
140 
141 /**
142  * Traverse constant namespace and find +classpath+ for _klass_.  If
143  * _preferred_ is not 0, choice the path whose base name is set to it.
144  * If +classpath+ is found, the hidden instance variable __classpath__
145  * is set to the found path, and __tmp_classpath__ is removed.
146  * The path is frozen.
147  */
148 static VALUE
find_class_path(VALUE klass,ID preferred)149 find_class_path(VALUE klass, ID preferred)
150 {
151     struct fc_result arg;
152 
153     arg.preferred = preferred;
154     arg.name = 0;
155     arg.path = 0;
156     arg.klass = klass;
157     arg.track = rb_cObject;
158     arg.prev = 0;
159     if (RCLASS_CONST_TBL(rb_cObject)) {
160 	rb_id_table_foreach(RCLASS_CONST_TBL(rb_cObject), fc_i, &arg);
161     }
162     if (arg.path) {
163 	st_data_t tmp = tmp_classpath;
164 	if (!RCLASS_IV_TBL(klass)) {
165 	    RCLASS_IV_TBL(klass) = st_init_numtable();
166 	}
167 	rb_class_ivar_set(klass, classpath, arg.path);
168 
169 	st_delete(RCLASS_IV_TBL(klass), &tmp, 0);
170 	return arg.path;
171     }
172     return Qnil;
173 }
174 
175 /**
176  * Returns +classpath+ of _klass_, if it is named, or +nil+ for
177  * anonymous +class+/+module+.  The last part of named +classpath+ is
178  * never anonymous, but anonymous +class+/+module+ names may be
179  * contained.  If the path is "permanent", that means it has no
180  * anonymous names, <code>*permanent</code> is set to 1.
181  */
182 static VALUE
classname(VALUE klass,int * permanent)183 classname(VALUE klass, int *permanent)
184 {
185     VALUE path = Qnil;
186     st_data_t n;
187 
188     if (!klass) klass = rb_cObject;
189     *permanent = 1;
190     if (RCLASS_IV_TBL(klass)) {
191 	if (!st_lookup(RCLASS_IV_TBL(klass), (st_data_t)classpath, &n)) {
192 	    ID cid = 0;
193 	    if (st_lookup(RCLASS_IV_TBL(klass), (st_data_t)classid, &n)) {
194 		VALUE cname = (VALUE)n;
195 		cid = rb_check_id(&cname);
196 		if (cid) path = find_class_path(klass, cid);
197 	    }
198 	    if (NIL_P(path)) {
199 		path = find_class_path(klass, (ID)0);
200 	    }
201 	    if (NIL_P(path)) {
202 		if (!cid) {
203 		    return Qnil;
204 		}
205 		if (!st_lookup(RCLASS_IV_TBL(klass), (st_data_t)tmp_classpath, &n)) {
206 		    path = rb_id2str(cid);
207 		    return path;
208 		}
209 		*permanent = 0;
210 		path = (VALUE)n;
211 		return path;
212 	    }
213 	}
214 	else {
215 	    path = (VALUE)n;
216 	}
217 	if (!RB_TYPE_P(path, T_STRING)) {
218 	    rb_bug("class path is not set properly");
219 	}
220 	return path;
221     }
222     return find_class_path(klass, (ID)0);
223 }
224 
225 /*
226  *  call-seq:
227  *     mod.name    -> string
228  *
229  *  Returns the name of the module <i>mod</i>.  Returns nil for anonymous modules.
230  */
231 
232 VALUE
rb_mod_name(VALUE mod)233 rb_mod_name(VALUE mod)
234 {
235     int permanent;
236     VALUE path = classname(mod, &permanent);
237 
238     if (!NIL_P(path)) return rb_str_dup(path);
239     return path;
240 }
241 
242 static VALUE
make_temporary_path(VALUE obj,VALUE klass)243 make_temporary_path(VALUE obj, VALUE klass)
244 {
245     VALUE path;
246     switch (klass) {
247       case Qnil:
248 	path = rb_sprintf("#<Class:%p>", (void*)obj);
249 	break;
250       case Qfalse:
251 	path = rb_sprintf("#<Module:%p>", (void*)obj);
252 	break;
253       default:
254 	path = rb_sprintf("#<%"PRIsVALUE":%p>", klass, (void*)obj);
255 	break;
256     }
257     OBJ_FREEZE(path);
258     return path;
259 }
260 
261 typedef VALUE (*path_cache_func)(VALUE obj, VALUE name);
262 
263 static VALUE
rb_tmp_class_path(VALUE klass,int * permanent,path_cache_func cache_path)264 rb_tmp_class_path(VALUE klass, int *permanent, path_cache_func cache_path)
265 {
266     VALUE path = classname(klass, permanent);
267     st_data_t n = (st_data_t)path;
268 
269     if (!NIL_P(path)) {
270 	return path;
271     }
272     if (RCLASS_IV_TBL(klass) && st_lookup(RCLASS_IV_TBL(klass),
273 					  (st_data_t)tmp_classpath, &n)) {
274 	*permanent = 0;
275 	return (VALUE)n;
276     }
277     else {
278 	if (RB_TYPE_P(klass, T_MODULE)) {
279 	    if (rb_obj_class(klass) == rb_cModule) {
280 		path = Qfalse;
281 	    }
282 	    else {
283 		int perm;
284 		path = rb_tmp_class_path(RBASIC(klass)->klass, &perm, cache_path);
285 	    }
286 	}
287 	*permanent = 0;
288 	return cache_path(klass, path);
289     }
290 }
291 
292 static VALUE
ivar_cache(VALUE obj,VALUE name)293 ivar_cache(VALUE obj, VALUE name)
294 {
295     return rb_ivar_set(obj, tmp_classpath, make_temporary_path(obj, name));
296 }
297 
298 VALUE
rb_class_path(VALUE klass)299 rb_class_path(VALUE klass)
300 {
301     int permanent;
302     VALUE path = rb_tmp_class_path(klass, &permanent, ivar_cache);
303     if (!NIL_P(path)) path = rb_str_dup(path);
304     return path;
305 }
306 
307 static VALUE
null_cache(VALUE obj,VALUE name)308 null_cache(VALUE obj, VALUE name)
309 {
310     return make_temporary_path(obj, name);
311 }
312 
313 VALUE
rb_class_path_no_cache(VALUE klass)314 rb_class_path_no_cache(VALUE klass)
315 {
316     int permanent;
317     VALUE path = rb_tmp_class_path(klass, &permanent, null_cache);
318     if (!NIL_P(path)) path = rb_str_dup(path);
319     return path;
320 }
321 
322 VALUE
rb_class_path_cached(VALUE klass)323 rb_class_path_cached(VALUE klass)
324 {
325     st_table *ivtbl;
326     st_data_t n;
327 
328     if (!RCLASS_EXT(klass)) return Qnil;
329     if (!(ivtbl = RCLASS_IV_TBL(klass))) return Qnil;
330     if (st_lookup(ivtbl, (st_data_t)classpath, &n)) return (VALUE)n;
331     if (st_lookup(ivtbl, (st_data_t)tmp_classpath, &n)) return (VALUE)n;
332     return Qnil;
333 }
334 
335 static VALUE
never_cache(VALUE obj,VALUE name)336 never_cache(VALUE obj, VALUE name)
337 {
338     return name;
339 }
340 
341 VALUE
rb_search_class_path(VALUE klass)342 rb_search_class_path(VALUE klass)
343 {
344     int permanent;
345     return rb_tmp_class_path(klass, &permanent, never_cache);
346 }
347 
348 void
rb_set_class_path_string(VALUE klass,VALUE under,VALUE name)349 rb_set_class_path_string(VALUE klass, VALUE under, VALUE name)
350 {
351     VALUE str;
352     ID pathid = classpath;
353 
354     if (under == rb_cObject) {
355 	str = rb_str_new_frozen(name);
356     }
357     else {
358 	int permanent;
359 	str = rb_str_dup(rb_tmp_class_path(under, &permanent, ivar_cache));
360 	rb_str_cat2(str, "::");
361 	rb_str_append(str, name);
362 	OBJ_FREEZE(str);
363 	if (!permanent) {
364 	    pathid = tmp_classpath;
365 	    rb_ivar_set(klass, classid, rb_str_intern(name));
366 	}
367     }
368     rb_ivar_set(klass, pathid, str);
369 }
370 
371 void
rb_set_class_path(VALUE klass,VALUE under,const char * name)372 rb_set_class_path(VALUE klass, VALUE under, const char *name)
373 {
374     VALUE str;
375     ID pathid = classpath;
376 
377     if (under == rb_cObject) {
378 	str = rb_str_new2(name);
379     }
380     else {
381 	int permanent;
382 	str = rb_str_dup(rb_tmp_class_path(under, &permanent, ivar_cache));
383 	rb_str_cat2(str, "::");
384 	rb_str_cat2(str, name);
385 	if (!permanent) {
386 	    pathid = tmp_classpath;
387 	    rb_ivar_set(klass, classid, rb_str_intern(rb_str_new_cstr(name)));
388 	}
389     }
390     OBJ_FREEZE(str);
391     rb_ivar_set(klass, pathid, str);
392 }
393 
394 VALUE
rb_path_to_class(VALUE pathname)395 rb_path_to_class(VALUE pathname)
396 {
397     rb_encoding *enc = rb_enc_get(pathname);
398     const char *pbeg, *pend, *p, *path = RSTRING_PTR(pathname);
399     ID id;
400     VALUE c = rb_cObject;
401 
402     if (!rb_enc_asciicompat(enc)) {
403 	rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
404     }
405     pbeg = p = path;
406     pend = path + RSTRING_LEN(pathname);
407     if (path == pend || path[0] == '#') {
408 	rb_raise(rb_eArgError, "can't retrieve anonymous class %"PRIsVALUE,
409 		 QUOTE(pathname));
410     }
411     while (p < pend) {
412 	while (p < pend && *p != ':') p++;
413 	id = rb_check_id_cstr(pbeg, p-pbeg, enc);
414 	if (p < pend && p[0] == ':') {
415 	    if ((size_t)(pend - p) < 2 || p[1] != ':') goto undefined_class;
416 	    p += 2;
417 	    pbeg = p;
418 	}
419 	if (!id) {
420 	  undefined_class:
421 	    rb_raise(rb_eArgError, "undefined class/module % "PRIsVALUE,
422 		     rb_str_subseq(pathname, 0, p-path));
423 	}
424 	c = rb_const_search(c, id, TRUE, FALSE, FALSE);
425 	if (c == Qundef) goto undefined_class;
426 	if (!RB_TYPE_P(c, T_MODULE) && !RB_TYPE_P(c, T_CLASS)) {
427 	    rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
428 		     pathname);
429 	}
430     }
431     RB_GC_GUARD(pathname);
432 
433     return c;
434 }
435 
436 VALUE
rb_path2class(const char * path)437 rb_path2class(const char *path)
438 {
439     return rb_path_to_class(rb_str_new_cstr(path));
440 }
441 
442 void
rb_name_class(VALUE klass,ID id)443 rb_name_class(VALUE klass, ID id)
444 {
445     rb_ivar_set(klass, classid, ID2SYM(id));
446 }
447 
448 VALUE
rb_class_name(VALUE klass)449 rb_class_name(VALUE klass)
450 {
451     return rb_class_path(rb_class_real(klass));
452 }
453 
454 const char *
rb_class2name(VALUE klass)455 rb_class2name(VALUE klass)
456 {
457     int permanent;
458     VALUE path = rb_tmp_class_path(rb_class_real(klass), &permanent, ivar_cache);
459     if (NIL_P(path)) return NULL;
460     return RSTRING_PTR(path);
461 }
462 
463 const char *
rb_obj_classname(VALUE obj)464 rb_obj_classname(VALUE obj)
465 {
466     return rb_class2name(CLASS_OF(obj));
467 }
468 
469 struct trace_var {
470     int removed;
471     void (*func)(VALUE arg, VALUE val);
472     VALUE data;
473     struct trace_var *next;
474 };
475 
476 struct rb_global_variable {
477     int counter;
478     int block_trace;
479     void *data;
480     rb_gvar_getter_t *getter;
481     rb_gvar_setter_t *setter;
482     rb_gvar_marker_t *marker;
483     struct trace_var *trace;
484 };
485 
486 static struct rb_global_entry*
rb_find_global_entry(ID id)487 rb_find_global_entry(ID id)
488 {
489     struct rb_global_entry *entry;
490     VALUE data;
491 
492     if (!rb_id_table_lookup(rb_global_tbl, id, &data)) {
493         return NULL;
494     }
495     entry = (struct rb_global_entry *)data;
496     ASSUME(entry != NULL);
497     return entry;
498 }
499 
500 MJIT_FUNC_EXPORTED struct rb_global_entry*
rb_global_entry(ID id)501 rb_global_entry(ID id)
502 {
503     struct rb_global_entry *entry = rb_find_global_entry(id);
504     if (!entry) {
505 	struct rb_global_variable *var;
506 	entry = ALLOC(struct rb_global_entry);
507 	var = ALLOC(struct rb_global_variable);
508 	entry->id = id;
509 	entry->var = var;
510 	var->counter = 1;
511 	var->data = 0;
512 	var->getter = rb_gvar_undef_getter;
513 	var->setter = rb_gvar_undef_setter;
514 	var->marker = rb_gvar_undef_marker;
515 
516 	var->block_trace = 0;
517 	var->trace = 0;
518 	rb_id_table_insert(rb_global_tbl, id, (VALUE)entry);
519     }
520     return entry;
521 }
522 
523 VALUE
rb_gvar_undef_getter(ID id,void * data,struct rb_global_variable * var)524 rb_gvar_undef_getter(ID id, void *data, struct rb_global_variable *var)
525 {
526     rb_warning("global variable `%"PRIsVALUE"' not initialized", QUOTE_ID(id));
527 
528     return Qnil;
529 }
530 
531 void
rb_gvar_undef_setter(VALUE val,ID id,void * d,struct rb_global_variable * var)532 rb_gvar_undef_setter(VALUE val, ID id, void *d, struct rb_global_variable *var)
533 {
534     var->getter = rb_gvar_val_getter;
535     var->setter = rb_gvar_val_setter;
536     var->marker = rb_gvar_val_marker;
537 
538     var->data = (void*)val;
539 }
540 
541 void
rb_gvar_undef_marker(VALUE * var)542 rb_gvar_undef_marker(VALUE *var)
543 {
544 }
545 
546 VALUE
rb_gvar_val_getter(ID id,void * data,struct rb_global_variable * var)547 rb_gvar_val_getter(ID id, void *data, struct rb_global_variable *var)
548 {
549     return (VALUE)data;
550 }
551 
552 void
rb_gvar_val_setter(VALUE val,ID id,void * data,struct rb_global_variable * var)553 rb_gvar_val_setter(VALUE val, ID id, void *data, struct rb_global_variable *var)
554 {
555     var->data = (void*)val;
556 }
557 
558 void
rb_gvar_val_marker(VALUE * var)559 rb_gvar_val_marker(VALUE *var)
560 {
561     VALUE data = (VALUE)var;
562     if (data) rb_gc_mark_maybe(data);
563 }
564 
565 VALUE
rb_gvar_var_getter(ID id,void * data,struct rb_global_variable * gvar)566 rb_gvar_var_getter(ID id, void *data, struct rb_global_variable *gvar)
567 {
568     VALUE *var = data;
569     if (!var) return Qnil;
570     return *var;
571 }
572 
573 void
rb_gvar_var_setter(VALUE val,ID id,void * data,struct rb_global_variable * g)574 rb_gvar_var_setter(VALUE val, ID id, void *data, struct rb_global_variable *g)
575 {
576     *(VALUE *)data = val;
577 }
578 
579 void
rb_gvar_var_marker(VALUE * var)580 rb_gvar_var_marker(VALUE *var)
581 {
582     if (var) rb_gc_mark_maybe(*var);
583 }
584 
585 void
rb_gvar_readonly_setter(VALUE v,ID id,void * d,struct rb_global_variable * g)586 rb_gvar_readonly_setter(VALUE v, ID id, void *d, struct rb_global_variable *g)
587 {
588     rb_name_error(id, "%"PRIsVALUE" is a read-only variable", QUOTE_ID(id));
589 }
590 
591 static enum rb_id_table_iterator_result
mark_global_entry(VALUE v,void * ignored)592 mark_global_entry(VALUE v, void *ignored)
593 {
594     struct rb_global_entry *entry = (struct rb_global_entry *)v;
595     struct trace_var *trace;
596     struct rb_global_variable *var = entry->var;
597 
598     (*var->marker)(var->data);
599     trace = var->trace;
600     while (trace) {
601 	if (trace->data) rb_gc_mark_maybe(trace->data);
602 	trace = trace->next;
603     }
604     return ID_TABLE_CONTINUE;
605 }
606 
607 void
rb_gc_mark_global_tbl(void)608 rb_gc_mark_global_tbl(void)
609 {
610     if (rb_global_tbl)
611         rb_id_table_foreach_values(rb_global_tbl, mark_global_entry, 0);
612 }
613 
614 static ID
global_id(const char * name)615 global_id(const char *name)
616 {
617     ID id;
618 
619     if (name[0] == '$') id = rb_intern(name);
620     else {
621 	size_t len = strlen(name);
622         VALUE vbuf = 0;
623         char *buf = ALLOCV_N(char, vbuf, len+1);
624 	buf[0] = '$';
625 	memcpy(buf+1, name, len);
626 	id = rb_intern2(buf, len+1);
627         ALLOCV_END(vbuf);
628     }
629     return id;
630 }
631 
632 static ID
find_global_id(const char * name)633 find_global_id(const char *name)
634 {
635     ID id;
636     size_t len = strlen(name);
637 
638     if (name[0] == '$') {
639         id = rb_check_id_cstr(name, len, NULL);
640     }
641     else {
642         VALUE vbuf = 0;
643         char *buf = ALLOCV_N(char, vbuf, len+1);
644         buf[0] = '$';
645         memcpy(buf+1, name, len);
646         id = rb_check_id_cstr(buf, len+1, NULL);
647         ALLOCV_END(vbuf);
648     }
649 
650     return id;
651 }
652 
653 void
rb_define_hooked_variable(const char * name,VALUE * var,VALUE (* getter)(ANYARGS),void (* setter)(ANYARGS))654 rb_define_hooked_variable(
655     const char *name,
656     VALUE *var,
657     VALUE (*getter)(ANYARGS),
658     void  (*setter)(ANYARGS))
659 {
660     volatile VALUE tmp = var ? *var : Qnil;
661     ID id = global_id(name);
662     struct rb_global_variable *gvar = rb_global_entry(id)->var;
663 
664     gvar->data = (void*)var;
665     gvar->getter = getter ? (rb_gvar_getter_t *)getter : rb_gvar_var_getter;
666     gvar->setter = setter ? (rb_gvar_setter_t *)setter : rb_gvar_var_setter;
667     gvar->marker = rb_gvar_var_marker;
668 
669     RB_GC_GUARD(tmp);
670 }
671 
672 void
rb_define_variable(const char * name,VALUE * var)673 rb_define_variable(const char *name, VALUE *var)
674 {
675     rb_define_hooked_variable(name, var, 0, 0);
676 }
677 
678 void
rb_define_readonly_variable(const char * name,const VALUE * var)679 rb_define_readonly_variable(const char *name, const VALUE *var)
680 {
681     rb_define_hooked_variable(name, (VALUE *)var, 0, rb_gvar_readonly_setter);
682 }
683 
684 void
rb_define_virtual_variable(const char * name,VALUE (* getter)(ANYARGS),void (* setter)(ANYARGS))685 rb_define_virtual_variable(
686     const char *name,
687     VALUE (*getter)(ANYARGS),
688     void  (*setter)(ANYARGS))
689 {
690     if (!getter) getter = rb_gvar_val_getter;
691     if (!setter) setter = rb_gvar_readonly_setter;
692     rb_define_hooked_variable(name, 0, getter, setter);
693 }
694 
695 static void
rb_trace_eval(VALUE cmd,VALUE val)696 rb_trace_eval(VALUE cmd, VALUE val)
697 {
698     rb_eval_cmd(cmd, rb_ary_new3(1, val), 0);
699 }
700 
701 /*
702  *  call-seq:
703  *     trace_var(symbol, cmd )             -> nil
704  *     trace_var(symbol) {|val| block }    -> nil
705  *
706  *  Controls tracing of assignments to global variables. The parameter
707  *  +symbol+ identifies the variable (as either a string name or a
708  *  symbol identifier). _cmd_ (which may be a string or a
709  *  +Proc+ object) or block is executed whenever the variable
710  *  is assigned. The block or +Proc+ object receives the
711  *  variable's new value as a parameter. Also see
712  *  <code>Kernel::untrace_var</code>.
713  *
714  *     trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
715  *     $_ = "hello"
716  *     $_ = ' there'
717  *
718  *  <em>produces:</em>
719  *
720  *     $_ is now 'hello'
721  *     $_ is now ' there'
722  */
723 
724 VALUE
rb_f_trace_var(int argc,const VALUE * argv)725 rb_f_trace_var(int argc, const VALUE *argv)
726 {
727     VALUE var, cmd;
728     struct rb_global_entry *entry;
729     struct trace_var *trace;
730 
731     if (rb_scan_args(argc, argv, "11", &var, &cmd) == 1) {
732 	cmd = rb_block_proc();
733     }
734     if (NIL_P(cmd)) {
735 	return rb_f_untrace_var(argc, argv);
736     }
737     entry = rb_global_entry(rb_to_id(var));
738     if (OBJ_TAINTED(cmd)) {
739 	rb_raise(rb_eSecurityError, "Insecure: tainted variable trace");
740     }
741     trace = ALLOC(struct trace_var);
742     trace->next = entry->var->trace;
743     trace->func = rb_trace_eval;
744     trace->data = cmd;
745     trace->removed = 0;
746     entry->var->trace = trace;
747 
748     return Qnil;
749 }
750 
751 static void
remove_trace(struct rb_global_variable * var)752 remove_trace(struct rb_global_variable *var)
753 {
754     struct trace_var *trace = var->trace;
755     struct trace_var t;
756     struct trace_var *next;
757 
758     t.next = trace;
759     trace = &t;
760     while (trace->next) {
761 	next = trace->next;
762 	if (next->removed) {
763 	    trace->next = next->next;
764 	    xfree(next);
765 	}
766 	else {
767 	    trace = next;
768 	}
769     }
770     var->trace = t.next;
771 }
772 
773 /*
774  *  call-seq:
775  *     untrace_var(symbol [, cmd] )   -> array or nil
776  *
777  *  Removes tracing for the specified command on the given global
778  *  variable and returns +nil+. If no command is specified,
779  *  removes all tracing for that variable and returns an array
780  *  containing the commands actually removed.
781  */
782 
783 VALUE
rb_f_untrace_var(int argc,const VALUE * argv)784 rb_f_untrace_var(int argc, const VALUE *argv)
785 {
786     VALUE var, cmd;
787     ID id;
788     struct rb_global_entry *entry;
789     struct trace_var *trace;
790     VALUE data;
791 
792     rb_scan_args(argc, argv, "11", &var, &cmd);
793     id = rb_check_id(&var);
794     if (!id) {
795 	rb_name_error_str(var, "undefined global variable %"PRIsVALUE"", QUOTE(var));
796     }
797     if (!rb_id_table_lookup(rb_global_tbl, id, &data)) {
798 	rb_name_error(id, "undefined global variable %"PRIsVALUE"", QUOTE_ID(id));
799     }
800 
801     trace = (entry = (struct rb_global_entry *)data)->var->trace;
802     if (NIL_P(cmd)) {
803 	VALUE ary = rb_ary_new();
804 
805 	while (trace) {
806 	    struct trace_var *next = trace->next;
807 	    rb_ary_push(ary, (VALUE)trace->data);
808 	    trace->removed = 1;
809 	    trace = next;
810 	}
811 
812 	if (!entry->var->block_trace) remove_trace(entry->var);
813 	return ary;
814     }
815     else {
816 	while (trace) {
817 	    if (trace->data == cmd) {
818 		trace->removed = 1;
819 		if (!entry->var->block_trace) remove_trace(entry->var);
820 		return rb_ary_new3(1, cmd);
821 	    }
822 	    trace = trace->next;
823 	}
824     }
825     return Qnil;
826 }
827 
828 MJIT_FUNC_EXPORTED VALUE
rb_gvar_get(struct rb_global_entry * entry)829 rb_gvar_get(struct rb_global_entry *entry)
830 {
831     struct rb_global_variable *var = entry->var;
832     return (*var->getter)(entry->id, var->data, var);
833 }
834 
835 struct trace_data {
836     struct trace_var *trace;
837     VALUE val;
838 };
839 
840 static VALUE
trace_ev(struct trace_data * data)841 trace_ev(struct trace_data *data)
842 {
843     struct trace_var *trace = data->trace;
844 
845     while (trace) {
846 	(*trace->func)(trace->data, data->val);
847 	trace = trace->next;
848     }
849 
850     return Qnil;
851 }
852 
853 static VALUE
trace_en(struct rb_global_variable * var)854 trace_en(struct rb_global_variable *var)
855 {
856     var->block_trace = 0;
857     remove_trace(var);
858     return Qnil;		/* not reached */
859 }
860 
861 MJIT_FUNC_EXPORTED VALUE
rb_gvar_set(struct rb_global_entry * entry,VALUE val)862 rb_gvar_set(struct rb_global_entry *entry, VALUE val)
863 {
864     struct trace_data trace;
865     struct rb_global_variable *var = entry->var;
866 
867     (*var->setter)(val, entry->id, var->data, var);
868 
869     if (var->trace && !var->block_trace) {
870 	var->block_trace = 1;
871 	trace.trace = var->trace;
872 	trace.val = val;
873 	rb_ensure(trace_ev, (VALUE)&trace, trace_en, (VALUE)var);
874     }
875     return val;
876 }
877 
878 VALUE
rb_gv_set(const char * name,VALUE val)879 rb_gv_set(const char *name, VALUE val)
880 {
881     struct rb_global_entry *entry;
882 
883     entry = rb_global_entry(global_id(name));
884     return rb_gvar_set(entry, val);
885 }
886 
887 VALUE
rb_gv_get(const char * name)888 rb_gv_get(const char *name)
889 {
890     struct rb_global_entry *entry;
891     ID id = find_global_id(name);
892 
893     if (!id) {
894         rb_warning("global variable `%s' not initialized", name);
895         return Qnil;
896     }
897 
898     entry = rb_global_entry(id);
899     return rb_gvar_get(entry);
900 }
901 
902 MJIT_FUNC_EXPORTED VALUE
rb_gvar_defined(struct rb_global_entry * entry)903 rb_gvar_defined(struct rb_global_entry *entry)
904 {
905     if (entry->var->getter == rb_gvar_undef_getter) return Qfalse;
906     return Qtrue;
907 }
908 
909 rb_gvar_getter_t *
rb_gvar_getter_function_of(const struct rb_global_entry * entry)910 rb_gvar_getter_function_of(const struct rb_global_entry *entry)
911 {
912     return entry->var->getter;
913 }
914 
915 rb_gvar_setter_t *
rb_gvar_setter_function_of(const struct rb_global_entry * entry)916 rb_gvar_setter_function_of(const struct rb_global_entry *entry)
917 {
918     return entry->var->setter;
919 }
920 
921 bool
rb_gvar_is_traced(const struct rb_global_entry * entry)922 rb_gvar_is_traced(const struct rb_global_entry *entry)
923 {
924     return !!entry->var->trace;
925 }
926 
927 static enum rb_id_table_iterator_result
gvar_i(ID key,VALUE val,void * a)928 gvar_i(ID key, VALUE val, void *a)
929 {
930     VALUE ary = (VALUE)a;
931     rb_ary_push(ary, ID2SYM(key));
932     return ID_TABLE_CONTINUE;
933 }
934 
935 /*
936  *  call-seq:
937  *     global_variables    -> array
938  *
939  *  Returns an array of the names of global variables.
940  *
941  *     global_variables.grep /std/   #=> [:$stdin, :$stdout, :$stderr]
942  */
943 
944 VALUE
rb_f_global_variables(void)945 rb_f_global_variables(void)
946 {
947     VALUE ary = rb_ary_new();
948     VALUE sym, backref = rb_backref_get();
949 
950     rb_id_table_foreach(rb_global_tbl, gvar_i, (void *)ary);
951     if (!NIL_P(backref)) {
952 	char buf[2];
953 	int i, nmatch = rb_match_count(backref);
954 	buf[0] = '$';
955 	for (i = 1; i <= nmatch; ++i) {
956 	    if (!rb_match_nth_defined(i, backref)) continue;
957 	    if (i < 10) {
958 		/* probably reused, make static ID */
959 		buf[1] = (char)(i + '0');
960 		sym = ID2SYM(rb_intern2(buf, 2));
961 	    }
962 	    else {
963 		/* dynamic symbol */
964 		sym = rb_str_intern(rb_sprintf("$%d", i));
965 	    }
966 	    rb_ary_push(ary, sym);
967 	}
968     }
969     return ary;
970 }
971 
972 void
rb_alias_variable(ID name1,ID name2)973 rb_alias_variable(ID name1, ID name2)
974 {
975     struct rb_global_entry *entry1, *entry2;
976     VALUE data1;
977 
978     entry2 = rb_global_entry(name2);
979     if (!rb_id_table_lookup(rb_global_tbl, name1, &data1)) {
980 	entry1 = ALLOC(struct rb_global_entry);
981 	entry1->id = name1;
982 	rb_id_table_insert(rb_global_tbl, name1, (VALUE)entry1);
983     }
984     else if ((entry1 = (struct rb_global_entry *)data1)->var != entry2->var) {
985 	struct rb_global_variable *var = entry1->var;
986 	if (var->block_trace) {
987 	    rb_raise(rb_eRuntimeError, "can't alias in tracer");
988 	}
989 	var->counter--;
990 	if (var->counter == 0) {
991 	    struct trace_var *trace = var->trace;
992 	    while (trace) {
993 		struct trace_var *next = trace->next;
994 		xfree(trace);
995 		trace = next;
996 	    }
997 	    xfree(var);
998 	}
999     }
1000     else {
1001 	return;
1002     }
1003     entry2->var->counter++;
1004     entry1->var = entry2->var;
1005 }
1006 
1007 static int
gen_ivtbl_get(VALUE obj,struct gen_ivtbl ** ivtbl)1008 gen_ivtbl_get(VALUE obj, struct gen_ivtbl **ivtbl)
1009 {
1010     st_data_t data;
1011 
1012     if (st_lookup(generic_iv_tbl, (st_data_t)obj, &data)) {
1013 	*ivtbl = (struct gen_ivtbl *)data;
1014 	return 1;
1015     }
1016     return 0;
1017 }
1018 
1019 static VALUE
generic_ivar_delete(VALUE obj,ID id,VALUE undef)1020 generic_ivar_delete(VALUE obj, ID id, VALUE undef)
1021 {
1022     struct gen_ivtbl *ivtbl;
1023 
1024     if (gen_ivtbl_get(obj, &ivtbl)) {
1025 	st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(rb_obj_class(obj));
1026 	st_data_t index;
1027 
1028 	if (st_lookup(iv_index_tbl, (st_data_t)id, &index)) {
1029 	    if (index < ivtbl->numiv) {
1030 		VALUE ret = ivtbl->ivptr[index];
1031 
1032 		ivtbl->ivptr[index] = Qundef;
1033 		return ret == Qundef ? undef : ret;
1034 	    }
1035 	}
1036     }
1037     return undef;
1038 }
1039 
1040 static VALUE
generic_ivar_get(VALUE obj,ID id,VALUE undef)1041 generic_ivar_get(VALUE obj, ID id, VALUE undef)
1042 {
1043     struct gen_ivtbl *ivtbl;
1044 
1045     if (gen_ivtbl_get(obj, &ivtbl)) {
1046 	st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(rb_obj_class(obj));
1047 	st_data_t index;
1048 
1049 	if (st_lookup(iv_index_tbl, (st_data_t)id, &index)) {
1050 	    if (index < ivtbl->numiv) {
1051 		VALUE ret = ivtbl->ivptr[index];
1052 
1053 		return ret == Qundef ? undef : ret;
1054 	    }
1055 	}
1056     }
1057     return undef;
1058 }
1059 
1060 static size_t
gen_ivtbl_bytes(size_t n)1061 gen_ivtbl_bytes(size_t n)
1062 {
1063     return offsetof(struct gen_ivtbl, ivptr) + n * sizeof(VALUE);
1064 }
1065 
1066 static struct gen_ivtbl *
gen_ivtbl_resize(struct gen_ivtbl * old,uint32_t n)1067 gen_ivtbl_resize(struct gen_ivtbl *old, uint32_t n)
1068 {
1069     uint32_t len = old ? old->numiv : 0;
1070     struct gen_ivtbl *ivtbl = xrealloc(old, gen_ivtbl_bytes(n));
1071 
1072     ivtbl->numiv = n;
1073     for (; len < n; len++) {
1074 	ivtbl->ivptr[len] = Qundef;
1075     }
1076 
1077     return ivtbl;
1078 }
1079 
1080 #if 0
1081 static struct gen_ivtbl *
1082 gen_ivtbl_dup(const struct gen_ivtbl *orig)
1083 {
1084     size_t s = gen_ivtbl_bytes(orig->numiv);
1085     struct gen_ivtbl *ivtbl = xmalloc(s);
1086 
1087     memcpy(ivtbl, orig, s);
1088 
1089     return ivtbl;
1090 }
1091 #endif
1092 
1093 static uint32_t
iv_index_tbl_newsize(struct ivar_update * ivup)1094 iv_index_tbl_newsize(struct ivar_update *ivup)
1095 {
1096     uint32_t index = (uint32_t)ivup->index;	/* should not overflow */
1097     uint32_t newsize = (index+1) + (index+1)/4; /* (index+1)*1.25 */
1098 
1099     if (!ivup->iv_extended &&
1100         ivup->u.iv_index_tbl->num_entries < (st_index_t)newsize) {
1101         newsize = (uint32_t)ivup->u.iv_index_tbl->num_entries;
1102     }
1103     return newsize;
1104 }
1105 
1106 static int
generic_ivar_update(st_data_t * k,st_data_t * v,st_data_t u,int existing)1107 generic_ivar_update(st_data_t *k, st_data_t *v, st_data_t u, int existing)
1108 {
1109     VALUE obj = (VALUE)*k;
1110     struct ivar_update *ivup = (struct ivar_update *)u;
1111     uint32_t newsize;
1112     int ret = ST_CONTINUE;
1113     struct gen_ivtbl *ivtbl;
1114 
1115     if (existing) {
1116 	ivtbl = (struct gen_ivtbl *)*v;
1117 	if (ivup->index >= ivtbl->numiv) {
1118 	    goto resize;
1119 	}
1120 	ret = ST_STOP;
1121     }
1122     else {
1123 	FL_SET(obj, FL_EXIVAR);
1124 	ivtbl = 0;
1125 resize:
1126 	newsize = iv_index_tbl_newsize(ivup);
1127 	ivtbl = gen_ivtbl_resize(ivtbl, newsize);
1128 	*v = (st_data_t)ivtbl;
1129     }
1130     ivup->u.ivtbl = ivtbl;
1131     return ret;
1132 }
1133 
1134 static VALUE
generic_ivar_defined(VALUE obj,ID id)1135 generic_ivar_defined(VALUE obj, ID id)
1136 {
1137     struct gen_ivtbl *ivtbl;
1138     st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(rb_obj_class(obj));
1139     st_data_t index;
1140 
1141     if (!iv_index_tbl) return Qfalse;
1142     if (!st_lookup(iv_index_tbl, (st_data_t)id, &index)) return Qfalse;
1143     if (!gen_ivtbl_get(obj, &ivtbl)) return Qfalse;
1144 
1145     if ((index < ivtbl->numiv) && (ivtbl->ivptr[index] != Qundef))
1146 	return Qtrue;
1147 
1148     return Qfalse;
1149 }
1150 
1151 static int
generic_ivar_remove(VALUE obj,ID id,VALUE * valp)1152 generic_ivar_remove(VALUE obj, ID id, VALUE *valp)
1153 {
1154     struct gen_ivtbl *ivtbl;
1155     st_data_t key = (st_data_t)id;
1156     st_data_t index;
1157     st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(rb_obj_class(obj));
1158 
1159     if (!iv_index_tbl) return 0;
1160     if (!st_lookup(iv_index_tbl, key, &index)) return 0;
1161     if (!gen_ivtbl_get(obj, &ivtbl)) return 0;
1162 
1163     if (index < ivtbl->numiv) {
1164 	if (ivtbl->ivptr[index] != Qundef) {
1165 	    *valp = ivtbl->ivptr[index];
1166 	    ivtbl->ivptr[index] = Qundef;
1167 	    return 1;
1168 	}
1169     }
1170     return 0;
1171 }
1172 
1173 static void
gen_ivtbl_mark(const struct gen_ivtbl * ivtbl)1174 gen_ivtbl_mark(const struct gen_ivtbl *ivtbl)
1175 {
1176     uint32_t i;
1177 
1178     for (i = 0; i < ivtbl->numiv; i++) {
1179 	rb_gc_mark(ivtbl->ivptr[i]);
1180     }
1181 }
1182 
1183 void
rb_mark_generic_ivar(VALUE obj)1184 rb_mark_generic_ivar(VALUE obj)
1185 {
1186     struct gen_ivtbl *ivtbl;
1187 
1188     if (gen_ivtbl_get(obj, &ivtbl)) {
1189 	gen_ivtbl_mark(ivtbl);
1190     }
1191 }
1192 
1193 void
rb_free_generic_ivar(VALUE obj)1194 rb_free_generic_ivar(VALUE obj)
1195 {
1196     st_data_t key = (st_data_t)obj;
1197     struct gen_ivtbl *ivtbl;
1198 
1199     if (st_delete(generic_iv_tbl, &key, (st_data_t *)&ivtbl))
1200 	xfree(ivtbl);
1201 
1202     if (generic_iv_tbl_compat) {
1203 	st_table *tbl;
1204 
1205 	if (st_delete(generic_iv_tbl_compat, &key, (st_data_t *)&tbl))
1206 	    st_free_table(tbl);
1207     }
1208 }
1209 
1210 RUBY_FUNC_EXPORTED size_t
rb_generic_ivar_memsize(VALUE obj)1211 rb_generic_ivar_memsize(VALUE obj)
1212 {
1213     struct gen_ivtbl *ivtbl;
1214 
1215     if (gen_ivtbl_get(obj, &ivtbl))
1216 	return gen_ivtbl_bytes(ivtbl->numiv);
1217     return 0;
1218 }
1219 
1220 static size_t
gen_ivtbl_count(const struct gen_ivtbl * ivtbl)1221 gen_ivtbl_count(const struct gen_ivtbl *ivtbl)
1222 {
1223     uint32_t i;
1224     size_t n = 0;
1225 
1226     for (i = 0; i < ivtbl->numiv; i++) {
1227 	if (ivtbl->ivptr[i] != Qundef) {
1228 	    n++;
1229 	}
1230     }
1231 
1232     return n;
1233 }
1234 
1235 VALUE
rb_ivar_lookup(VALUE obj,ID id,VALUE undef)1236 rb_ivar_lookup(VALUE obj, ID id, VALUE undef)
1237 {
1238     VALUE val, *ptr;
1239     struct st_table *iv_index_tbl;
1240     uint32_t len;
1241     st_data_t index;
1242 
1243     if (SPECIAL_CONST_P(obj)) return undef;
1244     switch (BUILTIN_TYPE(obj)) {
1245       case T_OBJECT:
1246         len = ROBJECT_NUMIV(obj);
1247         ptr = ROBJECT_IVPTR(obj);
1248         iv_index_tbl = ROBJECT_IV_INDEX_TBL(obj);
1249         if (!iv_index_tbl) break;
1250         if (!st_lookup(iv_index_tbl, (st_data_t)id, &index)) break;
1251         if (len <= index) break;
1252         val = ptr[index];
1253         if (val != Qundef)
1254             return val;
1255 	break;
1256       case T_CLASS:
1257       case T_MODULE:
1258 	if (RCLASS_IV_TBL(obj) &&
1259 		st_lookup(RCLASS_IV_TBL(obj), (st_data_t)id, &index))
1260 	    return (VALUE)index;
1261 	break;
1262       default:
1263 	if (FL_TEST(obj, FL_EXIVAR))
1264 	    return generic_ivar_get(obj, id, undef);
1265 	break;
1266     }
1267     return undef;
1268 }
1269 
1270 VALUE
rb_ivar_get(VALUE obj,ID id)1271 rb_ivar_get(VALUE obj, ID id)
1272 {
1273     VALUE iv = rb_ivar_lookup(obj, id, Qundef);
1274     RB_DEBUG_COUNTER_INC(ivar_get_base);
1275 
1276     if (iv == Qundef) {
1277 	if (RTEST(ruby_verbose))
1278 	    rb_warning("instance variable %"PRIsVALUE" not initialized", QUOTE_ID(id));
1279 	iv = Qnil;
1280     }
1281     return iv;
1282 }
1283 
1284 VALUE
rb_attr_get(VALUE obj,ID id)1285 rb_attr_get(VALUE obj, ID id)
1286 {
1287     return rb_ivar_lookup(obj, id, Qnil);
1288 }
1289 
1290 static VALUE
rb_ivar_delete(VALUE obj,ID id,VALUE undef)1291 rb_ivar_delete(VALUE obj, ID id, VALUE undef)
1292 {
1293     VALUE val, *ptr;
1294     struct st_table *iv_index_tbl;
1295     uint32_t len;
1296     st_data_t index;
1297 
1298     rb_check_frozen(obj);
1299     switch (BUILTIN_TYPE(obj)) {
1300       case T_OBJECT:
1301         len = ROBJECT_NUMIV(obj);
1302         ptr = ROBJECT_IVPTR(obj);
1303         iv_index_tbl = ROBJECT_IV_INDEX_TBL(obj);
1304         if (!iv_index_tbl) break;
1305         if (!st_lookup(iv_index_tbl, (st_data_t)id, &index)) break;
1306         if (len <= index) break;
1307         val = ptr[index];
1308         ptr[index] = Qundef;
1309         if (val != Qundef)
1310             return val;
1311 	break;
1312       case T_CLASS:
1313       case T_MODULE:
1314 	if (RCLASS_IV_TBL(obj) &&
1315 		st_delete(RCLASS_IV_TBL(obj), (st_data_t *)&id, &index))
1316 	    return (VALUE)index;
1317 	break;
1318       default:
1319 	if (FL_TEST(obj, FL_EXIVAR))
1320 	    return generic_ivar_delete(obj, id, undef);
1321 	break;
1322     }
1323     return undef;
1324 }
1325 
1326 VALUE
rb_attr_delete(VALUE obj,ID id)1327 rb_attr_delete(VALUE obj, ID id)
1328 {
1329     return rb_ivar_delete(obj, id, Qnil);
1330 }
1331 
1332 static st_table *
iv_index_tbl_make(VALUE obj)1333 iv_index_tbl_make(VALUE obj)
1334 {
1335     VALUE klass = rb_obj_class(obj);
1336     st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(klass);
1337 
1338     if (!iv_index_tbl) {
1339 	iv_index_tbl = RCLASS_IV_INDEX_TBL(klass) = st_init_numtable();
1340     }
1341 
1342     return iv_index_tbl;
1343 }
1344 
1345 static void
iv_index_tbl_extend(struct ivar_update * ivup,ID id)1346 iv_index_tbl_extend(struct ivar_update *ivup, ID id)
1347 {
1348     if (st_lookup(ivup->u.iv_index_tbl, (st_data_t)id, &ivup->index)) {
1349 	return;
1350     }
1351     if (ivup->u.iv_index_tbl->num_entries >= INT_MAX) {
1352 	rb_raise(rb_eArgError, "too many instance variables");
1353     }
1354     ivup->index = (st_data_t)ivup->u.iv_index_tbl->num_entries;
1355     st_add_direct(ivup->u.iv_index_tbl, (st_data_t)id, ivup->index);
1356     ivup->iv_extended = 1;
1357 }
1358 
1359 static void
generic_ivar_set(VALUE obj,ID id,VALUE val)1360 generic_ivar_set(VALUE obj, ID id, VALUE val)
1361 {
1362     struct ivar_update ivup;
1363 
1364     ivup.iv_extended = 0;
1365     ivup.u.iv_index_tbl = iv_index_tbl_make(obj);
1366     iv_index_tbl_extend(&ivup, id);
1367     st_update(generic_iv_tbl, (st_data_t)obj, generic_ivar_update,
1368 	      (st_data_t)&ivup);
1369 
1370     ivup.u.ivtbl->ivptr[ivup.index] = val;
1371 
1372     RB_OBJ_WRITTEN(obj, Qundef, val);
1373 }
1374 
1375 static VALUE *
obj_ivar_heap_alloc(VALUE obj,size_t newsize)1376 obj_ivar_heap_alloc(VALUE obj, size_t newsize)
1377 {
1378     VALUE *newptr = rb_transient_heap_alloc(obj, sizeof(VALUE) * newsize);
1379 
1380     if (newptr != NULL) {
1381         ROBJ_TRANSIENT_SET(obj);
1382     }
1383     else {
1384         ROBJ_TRANSIENT_UNSET(obj);
1385         newptr = ALLOC_N(VALUE, newsize);
1386     }
1387     return newptr;
1388 }
1389 
1390 static VALUE *
obj_ivar_heap_realloc(VALUE obj,int32_t len,size_t newsize)1391 obj_ivar_heap_realloc(VALUE obj, int32_t len, size_t newsize)
1392 {
1393     VALUE *newptr;
1394     int i;
1395 
1396     if (ROBJ_TRANSIENT_P(obj)) {
1397         const VALUE *orig_ptr = ROBJECT(obj)->as.heap.ivptr;
1398         if ((newptr = obj_ivar_heap_alloc(obj, newsize)) != NULL) {
1399             /* ok */
1400         }
1401         else {
1402             newptr = ALLOC_N(VALUE, newsize);
1403             ROBJ_TRANSIENT_UNSET(obj);
1404         }
1405         ROBJECT(obj)->as.heap.ivptr = newptr;
1406         for (i=0; i<(int)len; i++) {
1407             newptr[i] = orig_ptr[i];
1408         }
1409     }
1410     else {
1411         REALLOC_N(ROBJECT(obj)->as.heap.ivptr, VALUE, newsize);
1412         newptr = ROBJECT(obj)->as.heap.ivptr;
1413     }
1414 
1415     return newptr;
1416 }
1417 
1418 #if USE_TRANSIENT_HEAP
1419 void
rb_obj_transient_heap_evacuate(VALUE obj,int promote)1420 rb_obj_transient_heap_evacuate(VALUE obj, int promote)
1421 {
1422     if (ROBJ_TRANSIENT_P(obj)) {
1423         uint32_t len = ROBJECT_NUMIV(obj);
1424         const VALUE *old_ptr = ROBJECT_IVPTR(obj);
1425         VALUE *new_ptr;
1426 
1427         if (promote) {
1428             new_ptr = ALLOC_N(VALUE, len);
1429             ROBJ_TRANSIENT_UNSET(obj);
1430         }
1431         else {
1432             new_ptr = obj_ivar_heap_alloc(obj, len);
1433         }
1434         MEMCPY(new_ptr, old_ptr, VALUE, len);
1435         ROBJECT(obj)->as.heap.ivptr = new_ptr;
1436     }
1437 }
1438 #endif
1439 
1440 static VALUE
obj_ivar_set(VALUE obj,ID id,VALUE val)1441 obj_ivar_set(VALUE obj, ID id, VALUE val)
1442 {
1443     struct ivar_update ivup;
1444     uint32_t i, len;
1445 
1446     ivup.iv_extended = 0;
1447     ivup.u.iv_index_tbl = iv_index_tbl_make(obj);
1448     iv_index_tbl_extend(&ivup, id);
1449     len = ROBJECT_NUMIV(obj);
1450     if (len <= ivup.index) {
1451         VALUE *ptr = ROBJECT_IVPTR(obj);
1452         if (ivup.index < ROBJECT_EMBED_LEN_MAX) {
1453             RBASIC(obj)->flags |= ROBJECT_EMBED;
1454             ptr = ROBJECT(obj)->as.ary;
1455             for (i = 0; i < ROBJECT_EMBED_LEN_MAX; i++) {
1456                 ptr[i] = Qundef;
1457             }
1458         }
1459         else {
1460             VALUE *newptr;
1461             uint32_t newsize = iv_index_tbl_newsize(&ivup);
1462 
1463             if (RBASIC(obj)->flags & ROBJECT_EMBED) {
1464                 newptr = obj_ivar_heap_alloc(obj, newsize);
1465                 MEMCPY(newptr, ptr, VALUE, len);
1466                 RBASIC(obj)->flags &= ~ROBJECT_EMBED;
1467                 ROBJECT(obj)->as.heap.ivptr = newptr;
1468             }
1469             else {
1470                 newptr = obj_ivar_heap_realloc(obj, len, newsize);
1471             }
1472             for (; len < newsize; len++) {
1473                 newptr[len] = Qundef;
1474             }
1475             ROBJECT(obj)->as.heap.numiv = newsize;
1476             ROBJECT(obj)->as.heap.iv_index_tbl = ivup.u.iv_index_tbl;
1477         }
1478     }
1479     RB_OBJ_WRITE(obj, &ROBJECT_IVPTR(obj)[ivup.index], val);
1480 
1481     return val;
1482 }
1483 
1484 VALUE
rb_ivar_set(VALUE obj,ID id,VALUE val)1485 rb_ivar_set(VALUE obj, ID id, VALUE val)
1486 {
1487     RB_DEBUG_COUNTER_INC(ivar_set_base);
1488 
1489     rb_check_frozen(obj);
1490 
1491     switch (BUILTIN_TYPE(obj)) {
1492       case T_OBJECT:
1493         return obj_ivar_set(obj, id, val);
1494       case T_CLASS:
1495       case T_MODULE:
1496         if (!RCLASS_IV_TBL(obj)) RCLASS_IV_TBL(obj) = st_init_numtable();
1497         rb_class_ivar_set(obj, id, val);
1498         break;
1499       default:
1500         generic_ivar_set(obj, id, val);
1501         break;
1502     }
1503     return val;
1504 }
1505 
1506 VALUE
rb_ivar_defined(VALUE obj,ID id)1507 rb_ivar_defined(VALUE obj, ID id)
1508 {
1509     VALUE val;
1510     struct st_table *iv_index_tbl;
1511     st_data_t index;
1512 
1513     if (SPECIAL_CONST_P(obj)) return Qfalse;
1514     switch (BUILTIN_TYPE(obj)) {
1515       case T_OBJECT:
1516         iv_index_tbl = ROBJECT_IV_INDEX_TBL(obj);
1517         if (!iv_index_tbl) break;
1518         if (!st_lookup(iv_index_tbl, (st_data_t)id, &index)) break;
1519         if (ROBJECT_NUMIV(obj) <= index) break;
1520         val = ROBJECT_IVPTR(obj)[index];
1521         if (val != Qundef)
1522             return Qtrue;
1523 	break;
1524       case T_CLASS:
1525       case T_MODULE:
1526 	if (RCLASS_IV_TBL(obj) && st_lookup(RCLASS_IV_TBL(obj), (st_data_t)id, 0))
1527 	    return Qtrue;
1528 	break;
1529       default:
1530 	if (FL_TEST(obj, FL_EXIVAR))
1531 	    return generic_ivar_defined(obj, id);
1532 	break;
1533     }
1534     return Qfalse;
1535 }
1536 
1537 struct obj_ivar_tag {
1538     VALUE obj;
1539     int (*func)(ID key, VALUE val, st_data_t arg);
1540     st_data_t arg;
1541 };
1542 
1543 static int
obj_ivar_i(st_data_t key,st_data_t index,st_data_t arg)1544 obj_ivar_i(st_data_t key, st_data_t index, st_data_t arg)
1545 {
1546     struct obj_ivar_tag *data = (struct obj_ivar_tag *)arg;
1547     if (index < ROBJECT_NUMIV(data->obj)) {
1548         VALUE val = ROBJECT_IVPTR(data->obj)[index];
1549         if (val != Qundef) {
1550             return (data->func)((ID)key, val, data->arg);
1551         }
1552     }
1553     return ST_CONTINUE;
1554 }
1555 
1556 static void
obj_ivar_each(VALUE obj,int (* func)(ANYARGS),st_data_t arg)1557 obj_ivar_each(VALUE obj, int (*func)(ANYARGS), st_data_t arg)
1558 {
1559     st_table *tbl;
1560     struct obj_ivar_tag data;
1561 
1562     tbl = ROBJECT_IV_INDEX_TBL(obj);
1563     if (!tbl)
1564         return;
1565 
1566     data.obj = obj;
1567     data.func = (int (*)(ID key, VALUE val, st_data_t arg))func;
1568     data.arg = arg;
1569 
1570     st_foreach_safe(tbl, obj_ivar_i, (st_data_t)&data);
1571 }
1572 
1573 struct gen_ivar_tag {
1574     struct gen_ivtbl *ivtbl;
1575     int (*func)(ID key, VALUE val, st_data_t arg);
1576     st_data_t arg;
1577 };
1578 
1579 static int
gen_ivar_each_i(st_data_t key,st_data_t index,st_data_t data)1580 gen_ivar_each_i(st_data_t key, st_data_t index, st_data_t data)
1581 {
1582     struct gen_ivar_tag *arg = (struct gen_ivar_tag *)data;
1583 
1584     if (index < arg->ivtbl->numiv) {
1585         VALUE val = arg->ivtbl->ivptr[index];
1586         if (val != Qundef) {
1587             return (arg->func)((ID)key, val, arg->arg);
1588         }
1589     }
1590     return ST_CONTINUE;
1591 }
1592 
1593 static void
gen_ivar_each(VALUE obj,int (* func)(ANYARGS),st_data_t arg)1594 gen_ivar_each(VALUE obj, int (*func)(ANYARGS), st_data_t arg)
1595 {
1596     struct gen_ivar_tag data;
1597     st_table *iv_index_tbl = RCLASS_IV_INDEX_TBL(rb_obj_class(obj));
1598 
1599     if (!iv_index_tbl) return;
1600     if (!gen_ivtbl_get(obj, &data.ivtbl)) return;
1601 
1602     data.func = (int (*)(ID key, VALUE val, st_data_t arg))func;
1603     data.arg = arg;
1604 
1605     st_foreach_safe(iv_index_tbl, gen_ivar_each_i, (st_data_t)&data);
1606 }
1607 
1608 struct givar_copy {
1609     VALUE obj;
1610     st_table *iv_index_tbl;
1611     struct gen_ivtbl *ivtbl;
1612 };
1613 
1614 static int
gen_ivar_copy(ID id,VALUE val,st_data_t arg)1615 gen_ivar_copy(ID id, VALUE val, st_data_t arg)
1616 {
1617     struct givar_copy *c = (struct givar_copy *)arg;
1618     struct ivar_update ivup;
1619 
1620     ivup.iv_extended = 0;
1621     ivup.u.iv_index_tbl = c->iv_index_tbl;
1622     iv_index_tbl_extend(&ivup, id);
1623     if (ivup.index >= c->ivtbl->numiv) {
1624 	uint32_t newsize = iv_index_tbl_newsize(&ivup);
1625 	c->ivtbl = gen_ivtbl_resize(c->ivtbl, newsize);
1626     }
1627     c->ivtbl->ivptr[ivup.index] = val;
1628 
1629     RB_OBJ_WRITTEN(c->obj, Qundef, val);
1630 
1631     return ST_CONTINUE;
1632 }
1633 
1634 void
rb_copy_generic_ivar(VALUE clone,VALUE obj)1635 rb_copy_generic_ivar(VALUE clone, VALUE obj)
1636 {
1637     struct gen_ivtbl *ivtbl;
1638 
1639     rb_check_frozen(clone);
1640 
1641     if (!FL_TEST(obj, FL_EXIVAR)) {
1642       clear:
1643         if (FL_TEST(clone, FL_EXIVAR)) {
1644             rb_free_generic_ivar(clone);
1645             FL_UNSET(clone, FL_EXIVAR);
1646         }
1647         return;
1648     }
1649     if (gen_ivtbl_get(obj, &ivtbl)) {
1650 	struct givar_copy c;
1651 	uint32_t i;
1652 
1653 	if (gen_ivtbl_count(ivtbl) == 0)
1654 	    goto clear;
1655 
1656 	if (gen_ivtbl_get(clone, &c.ivtbl)) {
1657 	    for (i = 0; i < c.ivtbl->numiv; i++)
1658 		c.ivtbl->ivptr[i] = Qundef;
1659 	}
1660 	else {
1661 	    c.ivtbl = gen_ivtbl_resize(0, ivtbl->numiv);
1662 	    FL_SET(clone, FL_EXIVAR);
1663 	}
1664 
1665 	c.iv_index_tbl = iv_index_tbl_make(clone);
1666 	c.obj = clone;
1667 	gen_ivar_each(obj, gen_ivar_copy, (st_data_t)&c);
1668 	/*
1669 	 * c.ivtbl may change in gen_ivar_copy due to realloc,
1670 	 * no need to free
1671 	 */
1672 	st_insert(generic_iv_tbl, (st_data_t)clone, (st_data_t)c.ivtbl);
1673     }
1674 }
1675 
1676 void
rb_ivar_foreach(VALUE obj,int (* func)(ANYARGS),st_data_t arg)1677 rb_ivar_foreach(VALUE obj, int (*func)(ANYARGS), st_data_t arg)
1678 {
1679     if (SPECIAL_CONST_P(obj)) return;
1680     switch (BUILTIN_TYPE(obj)) {
1681       case T_OBJECT:
1682         obj_ivar_each(obj, func, arg);
1683 	break;
1684       case T_CLASS:
1685       case T_MODULE:
1686 	if (RCLASS_IV_TBL(obj)) {
1687 	    st_foreach_safe(RCLASS_IV_TBL(obj), func, arg);
1688 	}
1689 	break;
1690       default:
1691 	if (FL_TEST(obj, FL_EXIVAR)) {
1692 	    gen_ivar_each(obj, func, arg);
1693 	}
1694 	break;
1695     }
1696 }
1697 
1698 st_index_t
rb_ivar_count(VALUE obj)1699 rb_ivar_count(VALUE obj)
1700 {
1701     st_table *tbl;
1702 
1703     if (SPECIAL_CONST_P(obj)) return 0;
1704 
1705     switch (BUILTIN_TYPE(obj)) {
1706       case T_OBJECT:
1707 	if ((tbl = ROBJECT_IV_INDEX_TBL(obj)) != 0) {
1708 	    st_index_t i, count, num = ROBJECT_NUMIV(obj);
1709 	    const VALUE *const ivptr = ROBJECT_IVPTR(obj);
1710 	    for (i = count = 0; i < num; ++i) {
1711 		if (ivptr[i] != Qundef) {
1712 		    count++;
1713 		}
1714 	    }
1715 	    return count;
1716 	}
1717 	break;
1718       case T_CLASS:
1719       case T_MODULE:
1720 	if ((tbl = RCLASS_IV_TBL(obj)) != 0) {
1721 	    return tbl->num_entries;
1722 	}
1723 	break;
1724       default:
1725 	if (FL_TEST(obj, FL_EXIVAR)) {
1726 	    struct gen_ivtbl *ivtbl;
1727 
1728 	    if (gen_ivtbl_get(obj, &ivtbl)) {
1729 		return gen_ivtbl_count(ivtbl);
1730 	    }
1731 	}
1732 	break;
1733     }
1734     return 0;
1735 }
1736 
1737 static int
ivar_i(st_data_t k,st_data_t v,st_data_t a)1738 ivar_i(st_data_t k, st_data_t v, st_data_t a)
1739 {
1740     ID key = (ID)k;
1741     VALUE ary = (VALUE)a;
1742 
1743     if (rb_is_instance_id(key)) {
1744 	rb_ary_push(ary, ID2SYM(key));
1745     }
1746     return ST_CONTINUE;
1747 }
1748 
1749 /*
1750  *  call-seq:
1751  *     obj.instance_variables    -> array
1752  *
1753  *  Returns an array of instance variable names for the receiver. Note
1754  *  that simply defining an accessor does not create the corresponding
1755  *  instance variable.
1756  *
1757  *     class Fred
1758  *       attr_accessor :a1
1759  *       def initialize
1760  *         @iv = 3
1761  *       end
1762  *     end
1763  *     Fred.new.instance_variables   #=> [:@iv]
1764  */
1765 
1766 VALUE
rb_obj_instance_variables(VALUE obj)1767 rb_obj_instance_variables(VALUE obj)
1768 {
1769     VALUE ary;
1770 
1771     ary = rb_ary_new();
1772     rb_ivar_foreach(obj, ivar_i, ary);
1773     return ary;
1774 }
1775 
1776 #define rb_is_constant_id rb_is_const_id
1777 #define rb_is_constant_name rb_is_const_name
1778 #define id_for_var(obj, name, part, type) \
1779     id_for_var_message(obj, name, type, "`%1$s' is not allowed as "#part" "#type" variable name")
1780 #define id_for_var_message(obj, name, type, message) \
1781     check_id_type(obj, &(name), rb_is_##type##_id, rb_is_##type##_name, message, strlen(message))
1782 static ID
check_id_type(VALUE obj,VALUE * pname,int (* valid_id_p)(ID),int (* valid_name_p)(VALUE),const char * message,size_t message_len)1783 check_id_type(VALUE obj, VALUE *pname,
1784 	      int (*valid_id_p)(ID), int (*valid_name_p)(VALUE),
1785 	      const char *message, size_t message_len)
1786 {
1787     ID id = rb_check_id(pname);
1788     VALUE name = *pname;
1789 
1790     if (id ? !valid_id_p(id) : !valid_name_p(name)) {
1791 	rb_name_err_raise_str(rb_fstring_new(message, message_len),
1792 			      obj, name);
1793     }
1794     return id;
1795 }
1796 
1797 /*
1798  *  call-seq:
1799  *     obj.remove_instance_variable(symbol)    -> obj
1800  *     obj.remove_instance_variable(string)    -> obj
1801  *
1802  *  Removes the named instance variable from <i>obj</i>, returning that
1803  *  variable's value.
1804  *  String arguments are converted to symbols.
1805  *
1806  *     class Dummy
1807  *       attr_reader :var
1808  *       def initialize
1809  *         @var = 99
1810  *       end
1811  *       def remove
1812  *         remove_instance_variable(:@var)
1813  *       end
1814  *     end
1815  *     d = Dummy.new
1816  *     d.var      #=> 99
1817  *     d.remove   #=> 99
1818  *     d.var      #=> nil
1819  */
1820 
1821 VALUE
rb_obj_remove_instance_variable(VALUE obj,VALUE name)1822 rb_obj_remove_instance_variable(VALUE obj, VALUE name)
1823 {
1824     VALUE val = Qnil;
1825     const ID id = id_for_var(obj, name, an, instance);
1826     st_data_t n, v;
1827     struct st_table *iv_index_tbl;
1828     st_data_t index;
1829 
1830     rb_check_frozen(obj);
1831     if (!id) {
1832 	goto not_defined;
1833     }
1834 
1835     switch (BUILTIN_TYPE(obj)) {
1836       case T_OBJECT:
1837         iv_index_tbl = ROBJECT_IV_INDEX_TBL(obj);
1838         if (!iv_index_tbl) break;
1839         if (!st_lookup(iv_index_tbl, (st_data_t)id, &index)) break;
1840         if (ROBJECT_NUMIV(obj) <= index) break;
1841         val = ROBJECT_IVPTR(obj)[index];
1842         if (val != Qundef) {
1843             ROBJECT_IVPTR(obj)[index] = Qundef;
1844             return val;
1845         }
1846 	break;
1847       case T_CLASS:
1848       case T_MODULE:
1849 	n = id;
1850 	if (RCLASS_IV_TBL(obj) && st_delete(RCLASS_IV_TBL(obj), &n, &v)) {
1851 	    return (VALUE)v;
1852 	}
1853 	break;
1854       default:
1855 	if (FL_TEST(obj, FL_EXIVAR)) {
1856 	    if (generic_ivar_remove(obj, id, &val)) {
1857 		return val;
1858 	    }
1859 	}
1860 	break;
1861     }
1862 
1863   not_defined:
1864     rb_name_err_raise("instance variable %1$s not defined",
1865 		      obj, name);
1866     UNREACHABLE_RETURN(Qnil);
1867 }
1868 
1869 NORETURN(static void uninitialized_constant(VALUE, VALUE));
1870 static void
uninitialized_constant(VALUE klass,VALUE name)1871 uninitialized_constant(VALUE klass, VALUE name)
1872 {
1873     if (klass && rb_class_real(klass) != rb_cObject)
1874 	rb_name_err_raise("uninitialized constant %2$s::%1$s",
1875 			  klass, name);
1876     else
1877 	rb_name_err_raise("uninitialized constant %1$s",
1878 			  klass, name);
1879 }
1880 
1881 VALUE
rb_const_missing(VALUE klass,VALUE name)1882 rb_const_missing(VALUE klass, VALUE name)
1883 {
1884     VALUE value = rb_funcallv(klass, idConst_missing, 1, &name);
1885     rb_vm_inc_const_missing_count();
1886     return value;
1887 }
1888 
1889 
1890 /*
1891  * call-seq:
1892  *    mod.const_missing(sym)    -> obj
1893  *
1894  * Invoked when a reference is made to an undefined constant in
1895  * <i>mod</i>. It is passed a symbol for the undefined constant, and
1896  * returns a value to be used for that constant. The
1897  * following code is an example of the same:
1898  *
1899  *   def Foo.const_missing(name)
1900  *     name # return the constant name as Symbol
1901  *   end
1902  *
1903  *   Foo::UNDEFINED_CONST    #=> :UNDEFINED_CONST: symbol returned
1904  *
1905  * In the next example when a reference is made to an undefined constant,
1906  * it attempts to load a file whose name is the lowercase version of the
1907  * constant (thus class <code>Fred</code> is assumed to be in file
1908  * <code>fred.rb</code>).  If found, it returns the loaded class. It
1909  * therefore implements an autoload feature similar to Kernel#autoload and
1910  * Module#autoload.
1911  *
1912  *   def Object.const_missing(name)
1913  *     @looked_for ||= {}
1914  *     str_name = name.to_s
1915  *     raise "Class not found: #{name}" if @looked_for[str_name]
1916  *     @looked_for[str_name] = 1
1917  *     file = str_name.downcase
1918  *     require file
1919  *     klass = const_get(name)
1920  *     return klass if klass
1921  *     raise "Class not found: #{name}"
1922  *   end
1923  *
1924  */
1925 
1926 VALUE
rb_mod_const_missing(VALUE klass,VALUE name)1927 rb_mod_const_missing(VALUE klass, VALUE name)
1928 {
1929     VALUE ref = GET_EC()->private_const_reference;
1930     rb_vm_pop_cfunc_frame();
1931     if (ref) {
1932 	rb_name_err_raise("private constant %2$s::%1$s referenced",
1933 			  ref, name);
1934     }
1935     uninitialized_constant(klass, name);
1936 
1937     UNREACHABLE_RETURN(Qnil);
1938 }
1939 
1940 static void
autoload_mark(void * ptr)1941 autoload_mark(void *ptr)
1942 {
1943     rb_mark_tbl((st_table *)ptr);
1944 }
1945 
1946 static void
autoload_free(void * ptr)1947 autoload_free(void *ptr)
1948 {
1949     st_free_table((st_table *)ptr);
1950 }
1951 
1952 static size_t
autoload_memsize(const void * ptr)1953 autoload_memsize(const void *ptr)
1954 {
1955     const st_table *tbl = ptr;
1956     return st_memsize(tbl);
1957 }
1958 
1959 static const rb_data_type_t autoload_data_type = {
1960     "autoload",
1961     {autoload_mark, autoload_free, autoload_memsize,},
1962     0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1963 };
1964 
1965 #define check_autoload_table(av) \
1966     (struct st_table *)rb_check_typeddata((av), &autoload_data_type)
1967 
1968 static VALUE
autoload_data(VALUE mod,ID id)1969 autoload_data(VALUE mod, ID id)
1970 {
1971     struct st_table *tbl;
1972     st_data_t val;
1973 
1974     if (!st_lookup(RCLASS_IV_TBL(mod), autoload, &val) ||
1975 	    !(tbl = check_autoload_table((VALUE)val)) ||
1976 	    !st_lookup(tbl, (st_data_t)id, &val)) {
1977 	return 0;
1978     }
1979     return (VALUE)val;
1980 }
1981 
1982 struct autoload_const {
1983     struct list_node cnode; /* <=> autoload_data_i.constants */
1984     VALUE mod;
1985     VALUE ad; /* autoload_data_i */
1986     VALUE value;
1987     VALUE file;
1988     ID id;
1989     int safe_level;
1990     rb_const_flag_t flag;
1991     int line;
1992 };
1993 
1994 /* always on stack, no need to mark */
1995 struct autoload_state {
1996     struct autoload_const *ac;
1997     VALUE result;
1998     VALUE thread;
1999     struct list_node waitq;
2000 };
2001 
2002 struct autoload_data_i {
2003     VALUE feature;
2004     struct autoload_state *state; /* points to on-stack struct */
2005     rb_serial_t fork_gen;
2006     struct list_head constants; /* <=> autoload_const.cnode */
2007 };
2008 
2009 static void
autoload_i_mark(void * ptr)2010 autoload_i_mark(void *ptr)
2011 {
2012     struct autoload_data_i *p = ptr;
2013 
2014     rb_gc_mark(p->feature);
2015 
2016     /* allow GC to free us if no modules refer to this via autoload_const.ad */
2017     if (list_empty(&p->constants)) {
2018         rb_hash_delete(autoload_featuremap, p->feature);
2019     }
2020 }
2021 
2022 static void
autoload_i_free(void * ptr)2023 autoload_i_free(void *ptr)
2024 {
2025     struct autoload_data_i *p = ptr;
2026 
2027     /* we may leak some memory at VM shutdown time, no big deal */
2028     if (list_empty(&p->constants)) {
2029 	xfree(p);
2030     }
2031 }
2032 
2033 static size_t
autoload_i_memsize(const void * ptr)2034 autoload_i_memsize(const void *ptr)
2035 {
2036     return sizeof(struct autoload_data_i);
2037 }
2038 
2039 static const rb_data_type_t autoload_data_i_type = {
2040     "autoload_i",
2041     {autoload_i_mark, autoload_i_free, autoload_i_memsize,},
2042     0, 0, RUBY_TYPED_FREE_IMMEDIATELY
2043 };
2044 
2045 static void
autoload_c_mark(void * ptr)2046 autoload_c_mark(void *ptr)
2047 {
2048     struct autoload_const *ac = ptr;
2049 
2050     rb_gc_mark(ac->mod);
2051     rb_gc_mark(ac->ad);
2052     rb_gc_mark(ac->value);
2053     rb_gc_mark(ac->file);
2054 }
2055 
2056 static void
autoload_c_free(void * ptr)2057 autoload_c_free(void *ptr)
2058 {
2059     struct autoload_const *ac = ptr;
2060     list_del(&ac->cnode);
2061     xfree(ac);
2062 }
2063 
2064 static size_t
autoload_c_memsize(const void * ptr)2065 autoload_c_memsize(const void *ptr)
2066 {
2067     return sizeof(struct autoload_const);
2068 }
2069 
2070 static const rb_data_type_t autoload_const_type = {
2071     "autoload_const",
2072     {autoload_c_mark, autoload_c_free, autoload_c_memsize,},
2073     0, 0, RUBY_TYPED_FREE_IMMEDIATELY
2074 };
2075 
2076 static struct autoload_data_i *
get_autoload_data(VALUE acv,struct autoload_const ** acp)2077 get_autoload_data(VALUE acv, struct autoload_const **acp)
2078 {
2079     struct autoload_const *ac = rb_check_typeddata(acv, &autoload_const_type);
2080     struct autoload_data_i *ele;
2081 
2082     ele = rb_check_typeddata(ac->ad, &autoload_data_i_type);
2083     /* do not reach across stack for ->state after forking: */
2084     if (ele && ele->state && ele->fork_gen != GET_VM()->fork_gen) {
2085         ele->state = 0;
2086         ele->fork_gen = 0;
2087     }
2088     if (acp) *acp = ac;
2089     return ele;
2090 }
2091 
2092 RUBY_FUNC_EXPORTED void
rb_autoload(VALUE mod,ID id,const char * file)2093 rb_autoload(VALUE mod, ID id, const char *file)
2094 {
2095     if (!file || !*file) {
2096 	rb_raise(rb_eArgError, "empty file name");
2097     }
2098     rb_autoload_str(mod, id, rb_fstring_cstr(file));
2099 }
2100 
2101 void
rb_autoload_str(VALUE mod,ID id,VALUE file)2102 rb_autoload_str(VALUE mod, ID id, VALUE file)
2103 {
2104     st_data_t av;
2105     VALUE ad;
2106     struct st_table *tbl;
2107     struct autoload_data_i *ele;
2108     rb_const_entry_t *ce;
2109 
2110     if (!rb_is_const_id(id)) {
2111 	rb_raise(rb_eNameError, "autoload must be constant name: %"PRIsVALUE"",
2112 		 QUOTE_ID(id));
2113     }
2114 
2115     Check_Type(file, T_STRING);
2116     if (!RSTRING_LEN(file)) {
2117 	rb_raise(rb_eArgError, "empty file name");
2118     }
2119 
2120     ce = rb_const_lookup(mod, id);
2121     if (ce && ce->value != Qundef) {
2122 	return;
2123     }
2124 
2125     rb_const_set(mod, id, Qundef);
2126     tbl = RCLASS_IV_TBL(mod);
2127     if (tbl && st_lookup(tbl, (st_data_t)autoload, &av)) {
2128 	tbl = check_autoload_table((VALUE)av);
2129     }
2130     else {
2131 	if (!tbl) tbl = RCLASS_IV_TBL(mod) = st_init_numtable();
2132 	av = (st_data_t)TypedData_Wrap_Struct(0, &autoload_data_type, 0);
2133 	st_add_direct(tbl, (st_data_t)autoload, av);
2134 	RB_OBJ_WRITTEN(mod, Qnil, av);
2135 	DATA_PTR(av) = tbl = st_init_numtable();
2136     }
2137 
2138     if (OBJ_TAINTED(file)) {
2139 	file = rb_str_dup(file);
2140 	FL_UNSET(file, FL_TAINT);
2141     }
2142     file = rb_fstring(file);
2143     if (!autoload_featuremap) {
2144         autoload_featuremap = rb_hash_new_compare_by_id();
2145         rb_obj_hide(autoload_featuremap);
2146         rb_gc_register_mark_object(autoload_featuremap);
2147     }
2148     ad = rb_hash_aref(autoload_featuremap, file);
2149     if (NIL_P(ad)) {
2150         ad = TypedData_Make_Struct(0, struct autoload_data_i,
2151                                     &autoload_data_i_type, ele);
2152         ele->feature = file;
2153         ele->state = 0;
2154         list_head_init(&ele->constants);
2155         rb_hash_aset(autoload_featuremap, file, ad);
2156     }
2157     else {
2158         ele = rb_check_typeddata(ad, &autoload_data_i_type);
2159     }
2160     {
2161         VALUE acv;
2162         struct autoload_const *ac;
2163         acv = TypedData_Make_Struct(0, struct autoload_const,
2164                                     &autoload_const_type, ac);
2165         ac->mod = mod;
2166         ac->id = id;
2167         ac->value = Qundef;
2168         ac->safe_level = rb_safe_level();
2169         ac->flag = CONST_PUBLIC;
2170         ac->ad = ad;
2171         list_add_tail(&ele->constants, &ac->cnode);
2172         st_insert(tbl, (st_data_t)id, (st_data_t)acv);
2173     }
2174 }
2175 
2176 static void
autoload_delete(VALUE mod,ID id)2177 autoload_delete(VALUE mod, ID id)
2178 {
2179     st_data_t val, load = 0, n = id;
2180 
2181     if (st_lookup(RCLASS_IV_TBL(mod), (st_data_t)autoload, &val)) {
2182 	struct st_table *tbl = check_autoload_table((VALUE)val);
2183 	struct autoload_data_i *ele;
2184 	struct autoload_const *ac;
2185 
2186 	st_delete(tbl, &n, &load);
2187 	ele = get_autoload_data((VALUE)load, &ac);
2188 	VM_ASSERT(ele);
2189 	if (ele) {
2190 	    VM_ASSERT(!list_empty(&ele->constants));
2191 	}
2192 
2193 	/*
2194 	 * we must delete here to avoid "already initialized" warnings
2195 	 * with parallel autoload.  Using list_del_init here so list_del
2196 	 * works in autoload_c_free
2197 	 */
2198 	list_del_init(&ac->cnode);
2199 
2200 	if (tbl->num_entries == 0) {
2201 	    n = autoload;
2202 	    st_delete(RCLASS_IV_TBL(mod), &n, &val);
2203 	}
2204     }
2205 }
2206 
2207 static VALUE
autoload_provided(VALUE arg)2208 autoload_provided(VALUE arg)
2209 {
2210     const char **p = (const char **)arg;
2211     return rb_feature_provided(*p, p);
2212 }
2213 
2214 static VALUE
reset_safe(VALUE safe)2215 reset_safe(VALUE safe)
2216 {
2217     rb_set_safe_level_force((int)safe);
2218     return safe;
2219 }
2220 
2221 static VALUE
check_autoload_required(VALUE mod,ID id,const char ** loadingpath)2222 check_autoload_required(VALUE mod, ID id, const char **loadingpath)
2223 {
2224     VALUE file;
2225     VALUE load = autoload_data(mod, id);
2226     struct autoload_data_i *ele;
2227     const char *loading;
2228     int safe;
2229 
2230     if (!load || !(ele = get_autoload_data(load, 0))) {
2231 	return 0;
2232     }
2233     file = ele->feature;
2234     Check_Type(file, T_STRING);
2235     if (!RSTRING_LEN(file) || !*RSTRING_PTR(file)) {
2236 	rb_raise(rb_eArgError, "empty file name");
2237     }
2238 
2239     /*
2240      * if somebody else is autoloading, we MUST wait for them, since
2241      * rb_provide_feature can provide a feature before autoload_const_set
2242      * completes.  We must wait until autoload_const_set finishes in
2243      * the other thread.
2244      */
2245     if (ele->state && ele->state->thread != rb_thread_current()) {
2246 	return load;
2247     }
2248 
2249     loading = RSTRING_PTR(file);
2250     safe = rb_safe_level();
2251     rb_set_safe_level_force(0);
2252     if (!rb_ensure(autoload_provided, (VALUE)&loading, reset_safe, (VALUE)safe)) {
2253 	return load;
2254     }
2255     if (loadingpath && loading) {
2256 	*loadingpath = loading;
2257 	return load;
2258     }
2259     return 0;
2260 }
2261 
2262 MJIT_FUNC_EXPORTED int
rb_autoloading_value(VALUE mod,ID id,VALUE * value,rb_const_flag_t * flag)2263 rb_autoloading_value(VALUE mod, ID id, VALUE* value, rb_const_flag_t *flag)
2264 {
2265     VALUE load = autoload_data(mod, id);
2266     struct autoload_data_i *ele;
2267     struct autoload_const *ac;
2268 
2269     if (!load || !(ele = get_autoload_data(load, &ac))) {
2270         return 0;
2271     }
2272 
2273     if (ele->state && ele->state->thread == rb_thread_current()) {
2274 	if (ac->value != Qundef) {
2275 	    if (value) {
2276 		*value = ac->value;
2277 	    }
2278 	    if (flag) {
2279 		*flag = ac->flag;
2280 	    }
2281 	    return 1;
2282 	}
2283     }
2284     return 0;
2285 }
2286 
2287 static int
autoload_defined_p(VALUE mod,ID id)2288 autoload_defined_p(VALUE mod, ID id)
2289 {
2290     rb_const_entry_t *ce = rb_const_lookup(mod, id);
2291 
2292     if (!ce || ce->value != Qundef) {
2293 	return 0;
2294     }
2295     return !rb_autoloading_value(mod, id, NULL, NULL);
2296 }
2297 
2298 static void const_tbl_update(struct autoload_const *);
2299 
2300 static VALUE
autoload_const_set(VALUE arg)2301 autoload_const_set(VALUE arg)
2302 {
2303     struct autoload_const *ac = (struct autoload_const *)arg;
2304     VALUE klass = ac->mod;
2305     ID id = ac->id;
2306     check_before_mod_set(klass, id, ac->value, "constant");
2307     const_tbl_update(ac);
2308     return 0;			/* ignored */
2309 }
2310 
2311 static VALUE
autoload_require(VALUE arg)2312 autoload_require(VALUE arg)
2313 {
2314     struct autoload_state *state = (struct autoload_state *)arg;
2315     struct autoload_const *ac = state->ac;
2316     struct autoload_data_i *ele;
2317 
2318     ele = rb_check_typeddata(ac->ad, &autoload_data_i_type);
2319     /* this may release GVL and switch threads: */
2320     state->result = rb_funcall(rb_vm_top_self(), rb_intern("require"), 1,
2321 			       ele->feature);
2322 
2323     return state->result;
2324 }
2325 
2326 static VALUE
autoload_reset(VALUE arg)2327 autoload_reset(VALUE arg)
2328 {
2329     struct autoload_state *state = (struct autoload_state *)arg;
2330     int need_wakeups = 0;
2331     struct autoload_const *ac = state->ac;
2332     struct autoload_data_i *ele;
2333 
2334     ele = rb_check_typeddata(ac->ad, &autoload_data_i_type);
2335     if (ele->state == state) {
2336         need_wakeups = 1;
2337         ele->state = 0;
2338         ele->fork_gen = 0;
2339     }
2340 
2341     /* At the last, move a value defined in autoload to constant table */
2342     if (RTEST(state->result)) {
2343         struct autoload_const *next;
2344         int safe_backup = rb_safe_level();
2345 
2346         list_for_each_safe(&ele->constants, ac, next, cnode) {
2347             if (ac->value != Qundef) {
2348                 rb_ensure(autoload_const_set, (VALUE)ac,
2349                           reset_safe, (VALUE)safe_backup);
2350             }
2351         }
2352     }
2353 
2354     /* wakeup any waiters we had */
2355     if (need_wakeups) {
2356 	struct autoload_state *cur = 0, *nxt;
2357 
2358 	list_for_each_safe((struct list_head *)&state->waitq, cur, nxt, waitq) {
2359 	    VALUE th = cur->thread;
2360 
2361 	    cur->thread = Qfalse;
2362 	    list_del_init(&cur->waitq); /* idempotent */
2363 
2364 	    /*
2365 	     * cur is stored on the stack of cur->waiting_th,
2366 	     * do not touch cur after waking up waiting_th
2367 	     */
2368 	    rb_thread_wakeup_alive(th);
2369 	}
2370     }
2371 
2372     return 0;			/* ignored */
2373 }
2374 
2375 static VALUE
autoload_sleep(VALUE arg)2376 autoload_sleep(VALUE arg)
2377 {
2378     struct autoload_state *state = (struct autoload_state *)arg;
2379 
2380     /*
2381      * autoload_reset in other thread will resume us and remove us
2382      * from the waitq list
2383      */
2384     do {
2385 	rb_thread_sleep_deadly();
2386     } while (state->thread != Qfalse);
2387 
2388     return Qfalse;
2389 }
2390 
2391 static VALUE
autoload_sleep_done(VALUE arg)2392 autoload_sleep_done(VALUE arg)
2393 {
2394     struct autoload_state *state = (struct autoload_state *)arg;
2395 
2396     if (state->thread != Qfalse && rb_thread_to_be_killed(state->thread)) {
2397 	list_del(&state->waitq); /* idempotent after list_del_init */
2398     }
2399 
2400     return Qfalse;
2401 }
2402 
2403 VALUE
rb_autoload_load(VALUE mod,ID id)2404 rb_autoload_load(VALUE mod, ID id)
2405 {
2406     VALUE load, result;
2407     const char *loading = 0, *src;
2408     struct autoload_data_i *ele;
2409     struct autoload_const *ac;
2410     struct autoload_state state;
2411 
2412     if (!autoload_defined_p(mod, id)) return Qfalse;
2413     load = check_autoload_required(mod, id, &loading);
2414     if (!load) return Qfalse;
2415     src = rb_sourcefile();
2416     if (src && loading && strcmp(src, loading) == 0) return Qfalse;
2417 
2418     /* set ele->state for a marker of autoloading thread */
2419     if (!(ele = get_autoload_data(load, &ac))) {
2420 	return Qfalse;
2421     }
2422     state.ac = ac;
2423     state.thread = rb_thread_current();
2424     if (!ele->state) {
2425 	ele->state = &state;
2426 	ele->fork_gen = GET_VM()->fork_gen;
2427 
2428 	/*
2429 	 * autoload_reset will wake up any threads added to this
2430 	 * iff the GVL is released during autoload_require
2431 	 */
2432 	list_head_init((struct list_head *)&state.waitq);
2433     }
2434     else if (state.thread == ele->state->thread) {
2435 	return Qfalse;
2436     }
2437     else {
2438 	list_add_tail((struct list_head *)&ele->state->waitq, &state.waitq);
2439 
2440 	rb_ensure(autoload_sleep, (VALUE)&state,
2441 		autoload_sleep_done, (VALUE)&state);
2442     }
2443 
2444     /* autoload_data_i can be deleted by another thread while require */
2445     result = rb_ensure(autoload_require, (VALUE)&state,
2446 		       autoload_reset, (VALUE)&state);
2447 
2448     RB_GC_GUARD(load);
2449     return result;
2450 }
2451 
2452 VALUE
rb_autoload_p(VALUE mod,ID id)2453 rb_autoload_p(VALUE mod, ID id)
2454 {
2455     VALUE load;
2456     struct autoload_data_i *ele;
2457 
2458     while (!autoload_defined_p(mod, id)) {
2459 	mod = RCLASS_SUPER(mod);
2460 	if (!mod) return Qnil;
2461     }
2462     load = check_autoload_required(mod, id, 0);
2463     if (!load) return Qnil;
2464     return (ele = get_autoload_data(load, 0)) ? ele->feature : Qnil;
2465 }
2466 
2467 MJIT_FUNC_EXPORTED void
rb_const_warn_if_deprecated(const rb_const_entry_t * ce,VALUE klass,ID id)2468 rb_const_warn_if_deprecated(const rb_const_entry_t *ce, VALUE klass, ID id)
2469 {
2470     if (RB_CONST_DEPRECATED_P(ce)) {
2471 	if (klass == rb_cObject) {
2472 	    rb_warn("constant ::%"PRIsVALUE" is deprecated", QUOTE_ID(id));
2473 	}
2474 	else {
2475 	    rb_warn("constant %"PRIsVALUE"::%"PRIsVALUE" is deprecated",
2476 		    rb_class_name(klass), QUOTE_ID(id));
2477 	}
2478     }
2479 }
2480 
2481 static VALUE
rb_const_get_0(VALUE klass,ID id,int exclude,int recurse,int visibility)2482 rb_const_get_0(VALUE klass, ID id, int exclude, int recurse, int visibility)
2483 {
2484     VALUE c = rb_const_search(klass, id, exclude, recurse, visibility);
2485     if (c != Qundef) return c;
2486     return rb_const_missing(klass, ID2SYM(id));
2487 }
2488 
2489 static VALUE
rb_const_search(VALUE klass,ID id,int exclude,int recurse,int visibility)2490 rb_const_search(VALUE klass, ID id, int exclude, int recurse, int visibility)
2491 {
2492     VALUE value, tmp, av;
2493     rb_const_flag_t flag;
2494     int mod_retry = 0;
2495 
2496     tmp = klass;
2497   retry:
2498     while (RTEST(tmp)) {
2499 	VALUE am = 0;
2500 	rb_const_entry_t *ce;
2501 
2502 	while ((ce = rb_const_lookup(tmp, id))) {
2503 	    if (visibility && RB_CONST_PRIVATE_P(ce)) {
2504 		if (BUILTIN_TYPE(tmp) == T_ICLASS) tmp = RBASIC(tmp)->klass;
2505 		GET_EC()->private_const_reference = tmp;
2506 		return Qundef;
2507 	    }
2508 	    rb_const_warn_if_deprecated(ce, tmp, id);
2509 	    value = ce->value;
2510 	    if (value == Qundef) {
2511 		if (am == tmp) break;
2512 		am = tmp;
2513 		if (rb_autoloading_value(tmp, id, &av, &flag)) return av;
2514 		rb_autoload_load(tmp, id);
2515 		continue;
2516 	    }
2517 	    if (exclude && tmp == rb_cObject && klass != rb_cObject) {
2518 		goto not_found;
2519 	    }
2520 	    return value;
2521 	}
2522 	if (!recurse) break;
2523 	tmp = RCLASS_SUPER(tmp);
2524     }
2525     if (!exclude && !mod_retry && BUILTIN_TYPE(klass) == T_MODULE) {
2526 	mod_retry = 1;
2527 	tmp = rb_cObject;
2528 	goto retry;
2529     }
2530 
2531   not_found:
2532     GET_EC()->private_const_reference = 0;
2533     return Qundef;
2534 }
2535 
2536 VALUE
rb_const_get_from(VALUE klass,ID id)2537 rb_const_get_from(VALUE klass, ID id)
2538 {
2539     return rb_const_get_0(klass, id, TRUE, TRUE, FALSE);
2540 }
2541 
2542 VALUE
rb_const_get(VALUE klass,ID id)2543 rb_const_get(VALUE klass, ID id)
2544 {
2545     return rb_const_get_0(klass, id, FALSE, TRUE, FALSE);
2546 }
2547 
2548 VALUE
rb_const_get_at(VALUE klass,ID id)2549 rb_const_get_at(VALUE klass, ID id)
2550 {
2551     return rb_const_get_0(klass, id, TRUE, FALSE, FALSE);
2552 }
2553 
2554 MJIT_FUNC_EXPORTED VALUE
rb_public_const_get_from(VALUE klass,ID id)2555 rb_public_const_get_from(VALUE klass, ID id)
2556 {
2557     return rb_const_get_0(klass, id, TRUE, TRUE, TRUE);
2558 }
2559 
2560 VALUE
rb_public_const_get(VALUE klass,ID id)2561 rb_public_const_get(VALUE klass, ID id)
2562 {
2563     return rb_const_get_0(klass, id, FALSE, TRUE, TRUE);
2564 }
2565 
2566 MJIT_FUNC_EXPORTED VALUE
rb_public_const_get_at(VALUE klass,ID id)2567 rb_public_const_get_at(VALUE klass, ID id)
2568 {
2569     return rb_const_get_0(klass, id, TRUE, FALSE, TRUE);
2570 }
2571 
2572 /*
2573  *  call-seq:
2574  *     remove_const(sym)   -> obj
2575  *
2576  *  Removes the definition of the given constant, returning that
2577  *  constant's previous value.  If that constant referred to
2578  *  a module, this will not change that module's name and can lead
2579  *  to confusion.
2580  */
2581 
2582 VALUE
rb_mod_remove_const(VALUE mod,VALUE name)2583 rb_mod_remove_const(VALUE mod, VALUE name)
2584 {
2585     const ID id = id_for_var(mod, name, a, constant);
2586 
2587     if (!id) {
2588 	rb_name_err_raise("constant %2$s::%1$s not defined",
2589 			  mod, name);
2590     }
2591     return rb_const_remove(mod, id);
2592 }
2593 
2594 VALUE
rb_const_remove(VALUE mod,ID id)2595 rb_const_remove(VALUE mod, ID id)
2596 {
2597     VALUE val;
2598     rb_const_entry_t *ce;
2599 
2600     rb_check_frozen(mod);
2601     ce = rb_const_lookup(mod, id);
2602     if (!ce || !rb_id_table_delete(RCLASS_CONST_TBL(mod), id)) {
2603 	if (rb_const_defined_at(mod, id)) {
2604 	    rb_name_err_raise("cannot remove %2$s::%1$s",
2605 			      mod, ID2SYM(id));
2606 	}
2607 	rb_name_err_raise("constant %2$s::%1$s not defined",
2608 			  mod, ID2SYM(id));
2609     }
2610 
2611     rb_clear_constant_cache();
2612 
2613     val = ce->value;
2614     if (val == Qundef) {
2615 	autoload_delete(mod, id);
2616 	val = Qnil;
2617     }
2618     xfree(ce);
2619     return val;
2620 }
2621 
2622 static int
cv_i_update(st_data_t * k,st_data_t * v,st_data_t a,int existing)2623 cv_i_update(st_data_t *k, st_data_t *v, st_data_t a, int existing)
2624 {
2625     if (existing) return ST_STOP;
2626     *v = a;
2627     return ST_CONTINUE;
2628 }
2629 
2630 static enum rb_id_table_iterator_result
sv_i(ID key,VALUE v,void * a)2631 sv_i(ID key, VALUE v, void *a)
2632 {
2633     rb_const_entry_t *ce = (rb_const_entry_t *)v;
2634     st_table *tbl = a;
2635 
2636     if (rb_is_const_id(key)) {
2637 	st_update(tbl, (st_data_t)key, cv_i_update, (st_data_t)ce);
2638     }
2639     return ID_TABLE_CONTINUE;
2640 }
2641 
2642 static enum rb_id_table_iterator_result
rb_local_constants_i(ID const_name,VALUE const_value,void * ary)2643 rb_local_constants_i(ID const_name, VALUE const_value, void *ary)
2644 {
2645     if (rb_is_const_id(const_name) && !RB_CONST_PRIVATE_P((rb_const_entry_t *)const_value)) {
2646 	rb_ary_push((VALUE)ary, ID2SYM(const_name));
2647     }
2648     return ID_TABLE_CONTINUE;
2649 }
2650 
2651 static VALUE
rb_local_constants(VALUE mod)2652 rb_local_constants(VALUE mod)
2653 {
2654     struct rb_id_table *tbl = RCLASS_CONST_TBL(mod);
2655     VALUE ary;
2656 
2657     if (!tbl) return rb_ary_new2(0);
2658 
2659     ary = rb_ary_new2(rb_id_table_size(tbl));
2660     rb_id_table_foreach(tbl, rb_local_constants_i, (void *)ary);
2661     return ary;
2662 }
2663 
2664 void*
rb_mod_const_at(VALUE mod,void * data)2665 rb_mod_const_at(VALUE mod, void *data)
2666 {
2667     st_table *tbl = data;
2668     if (!tbl) {
2669 	tbl = st_init_numtable();
2670     }
2671     if (RCLASS_CONST_TBL(mod)) {
2672 	rb_id_table_foreach(RCLASS_CONST_TBL(mod), sv_i, tbl);
2673     }
2674     return tbl;
2675 }
2676 
2677 void*
rb_mod_const_of(VALUE mod,void * data)2678 rb_mod_const_of(VALUE mod, void *data)
2679 {
2680     VALUE tmp = mod;
2681     for (;;) {
2682 	data = rb_mod_const_at(tmp, data);
2683 	tmp = RCLASS_SUPER(tmp);
2684 	if (!tmp) break;
2685 	if (tmp == rb_cObject && mod != rb_cObject) break;
2686     }
2687     return data;
2688 }
2689 
2690 static int
list_i(st_data_t key,st_data_t value,VALUE ary)2691 list_i(st_data_t key, st_data_t value, VALUE ary)
2692 {
2693     ID sym = (ID)key;
2694     rb_const_entry_t *ce = (rb_const_entry_t *)value;
2695     if (RB_CONST_PUBLIC_P(ce)) rb_ary_push(ary, ID2SYM(sym));
2696     return ST_CONTINUE;
2697 }
2698 
2699 VALUE
rb_const_list(void * data)2700 rb_const_list(void *data)
2701 {
2702     st_table *tbl = data;
2703     VALUE ary;
2704 
2705     if (!tbl) return rb_ary_new2(0);
2706     ary = rb_ary_new2(tbl->num_entries);
2707     st_foreach_safe(tbl, list_i, ary);
2708     st_free_table(tbl);
2709 
2710     return ary;
2711 }
2712 
2713 /*
2714  *  call-seq:
2715  *     mod.constants(inherit=true)    -> array
2716  *
2717  *  Returns an array of the names of the constants accessible in
2718  *  <i>mod</i>. This includes the names of constants in any included
2719  *  modules (example at start of section), unless the <i>inherit</i>
2720  *  parameter is set to <code>false</code>.
2721  *
2722  *  The implementation makes no guarantees about the order in which the
2723  *  constants are yielded.
2724  *
2725  *    IO.constants.include?(:SYNC)        #=> true
2726  *    IO.constants(false).include?(:SYNC) #=> false
2727  *
2728  *  Also see <code>Module::const_defined?</code>.
2729  */
2730 
2731 VALUE
rb_mod_constants(int argc,const VALUE * argv,VALUE mod)2732 rb_mod_constants(int argc, const VALUE *argv, VALUE mod)
2733 {
2734     bool inherit = TRUE;
2735 
2736     if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
2737 
2738     if (inherit) {
2739 	return rb_const_list(rb_mod_const_of(mod, 0));
2740     }
2741     else {
2742 	return rb_local_constants(mod);
2743     }
2744 }
2745 
2746 static int
rb_const_defined_0(VALUE klass,ID id,int exclude,int recurse,int visibility)2747 rb_const_defined_0(VALUE klass, ID id, int exclude, int recurse, int visibility)
2748 {
2749     VALUE tmp;
2750     int mod_retry = 0;
2751     rb_const_entry_t *ce;
2752 
2753     tmp = klass;
2754   retry:
2755     while (tmp) {
2756 	if ((ce = rb_const_lookup(tmp, id))) {
2757 	    if (visibility && RB_CONST_PRIVATE_P(ce)) {
2758 		return (int)Qfalse;
2759 	    }
2760 	    if (ce->value == Qundef && !check_autoload_required(tmp, id, 0) &&
2761 		!rb_autoloading_value(tmp, id, NULL, NULL))
2762 		return (int)Qfalse;
2763 
2764 	    if (exclude && tmp == rb_cObject && klass != rb_cObject) {
2765 		return (int)Qfalse;
2766 	    }
2767 
2768 	    return (int)Qtrue;
2769 	}
2770 	if (!recurse) break;
2771 	tmp = RCLASS_SUPER(tmp);
2772     }
2773     if (!exclude && !mod_retry && BUILTIN_TYPE(klass) == T_MODULE) {
2774 	mod_retry = 1;
2775 	tmp = rb_cObject;
2776 	goto retry;
2777     }
2778     return (int)Qfalse;
2779 }
2780 
2781 int
rb_const_defined_from(VALUE klass,ID id)2782 rb_const_defined_from(VALUE klass, ID id)
2783 {
2784     return rb_const_defined_0(klass, id, TRUE, TRUE, FALSE);
2785 }
2786 
2787 int
rb_const_defined(VALUE klass,ID id)2788 rb_const_defined(VALUE klass, ID id)
2789 {
2790     return rb_const_defined_0(klass, id, FALSE, TRUE, FALSE);
2791 }
2792 
2793 int
rb_const_defined_at(VALUE klass,ID id)2794 rb_const_defined_at(VALUE klass, ID id)
2795 {
2796     return rb_const_defined_0(klass, id, TRUE, FALSE, FALSE);
2797 }
2798 
2799 MJIT_FUNC_EXPORTED int
rb_public_const_defined_from(VALUE klass,ID id)2800 rb_public_const_defined_from(VALUE klass, ID id)
2801 {
2802     return rb_const_defined_0(klass, id, TRUE, TRUE, TRUE);
2803 }
2804 
2805 int
rb_public_const_defined(VALUE klass,ID id)2806 rb_public_const_defined(VALUE klass, ID id)
2807 {
2808     return rb_const_defined_0(klass, id, FALSE, TRUE, TRUE);
2809 }
2810 
2811 int
rb_public_const_defined_at(VALUE klass,ID id)2812 rb_public_const_defined_at(VALUE klass, ID id)
2813 {
2814     return rb_const_defined_0(klass, id, TRUE, FALSE, TRUE);
2815 }
2816 
2817 static void
check_before_mod_set(VALUE klass,ID id,VALUE val,const char * dest)2818 check_before_mod_set(VALUE klass, ID id, VALUE val, const char *dest)
2819 {
2820     rb_check_frozen(klass);
2821 }
2822 
2823 void
rb_const_set(VALUE klass,ID id,VALUE val)2824 rb_const_set(VALUE klass, ID id, VALUE val)
2825 {
2826     rb_const_entry_t *ce;
2827     struct rb_id_table *tbl = RCLASS_CONST_TBL(klass);
2828 
2829     if (NIL_P(klass)) {
2830 	rb_raise(rb_eTypeError, "no class/module to define constant %"PRIsVALUE"",
2831 		 QUOTE_ID(id));
2832     }
2833 
2834     check_before_mod_set(klass, id, val, "constant");
2835     if (!tbl) {
2836 	RCLASS_CONST_TBL(klass) = tbl = rb_id_table_create(0);
2837 	rb_clear_constant_cache();
2838 	ce = ZALLOC(rb_const_entry_t);
2839 	rb_id_table_insert(tbl, id, (VALUE)ce);
2840 	setup_const_entry(ce, klass, val, CONST_PUBLIC);
2841     }
2842     else {
2843 	struct autoload_const ac;
2844 	memset(&ac, 0, sizeof(ac));
2845 	ac.mod = klass;
2846 	ac.id = id;
2847 	ac.value = val;
2848 	ac.flag = CONST_PUBLIC;
2849 	const_tbl_update(&ac);
2850     }
2851     /*
2852      * Resolve and cache class name immediately to resolve ambiguity
2853      * and avoid order-dependency on const_tbl
2854      */
2855     if (rb_cObject && (RB_TYPE_P(val, T_MODULE) || RB_TYPE_P(val, T_CLASS))) {
2856 	if (NIL_P(rb_class_path_cached(val))) {
2857 	    if (klass == rb_cObject) {
2858 		rb_ivar_set(val, classpath, rb_id2str(id));
2859 		rb_name_class(val, id);
2860 	    }
2861 	    else {
2862 		VALUE path;
2863 		ID pathid;
2864 		st_data_t n;
2865 		st_table *ivtbl = RCLASS_IV_TBL(klass);
2866 		if (ivtbl &&
2867 		    (st_lookup(ivtbl, (st_data_t)(pathid = classpath), &n) ||
2868 		     st_lookup(ivtbl, (st_data_t)(pathid = tmp_classpath), &n))) {
2869 		    path = rb_str_dup((VALUE)n);
2870 		    rb_str_append(rb_str_cat2(path, "::"), rb_id2str(id));
2871 		    OBJ_FREEZE(path);
2872 		    rb_ivar_set(val, pathid, path);
2873 		    rb_name_class(val, id);
2874 		}
2875 	    }
2876 	}
2877     }
2878 }
2879 
2880 static struct autoload_data_i *
current_autoload_data(VALUE mod,ID id,struct autoload_const ** acp)2881 current_autoload_data(VALUE mod, ID id, struct autoload_const **acp)
2882 {
2883     struct autoload_data_i *ele;
2884     VALUE load = autoload_data(mod, id);
2885     if (!load) return 0;
2886     ele = get_autoload_data(load, acp);
2887     if (!ele) return 0;
2888     /* for autoloading thread, keep the defined value to autoloading storage */
2889     if (ele->state && (ele->state->thread == rb_thread_current())) {
2890 	return ele;
2891     }
2892     return 0;
2893 }
2894 
2895 static void
const_tbl_update(struct autoload_const * ac)2896 const_tbl_update(struct autoload_const *ac)
2897 {
2898     VALUE value;
2899     VALUE klass = ac->mod;
2900     VALUE val = ac->value;
2901     ID id = ac->id;
2902     struct rb_id_table *tbl = RCLASS_CONST_TBL(klass);
2903     rb_const_flag_t visibility = ac->flag;
2904     rb_const_entry_t *ce;
2905 
2906     if (rb_id_table_lookup(tbl, id, &value)) {
2907 	ce = (rb_const_entry_t *)value;
2908 	if (ce->value == Qundef) {
2909 	    struct autoload_data_i *ele = current_autoload_data(klass, id, &ac);
2910 
2911 	    if (ele) {
2912 		rb_clear_constant_cache();
2913 
2914 		ac->value = val; /* autoload_i is non-WB-protected */
2915                 ac->file = rb_source_location(&ac->line);
2916 	    }
2917             else {
2918                 /* otherwise autoloaded constant, allow to override */
2919                 autoload_delete(klass, id);
2920                 ce->flag = visibility;
2921                 RB_OBJ_WRITE(klass, &ce->value, val);
2922                 RB_OBJ_WRITE(klass, &ce->file, ac->file);
2923                 ce->line = ac->line;
2924             }
2925             return;
2926 	}
2927 	else {
2928 	    VALUE name = QUOTE_ID(id);
2929 	    visibility = ce->flag;
2930 	    if (klass == rb_cObject)
2931 		rb_warn("already initialized constant %"PRIsVALUE"", name);
2932 	    else
2933 		rb_warn("already initialized constant %"PRIsVALUE"::%"PRIsVALUE"",
2934 			rb_class_name(klass), name);
2935 	    if (!NIL_P(ce->file) && ce->line) {
2936 		rb_compile_warn(RSTRING_PTR(ce->file), ce->line,
2937 				"previous definition of %"PRIsVALUE" was here", name);
2938 	    }
2939 	}
2940 	rb_clear_constant_cache();
2941 	setup_const_entry(ce, klass, val, visibility);
2942     }
2943     else {
2944 	rb_clear_constant_cache();
2945 
2946 	ce = ZALLOC(rb_const_entry_t);
2947 	rb_id_table_insert(tbl, id, (VALUE)ce);
2948 	setup_const_entry(ce, klass, val, visibility);
2949     }
2950 }
2951 
2952 static void
setup_const_entry(rb_const_entry_t * ce,VALUE klass,VALUE val,rb_const_flag_t visibility)2953 setup_const_entry(rb_const_entry_t *ce, VALUE klass, VALUE val,
2954 		  rb_const_flag_t visibility)
2955 {
2956     ce->flag = visibility;
2957     RB_OBJ_WRITE(klass, &ce->value, val);
2958     RB_OBJ_WRITE(klass, &ce->file, rb_source_location(&ce->line));
2959 }
2960 
2961 void
rb_define_const(VALUE klass,const char * name,VALUE val)2962 rb_define_const(VALUE klass, const char *name, VALUE val)
2963 {
2964     ID id = rb_intern(name);
2965 
2966     if (!rb_is_const_id(id)) {
2967 	rb_warn("rb_define_const: invalid name `%s' for constant", name);
2968     }
2969     rb_const_set(klass, id, val);
2970 }
2971 
2972 void
rb_define_global_const(const char * name,VALUE val)2973 rb_define_global_const(const char *name, VALUE val)
2974 {
2975     rb_define_const(rb_cObject, name, val);
2976 }
2977 
2978 static void
set_const_visibility(VALUE mod,int argc,const VALUE * argv,rb_const_flag_t flag,rb_const_flag_t mask)2979 set_const_visibility(VALUE mod, int argc, const VALUE *argv,
2980 		     rb_const_flag_t flag, rb_const_flag_t mask)
2981 {
2982     int i;
2983     rb_const_entry_t *ce;
2984     ID id;
2985 
2986     rb_class_modify_check(mod);
2987     if (argc == 0) {
2988 	rb_warning("%"PRIsVALUE" with no argument is just ignored",
2989 		   QUOTE_ID(rb_frame_callee()));
2990 	return;
2991     }
2992 
2993     for (i = 0; i < argc; i++) {
2994 	struct autoload_const *ac;
2995 	VALUE val = argv[i];
2996 	id = rb_check_id(&val);
2997 	if (!id) {
2998 	    if (i > 0) {
2999 		rb_clear_constant_cache();
3000 	    }
3001 
3002 	    rb_name_err_raise("constant %2$s::%1$s not defined",
3003 			      mod, val);
3004 	}
3005 	if ((ce = rb_const_lookup(mod, id))) {
3006 	    ce->flag &= ~mask;
3007 	    ce->flag |= flag;
3008 	    if (ce->value == Qundef) {
3009 		struct autoload_data_i *ele;
3010 
3011 		ele = current_autoload_data(mod, id, &ac);
3012 		if (ele) {
3013 		    ac->flag &= ~mask;
3014 		    ac->flag |= flag;
3015 		}
3016 	    }
3017 	}
3018 	else {
3019 	    if (i > 0) {
3020 		rb_clear_constant_cache();
3021 	    }
3022 	    rb_name_err_raise("constant %2$s::%1$s not defined",
3023 			      mod, ID2SYM(id));
3024 	}
3025     }
3026     rb_clear_constant_cache();
3027 }
3028 
3029 void
rb_deprecate_constant(VALUE mod,const char * name)3030 rb_deprecate_constant(VALUE mod, const char *name)
3031 {
3032     rb_const_entry_t *ce;
3033     ID id;
3034     long len = strlen(name);
3035 
3036     rb_class_modify_check(mod);
3037     if (!(id = rb_check_id_cstr(name, len, NULL)) ||
3038 	!(ce = rb_const_lookup(mod, id))) {
3039 	rb_name_err_raise("constant %2$s::%1$s not defined",
3040 			  mod, rb_fstring_new(name, len));
3041     }
3042     ce->flag |= CONST_DEPRECATED;
3043 }
3044 
3045 /*
3046  *  call-seq:
3047  *     mod.private_constant(symbol, ...)    => mod
3048  *
3049  *  Makes a list of existing constants private.
3050  */
3051 
3052 VALUE
rb_mod_private_constant(int argc,const VALUE * argv,VALUE obj)3053 rb_mod_private_constant(int argc, const VALUE *argv, VALUE obj)
3054 {
3055     set_const_visibility(obj, argc, argv, CONST_PRIVATE, CONST_VISIBILITY_MASK);
3056     return obj;
3057 }
3058 
3059 /*
3060  *  call-seq:
3061  *     mod.public_constant(symbol, ...)    => mod
3062  *
3063  *  Makes a list of existing constants public.
3064  */
3065 
3066 VALUE
rb_mod_public_constant(int argc,const VALUE * argv,VALUE obj)3067 rb_mod_public_constant(int argc, const VALUE *argv, VALUE obj)
3068 {
3069     set_const_visibility(obj, argc, argv, CONST_PUBLIC, CONST_VISIBILITY_MASK);
3070     return obj;
3071 }
3072 
3073 /*
3074  *  call-seq:
3075  *     mod.deprecate_constant(symbol, ...)    => mod
3076  *
3077  *  Makes a list of existing constants deprecated.
3078  */
3079 
3080 VALUE
rb_mod_deprecate_constant(int argc,const VALUE * argv,VALUE obj)3081 rb_mod_deprecate_constant(int argc, const VALUE *argv, VALUE obj)
3082 {
3083     set_const_visibility(obj, argc, argv, CONST_DEPRECATED, CONST_DEPRECATED);
3084     return obj;
3085 }
3086 
3087 static VALUE
original_module(VALUE c)3088 original_module(VALUE c)
3089 {
3090     if (RB_TYPE_P(c, T_ICLASS))
3091 	return RBASIC(c)->klass;
3092     return c;
3093 }
3094 
3095 static int
cvar_lookup_at(VALUE klass,ID id,st_data_t * v)3096 cvar_lookup_at(VALUE klass, ID id, st_data_t *v)
3097 {
3098     if (!RCLASS_IV_TBL(klass)) return 0;
3099     return st_lookup(RCLASS_IV_TBL(klass), (st_data_t)id, v);
3100 }
3101 
3102 static VALUE
cvar_front_klass(VALUE klass)3103 cvar_front_klass(VALUE klass)
3104 {
3105     if (FL_TEST(klass, FL_SINGLETON)) {
3106 	VALUE obj = rb_ivar_get(klass, id__attached__);
3107 	if (RB_TYPE_P(obj, T_MODULE) || RB_TYPE_P(obj, T_CLASS)) {
3108 	    return obj;
3109 	}
3110     }
3111     return RCLASS_SUPER(klass);
3112 }
3113 
3114 static void
cvar_overtaken(VALUE front,VALUE target,ID id)3115 cvar_overtaken(VALUE front, VALUE target, ID id)
3116 {
3117     if (front && target != front) {
3118 	st_data_t did = (st_data_t)id;
3119 
3120 	if (RTEST(ruby_verbose)) {
3121 	    rb_warning("class variable % "PRIsVALUE" of %"PRIsVALUE" is overtaken by %"PRIsVALUE"",
3122 		       ID2SYM(id), rb_class_name(original_module(front)),
3123 		       rb_class_name(original_module(target)));
3124 	}
3125 	if (BUILTIN_TYPE(front) == T_CLASS) {
3126 	    st_delete(RCLASS_IV_TBL(front), &did, 0);
3127 	}
3128     }
3129 }
3130 
3131 #define CVAR_FOREACH_ANCESTORS(klass, v, r) \
3132     for (klass = cvar_front_klass(klass); klass; klass = RCLASS_SUPER(klass)) { \
3133 	if (cvar_lookup_at(klass, id, (v))) { \
3134 	    r; \
3135 	} \
3136     }
3137 
3138 #define CVAR_LOOKUP(v,r) do {\
3139     if (cvar_lookup_at(klass, id, (v))) {r;}\
3140     CVAR_FOREACH_ANCESTORS(klass, v, r);\
3141 } while(0)
3142 
3143 void
rb_cvar_set(VALUE klass,ID id,VALUE val)3144 rb_cvar_set(VALUE klass, ID id, VALUE val)
3145 {
3146     VALUE tmp, front = 0, target = 0;
3147 
3148     tmp = klass;
3149     CVAR_LOOKUP(0, {if (!front) front = klass; target = klass;});
3150     if (target) {
3151 	cvar_overtaken(front, target, id);
3152     }
3153     else {
3154 	target = tmp;
3155     }
3156 
3157     check_before_mod_set(target, id, val, "class variable");
3158     if (!RCLASS_IV_TBL(target)) {
3159 	RCLASS_IV_TBL(target) = st_init_numtable();
3160     }
3161 
3162     rb_class_ivar_set(target, id, val);
3163 }
3164 
3165 VALUE
rb_cvar_get(VALUE klass,ID id)3166 rb_cvar_get(VALUE klass, ID id)
3167 {
3168     VALUE tmp, front = 0, target = 0;
3169     st_data_t value;
3170 
3171     tmp = klass;
3172     CVAR_LOOKUP(&value, {if (!front) front = klass; target = klass;});
3173     if (!target) {
3174 	rb_name_err_raise("uninitialized class variable %1$s in %2$s",
3175 			  tmp, ID2SYM(id));
3176     }
3177     cvar_overtaken(front, target, id);
3178     return (VALUE)value;
3179 }
3180 
3181 VALUE
rb_cvar_defined(VALUE klass,ID id)3182 rb_cvar_defined(VALUE klass, ID id)
3183 {
3184     if (!klass) return Qfalse;
3185     CVAR_LOOKUP(0,return Qtrue);
3186     return Qfalse;
3187 }
3188 
3189 static ID
cv_intern(VALUE klass,const char * name)3190 cv_intern(VALUE klass, const char *name)
3191 {
3192     ID id = rb_intern(name);
3193     if (!rb_is_class_id(id)) {
3194 	rb_name_err_raise("wrong class variable name %1$s",
3195 			  klass, rb_str_new_cstr(name));
3196     }
3197     return id;
3198 }
3199 
3200 void
rb_cv_set(VALUE klass,const char * name,VALUE val)3201 rb_cv_set(VALUE klass, const char *name, VALUE val)
3202 {
3203     ID id = cv_intern(klass, name);
3204     rb_cvar_set(klass, id, val);
3205 }
3206 
3207 VALUE
rb_cv_get(VALUE klass,const char * name)3208 rb_cv_get(VALUE klass, const char *name)
3209 {
3210     ID id = cv_intern(klass, name);
3211     return rb_cvar_get(klass, id);
3212 }
3213 
3214 void
rb_define_class_variable(VALUE klass,const char * name,VALUE val)3215 rb_define_class_variable(VALUE klass, const char *name, VALUE val)
3216 {
3217     ID id = cv_intern(klass, name);
3218     rb_cvar_set(klass, id, val);
3219 }
3220 
3221 static int
cv_i(st_data_t k,st_data_t v,st_data_t a)3222 cv_i(st_data_t k, st_data_t v, st_data_t a)
3223 {
3224     ID key = (ID)k;
3225     st_table *tbl = (st_table *)a;
3226 
3227     if (rb_is_class_id(key)) {
3228 	st_update(tbl, (st_data_t)key, cv_i_update, 0);
3229     }
3230     return ST_CONTINUE;
3231 }
3232 
3233 static void*
mod_cvar_at(VALUE mod,void * data)3234 mod_cvar_at(VALUE mod, void *data)
3235 {
3236     st_table *tbl = data;
3237     if (!tbl) {
3238 	tbl = st_init_numtable();
3239     }
3240     if (RCLASS_IV_TBL(mod)) {
3241 	st_foreach_safe(RCLASS_IV_TBL(mod), cv_i, (st_data_t)tbl);
3242     }
3243     return tbl;
3244 }
3245 
3246 static void*
mod_cvar_of(VALUE mod,void * data)3247 mod_cvar_of(VALUE mod, void *data)
3248 {
3249     VALUE tmp = mod;
3250     for (;;) {
3251 	data = mod_cvar_at(tmp, data);
3252 	tmp = RCLASS_SUPER(tmp);
3253 	if (!tmp) break;
3254     }
3255     return data;
3256 }
3257 
3258 static int
cv_list_i(st_data_t key,st_data_t value,VALUE ary)3259 cv_list_i(st_data_t key, st_data_t value, VALUE ary)
3260 {
3261     ID sym = (ID)key;
3262     rb_ary_push(ary, ID2SYM(sym));
3263     return ST_CONTINUE;
3264 }
3265 
3266 static VALUE
cvar_list(void * data)3267 cvar_list(void *data)
3268 {
3269     st_table *tbl = data;
3270     VALUE ary;
3271 
3272     if (!tbl) return rb_ary_new2(0);
3273     ary = rb_ary_new2(tbl->num_entries);
3274     st_foreach_safe(tbl, cv_list_i, ary);
3275     st_free_table(tbl);
3276 
3277     return ary;
3278 }
3279 
3280 /*
3281  *  call-seq:
3282  *     mod.class_variables(inherit=true)    -> array
3283  *
3284  *  Returns an array of the names of class variables in <i>mod</i>.
3285  *  This includes the names of class variables in any included
3286  *  modules, unless the <i>inherit</i> parameter is set to
3287  *  <code>false</code>.
3288  *
3289  *     class One
3290  *       @@var1 = 1
3291  *     end
3292  *     class Two < One
3293  *       @@var2 = 2
3294  *     end
3295  *     One.class_variables          #=> [:@@var1]
3296  *     Two.class_variables          #=> [:@@var2, :@@var1]
3297  *     Two.class_variables(false)   #=> [:@@var2]
3298  */
3299 
3300 VALUE
rb_mod_class_variables(int argc,const VALUE * argv,VALUE mod)3301 rb_mod_class_variables(int argc, const VALUE *argv, VALUE mod)
3302 {
3303     bool inherit = TRUE;
3304     st_table *tbl;
3305 
3306     if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
3307     if (inherit) {
3308 	tbl = mod_cvar_of(mod, 0);
3309     }
3310     else {
3311 	tbl = mod_cvar_at(mod, 0);
3312     }
3313     return cvar_list(tbl);
3314 }
3315 
3316 /*
3317  *  call-seq:
3318  *     remove_class_variable(sym)    -> obj
3319  *
3320  *  Removes the definition of the <i>sym</i>, returning that
3321  *  constant's value.
3322  *
3323  *     class Dummy
3324  *       @@var = 99
3325  *       puts @@var
3326  *       remove_class_variable(:@@var)
3327  *       p(defined? @@var)
3328  *     end
3329  *
3330  *  <em>produces:</em>
3331  *
3332  *     99
3333  *     nil
3334  */
3335 
3336 VALUE
rb_mod_remove_cvar(VALUE mod,VALUE name)3337 rb_mod_remove_cvar(VALUE mod, VALUE name)
3338 {
3339     const ID id = id_for_var_message(mod, name, class, "wrong class variable name %1$s");
3340     st_data_t val, n = id;
3341 
3342     if (!id) {
3343       not_defined:
3344 	rb_name_err_raise("class variable %1$s not defined for %2$s",
3345 			  mod, name);
3346     }
3347     rb_check_frozen(mod);
3348     if (RCLASS_IV_TBL(mod) && st_delete(RCLASS_IV_TBL(mod), &n, &val)) {
3349 	return (VALUE)val;
3350     }
3351     if (rb_cvar_defined(mod, id)) {
3352 	rb_name_err_raise("cannot remove %1$s for %2$s", mod, ID2SYM(id));
3353     }
3354     goto not_defined;
3355 }
3356 
3357 VALUE
rb_iv_get(VALUE obj,const char * name)3358 rb_iv_get(VALUE obj, const char *name)
3359 {
3360     ID id = rb_intern(name);
3361 
3362     return rb_ivar_get(obj, id);
3363 }
3364 
3365 VALUE
rb_iv_set(VALUE obj,const char * name,VALUE val)3366 rb_iv_set(VALUE obj, const char *name, VALUE val)
3367 {
3368     ID id = rb_intern(name);
3369 
3370     return rb_ivar_set(obj, id, val);
3371 }
3372 
3373 /* tbl = xx(obj); tbl[key] = value; */
3374 int
rb_class_ivar_set(VALUE obj,ID key,VALUE value)3375 rb_class_ivar_set(VALUE obj, ID key, VALUE value)
3376 {
3377     st_table *tbl = RCLASS_IV_TBL(obj);
3378     int result = st_insert(tbl, (st_data_t)key, (st_data_t)value);
3379     RB_OBJ_WRITTEN(obj, Qundef, value);
3380     return result;
3381 }
3382 
3383 static int
tbl_copy_i(st_data_t key,st_data_t value,st_data_t data)3384 tbl_copy_i(st_data_t key, st_data_t value, st_data_t data)
3385 {
3386     RB_OBJ_WRITTEN((VALUE)data, Qundef, (VALUE)value);
3387     return ST_CONTINUE;
3388 }
3389 
3390 st_table *
rb_st_copy(VALUE obj,struct st_table * orig_tbl)3391 rb_st_copy(VALUE obj, struct st_table *orig_tbl)
3392 {
3393     st_table *new_tbl = st_copy(orig_tbl);
3394     st_foreach(new_tbl, tbl_copy_i, (st_data_t)obj);
3395     return new_tbl;
3396 }
3397 
3398 MJIT_FUNC_EXPORTED rb_const_entry_t *
rb_const_lookup(VALUE klass,ID id)3399 rb_const_lookup(VALUE klass, ID id)
3400 {
3401     struct rb_id_table *tbl = RCLASS_CONST_TBL(klass);
3402     VALUE val;
3403 
3404     if (tbl && rb_id_table_lookup(tbl, id, &val)) {
3405 	return (rb_const_entry_t *)val;
3406     }
3407     return 0;
3408 }
3409