Ruby 4.1.0dev (2026-09-27 revision f6ff9e7d02e46360f8930b280a3dd921cccbda29)
vm_method.c (f6ff9e7d02e46360f8930b280a3dd921cccbda29)
1/*
2 * This file is included by vm.c
3 */
4
5#include "id_table.h"
6#include "yjit.h"
7
8#define METHOD_DEBUG 0
9
10static int vm_redefinition_check_flag(VALUE klass);
11static void rb_vm_check_redefinition_opt_method(const rb_method_entry_t *me, VALUE klass);
12static inline rb_method_entry_t *lookup_method_table(VALUE klass, ID id);
13
14#define object_id idObject_id
15#define added idMethod_added
16#define singleton_added idSingleton_method_added
17#define removed idMethod_removed
18#define singleton_removed idSingleton_method_removed
19#define undefined idMethod_undefined
20#define singleton_undefined idSingleton_method_undefined
21
22#define ruby_running (GET_VM()->running)
23/* int ruby_running = 0; */
24
25static enum rb_id_table_iterator_result
26mark_cc_entry_i(VALUE ccs_ptr, void *data)
27{
28 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_ptr;
29
30 VM_ASSERT(vm_ccs_p(ccs));
31
32 if (METHOD_ENTRY_INVALIDATED(ccs->cme)) {
33 /* Never prune from a GC, only mark. A cc table walk (dup and friends) can trigger a
34 * GC from an allocation midway, so an xfree+DELETE while marking would derail the
35 * walking iterator into freed ccs. The mutator cleans up, under the VM lock. */
36 rb_gc_mark_movable((VALUE)ccs->cme);
37 for (int i = 0; i < ccs->len; i++) {
38 rb_gc_mark_movable((VALUE)ccs->entries[i].cc);
39 }
40 return ID_TABLE_CONTINUE;
41 }
42 else {
43 rb_gc_mark_movable((VALUE)ccs->cme);
44
45 for (int i = 0; i < ccs->len; i++) {
46 const struct rb_callcache *cc = ccs->entries[i].cc;
47 VM_ASSERT(cc->klass == Qundef || vm_cc_check_cme(cc, ccs->cme));
48
49 rb_gc_mark_movable((VALUE)cc);
50 }
51 return ID_TABLE_CONTINUE;
52 }
53}
54
55static void
56vm_cc_table_mark(void *data)
57{
58 struct rb_id_table *tbl = (struct rb_id_table *)data;
59 if (tbl) {
60 rb_id_table_foreach_values(tbl, mark_cc_entry_i, NULL);
61 }
62}
63
64static enum rb_id_table_iterator_result
65cc_table_free_i(VALUE ccs_ptr, void *data)
66{
67 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_ptr;
68 VM_ASSERT(vm_ccs_p(ccs));
69
70 ruby_xfree_sized(ccs, vm_ccs_alloc_size(ccs->capa));
71
72 return ID_TABLE_CONTINUE;
73}
74
75static void
76vm_cc_table_free(void *data)
77{
78 struct rb_id_table *tbl = (struct rb_id_table *)data;
79
80 rb_id_table_foreach_values(tbl, cc_table_free_i, NULL);
81 rb_managed_id_table_type.function.dfree(data);
82}
83
84static enum rb_id_table_iterator_result
85cc_table_memsize_i(VALUE ccs_ptr, void *data_ptr)
86{
87 size_t *total_size = data_ptr;
88 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_ptr;
89 *total_size += sizeof(*ccs);
90 *total_size += sizeof(ccs->entries[0]) * ccs->capa;
91 return ID_TABLE_CONTINUE;
92}
93
94static size_t
95vm_cc_table_memsize(const void *data)
96{
97 size_t memsize = rb_managed_id_table_type.function.dsize(data);
98 struct rb_id_table *tbl = (struct rb_id_table *)data;
99 rb_id_table_foreach_values(tbl, cc_table_memsize_i, &memsize);
100 return memsize;
101}
102
103static enum rb_id_table_iterator_result
104compact_cc_entry_i(VALUE ccs_ptr, void *data)
105{
106 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_ptr;
107
108 rb_gc_update_moved_ptr(&ccs->cme);
109 VM_ASSERT(vm_ccs_p(ccs));
110
111 for (int i=0; i<ccs->len; i++) {
112 rb_gc_update_moved_ptr(&ccs->entries[i].cc);
113 }
114
115 return ID_TABLE_CONTINUE;
116}
117
118static void
119vm_cc_table_compact(void *data)
120{
121 struct rb_id_table *tbl = (struct rb_id_table *)data;
122 rb_id_table_foreach_values(tbl, compact_cc_entry_i, NULL);
123}
124
125static const rb_data_type_t cc_table_type = {
126 .wrap_struct_name = "VM/cc_table",
127 .function = {
128 .dmark = vm_cc_table_mark,
129 .dfree = vm_cc_table_free,
130 .dsize = vm_cc_table_memsize,
131 .dcompact = vm_cc_table_compact,
132 },
133 .parent = &rb_managed_id_table_type,
134 .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE,
135};
136
137VALUE
138rb_vm_cc_table_create(size_t capa)
139{
140 return rb_managed_id_table_create(&cc_table_type, capa);
141}
142
143static void vm_ccs_invalidate(struct rb_class_cc_entries *ccs);
144
145static enum rb_id_table_iterator_result
146vm_cc_table_dup_i(ID key, VALUE old_ccs_ptr, void *data)
147{
148 VALUE new_table = (VALUE)data;
149 struct rb_class_cc_entries *old_ccs = (struct rb_class_cc_entries *)old_ccs_ptr;
150
151 if (METHOD_ENTRY_INVALIDATED(old_ccs->cme)) {
152 // At this point, old_ccs is valid and hasn't been freed.
153 // However once we allocate below, mark_cc_entry_i may free the entries
154 // If this is invalidated, we should avoid the copy, and invalidate the CCs
155 // since later we will CAS the new cc_table, disconnecting old_ccs and it
156 // may not be marked.
157 // We don't want to copy this anyways since it's invalidated.
158 vm_ccs_invalidate(old_ccs);
159 return ID_TABLE_CONTINUE;
160 }
161
162 size_t memsize = vm_ccs_alloc_size(old_ccs->capa);
163 struct rb_class_cc_entries *new_ccs = ruby_xcalloc(1, memsize);
164 rb_managed_id_table_insert(new_table, key, (VALUE)new_ccs);
165
166 // We hold the VM lock, so invalidation should not have happened between
167 // our earlier invalidation check and now.
168 VM_ASSERT(!METHOD_ENTRY_INVALIDATED(old_ccs->cme));
169
170 memcpy(new_ccs, old_ccs, memsize);
171
172#if VM_CHECK_MODE > 0
173 new_ccs->debug_sig = ~(VALUE)new_ccs;
174#endif
175
176 RB_OBJ_WRITTEN(new_table, Qundef, (VALUE)new_ccs->cme);
177 for (int index = 0; index < new_ccs->len; index++) {
178 RB_OBJ_WRITTEN(new_table, Qundef, new_ccs->entries[index].cc);
179 }
180 return ID_TABLE_CONTINUE;
181}
182
183VALUE
184rb_vm_cc_table_dup(VALUE old_table)
185{
186 ASSERT_vm_locking();
187 VALUE new_table = rb_vm_cc_table_create(rb_managed_id_table_size(old_table));
188 rb_managed_id_table_foreach(old_table, vm_cc_table_dup_i, (void *)new_table);
189 return new_table;
190}
191
192static void
193vm_ccs_invalidate(struct rb_class_cc_entries *ccs)
194{
195 for (int i=0; i<ccs->len; i++) {
196 const struct rb_callcache *cc = ccs->entries[i].cc;
197 if (cc->klass == Qundef) continue; // already invalidated
198 VM_ASSERT(!vm_cc_super_p(cc) && !vm_cc_refinement_p(cc));
199 vm_cc_invalidate(cc);
200 }
201}
202
203static void
204rb_vm_ccs_invalidate_and_free(struct rb_class_cc_entries *ccs)
205{
206 RB_DEBUG_COUNTER_INC(ccs_free);
207 vm_ccs_invalidate(ccs);
208 ruby_xfree_sized(ccs, vm_ccs_alloc_size(ccs->capa));
209}
210
211void
212rb_vm_cc_table_delete(VALUE table, ID mid)
213{
214 VALUE ccs_obj;
215 if (rb_managed_id_table_lookup(table, mid, &ccs_obj)) {
216 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_obj;
217 rb_managed_id_table_delete(table, mid);
218 rb_vm_ccs_invalidate_and_free(ccs);
219 }
220}
221
222static enum rb_id_table_iterator_result
223vm_ccs_dump_i(ID mid, VALUE val, void *data)
224{
225 const struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)val;
226 fprintf(stderr, " | %s (len:%d) ", rb_id2name(mid), ccs->len);
227 rp(ccs->cme);
228
229 for (int i=0; i<ccs->len; i++) {
230 rp_m( " | \t", ccs->entries[i].cc);
231 }
232
233 return ID_TABLE_CONTINUE;
234}
235
236static void
237vm_ccs_dump(VALUE klass, ID target_mid)
238{
239 VALUE cc_tbl = RCLASS_WRITABLE_CC_TBL(klass);
240 if (cc_tbl) {
241 VALUE ccs;
242 if (target_mid) {
243 if (rb_managed_id_table_lookup(cc_tbl, target_mid, &ccs)) {
244 fprintf(stderr, " [CCTB] %p\n", (void *)cc_tbl);
245 vm_ccs_dump_i(target_mid, ccs, NULL);
246 }
247 }
248 else {
249 fprintf(stderr, " [CCTB] %p\n", (void *)cc_tbl);
250 rb_managed_id_table_foreach(cc_tbl, vm_ccs_dump_i, (void *)target_mid);
251 }
252 }
253}
254
255static enum rb_id_table_iterator_result
256vm_cme_dump_i(ID mid, VALUE val, void *data)
257{
258 ID target_mid = (ID)data;
259 if (target_mid == 0 || mid == target_mid) {
260 rp_m(" > ", val);
261 }
262 return ID_TABLE_CONTINUE;
263}
264
265static VALUE
266vm_mtbl_dump(VALUE klass, ID target_mid)
267{
268 fprintf(stderr, "# vm_mtbl\n");
269 while (klass) {
270 rp_m(" -> ", klass);
271 VALUE me;
272
273 if (RCLASS_M_TBL(klass)) {
274 if (target_mid != 0) {
275 if (rb_id_table_lookup(RCLASS_M_TBL(klass), target_mid, &me)) {
276 rp_m(" [MTBL] ", me);
277 }
278 }
279 else {
280 fprintf(stderr, " ## RCLASS_M_TBL (%p)\n", (void *)RCLASS_M_TBL(klass));
281 rb_id_table_foreach(RCLASS_M_TBL(klass), vm_cme_dump_i, NULL);
282 }
283 }
284 else {
285 fprintf(stderr, " MTBL: NULL\n");
286 }
287 if (RCLASS_WRITABLE_CALLABLE_M_TBL(klass)) {
288 if (target_mid != 0) {
289 if (rb_id_table_lookup(RCLASS_WRITABLE_CALLABLE_M_TBL(klass), target_mid, &me)) {
290 rp_m(" [CM**] ", me);
291 }
292 }
293 else {
294 fprintf(stderr, " ## RCLASS_CALLABLE_M_TBL\n");
295 rb_id_table_foreach(RCLASS_WRITABLE_CALLABLE_M_TBL(klass), vm_cme_dump_i, NULL);
296 }
297 }
298 if (RCLASS_WRITABLE_CC_TBL(klass)) {
299 vm_ccs_dump(klass, target_mid);
300 }
301 klass = RCLASS_SUPER(klass);
302 }
303 return Qnil;
304}
305
306void
307rb_vm_mtbl_dump(const char *msg, VALUE klass, ID target_mid)
308{
309 fprintf(stderr, "[%s] ", msg);
310 vm_mtbl_dump(klass, target_mid);
311}
312
313static inline void
314vm_cme_invalidate(rb_callable_method_entry_t *cme)
315{
316 VM_ASSERT(IMEMO_TYPE_P(cme, imemo_ment), "cme: %d", imemo_type((VALUE)cme));
317 VM_ASSERT(callable_method_entry_p(cme));
318 METHOD_ENTRY_INVALIDATED_SET(cme);
319 RB_DEBUG_COUNTER_INC(cc_cme_invalidate);
320
321 rb_yjit_cme_invalidate(cme);
322 rb_zjit_cme_invalidate(cme);
323}
324
325static int
326rb_clear_constant_cache_for_id_i(st_data_t ic, st_data_t arg)
327{
328 ((IC) ic)->entry = NULL;
329 return ST_CONTINUE;
330}
331
332void
334{
335 VALUE lookup_result;
336 rb_vm_t *vm = GET_VM();
337
338 if (rb_id_table_lookup(&vm->constant_cache, id, &lookup_result)) {
339 set_table *ics = (set_table *)lookup_result;
340 set_table_foreach(ics, rb_clear_constant_cache_for_id_i, (st_data_t) NULL);
341 ruby_vm_constant_cache_invalidations += ics->num_entries;
342 }
343
344 rb_yjit_constant_state_changed(id);
345 rb_zjit_constant_state_changed(id);
346}
347
348static void
349invalidate_negative_cache(ID mid)
350{
351 VALUE cme;
352 rb_vm_t *vm = GET_VM();
353
354 if (rb_id_table_lookup(&vm->negative_cme_table, mid, &cme)) {
355 rb_id_table_delete(&vm->negative_cme_table, mid);
356 vm_cme_invalidate((rb_callable_method_entry_t *)cme);
357 RB_DEBUG_COUNTER_INC(cc_invalidate_negative);
358 }
359}
360
361const rb_method_entry_t * rb_method_entry_clone(const rb_method_entry_t *src_me);
362static const rb_callable_method_entry_t *complemented_callable_method_entry(VALUE klass, ID id);
363static const rb_callable_method_entry_t *lookup_overloaded_cme(const rb_callable_method_entry_t *cme);
364
365static void
366invalidate_method_cache_in_cc_table(VALUE tbl, ID mid)
367{
368 VALUE ccs_data;
369 if (tbl && rb_managed_id_table_lookup(tbl, mid, &ccs_data)) {
370 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_data;
371 rb_yjit_cme_invalidate((rb_callable_method_entry_t *)ccs->cme);
372 rb_zjit_cme_invalidate((rb_callable_method_entry_t *)ccs->cme);
373 if (NIL_P(ccs->cme->owner)) invalidate_negative_cache(mid);
374 rb_vm_ccs_invalidate_and_free(ccs);
375 rb_managed_id_table_delete(tbl, mid);
376 RB_DEBUG_COUNTER_INC(cc_invalidate_leaf_ccs);
377 }
378}
379
380static void
381invalidate_callable_method_entry_in_callable_m_table(struct rb_id_table *tbl, ID mid)
382{
383 VALUE cme;
384 if (tbl && rb_id_table_lookup(tbl, mid, &cme)) {
385 rb_yjit_cme_invalidate((rb_callable_method_entry_t *)cme);
386 rb_zjit_cme_invalidate((rb_callable_method_entry_t *)cme);
387 rb_id_table_delete(tbl, mid);
388 RB_DEBUG_COUNTER_INC(cc_invalidate_leaf_callable);
389 }
390}
391
393 VALUE klass;
394 ID mid;
395 const rb_method_entry_t *cme;
396 const rb_method_entry_t *newer;
397};
398
399static void
400invalidate_callable_method_entry_in_every_m_table_i(rb_classext_t *ext, bool is_prime, VALUE box_value, void *data)
401{
402 st_data_t me;
404 struct rb_id_table *tbl = RCLASSEXT_M_TBL(ext);
405
406 if (rb_id_table_lookup(tbl, arg->mid, &me) && arg->cme == (const rb_method_entry_t *)me) {
407 rb_method_table_insert(arg->klass, tbl, arg->mid, arg->newer);
408 }
409}
410
412 VALUE owner;
413 VALUE klass_housing_cme;
414 VALUE origins; // Array of origins
415};
416
417static void
418collect_per_box_origins_i(rb_classext_t *ext, bool is_prime, VALUE box_value, void *data)
419{
420 struct collect_per_box_origins_arg *arg = (struct collect_per_box_origins_arg *)data;
421 VALUE origin = RCLASSEXT_ORIGIN(ext);
422
423 if (origin == arg->owner || origin == arg->klass_housing_cme) {
424 return;
425 }
426 long len = RARRAY_LEN(arg->origins);
427 for (long i = 0; i < len; i++) {
428 if (RARRAY_AREF(arg->origins, i) == origin) {
429 return;
430 }
431 }
432 rb_ary_push(arg->origins, origin);
433}
434
435static void
436invalidate_callable_method_entry_in_every_m_table(VALUE klass, ID mid, const rb_callable_method_entry_t *cme)
437{
438 // The argument cme must be invalidated later in the caller side
439 const rb_method_entry_t *newer = rb_method_entry_clone((const rb_method_entry_t *)cme);
441 .klass = klass,
442 .mid = mid,
443 .cme = (const rb_method_entry_t *) cme,
444 .newer = newer,
445 };
446 rb_class_classext_foreach(klass, invalidate_callable_method_entry_in_every_m_table_i, (void *)&arg);
447}
448
449static void
450invalidate_complemented_method_entry_in_callable_m_table(struct rb_id_table *tbl, ID mid)
451{
452 VALUE cme;
453 if (tbl && rb_id_table_lookup(tbl, mid, &cme)) {
454 rb_yjit_cme_invalidate((rb_callable_method_entry_t *)cme);
455 rb_zjit_cme_invalidate((rb_callable_method_entry_t *)cme);
456 rb_id_table_delete(tbl, mid);
457 RB_DEBUG_COUNTER_INC(cc_invalidate_tree_callable);
458 }
459}
460
461static void
462clear_method_cache_by_id_in_class(VALUE klass, ID mid)
463{
464 VM_ASSERT_TYPE2(klass, T_CLASS, T_ICLASS);
465 if (rb_objspace_garbage_object_p(klass)) return;
466
467 RB_VM_LOCKING() {
468 rb_vm_barrier();
469
470 if (LIKELY(!RCLASS_SUBCLASSES(klass)) &&
471 !FL_TEST_RAW(klass, RCLASS_HAS_SUBCLASSES) &&
472 // Non-refinement ICLASSes (from module inclusion) previously had
473 // subclasses reparented onto them, so they need the tree path for
474 // broader cme-based invalidation even though they now have no subclasses.
475 !(RB_TYPE_P(klass, T_ICLASS) && NIL_P(RCLASS_REFINED_CLASS(klass)))) {
476 // no subclasses
477 // check only current class
478
479 // invalidate CCs
480 VALUE cc_tbl = RCLASS_WRITABLE_CC_TBL(klass);
481 invalidate_method_cache_in_cc_table(cc_tbl, mid);
482 if (RCLASS_CC_TBL_NOT_PRIME_P(klass, cc_tbl)) {
483 invalidate_method_cache_in_cc_table(RCLASS_PRIME_CC_TBL(klass), mid);
484 }
485
486 // remove from callable_m_tbl, if exists
487 struct rb_id_table *cm_tbl = RCLASS_WRITABLE_CALLABLE_M_TBL(klass);
488 invalidate_callable_method_entry_in_callable_m_table(cm_tbl, mid);
489 if (RCLASS_CALLABLE_M_TBL_NOT_PRIME_P(klass, cm_tbl)) {
490 invalidate_callable_method_entry_in_callable_m_table(RCLASS_PRIME_CALLABLE_M_TBL(klass), mid);
491 }
492
493 RB_DEBUG_COUNTER_INC(cc_invalidate_leaf);
494 }
495 else {
496 const rb_callable_method_entry_t *cme = complemented_callable_method_entry(klass, mid);
497
498 if (cme) {
499 // invalidate cme if found to invalidate the inline method cache.
500 if (METHOD_ENTRY_CACHED(cme)) {
501 if (METHOD_ENTRY_COMPLEMENTED(cme)) {
502 // do nothing
503 }
504 else {
505 // invalidate cc by invalidating cc->cme
506 VALUE owner = cme->owner;
507 VM_ASSERT_TYPE(owner, T_CLASS);
508 VALUE klass_housing_cme;
509 if (cme->def->type == VM_METHOD_TYPE_REFINED && !cme->def->body.refined.orig_me) {
510 klass_housing_cme = owner;
511 }
512 else {
513 klass_housing_cme = RCLASS_ORIGIN(owner);
514 }
515
516 // replace the cme that will be invalid in the all classexts
517 invalidate_callable_method_entry_in_every_m_table(klass_housing_cme, mid, cme);
518 // owner may be a boxable class with per-box classext copies of its m_tbl
519 // (klass_housing_cme may be a non-boxable origin ICLASS that doesn't cover them)
520 if (klass_housing_cme != owner) {
521 invalidate_callable_method_entry_in_every_m_table(owner, mid, cme);
522 }
523 // Also update per-box origin ICLASSes. When ensure_origin is called in
524 // one box's context, it creates a per-box origin ICLASS whose m_tbl is
525 // a copy of owner's m_tbl at that time. The current execution box may
526 // not see these origins via RCLASS_ORIGIN(owner), so we find them by
527 // iterating all of owner's classexts and checking their origin_ fields.
528 {
529 VALUE origins = rb_ary_hidden_new(1);
530 struct collect_per_box_origins_arg origins_arg = {
531 .owner = owner,
532 .klass_housing_cme = klass_housing_cme,
533 .origins = origins,
534 };
535 rb_class_classext_foreach(owner, collect_per_box_origins_i, &origins_arg);
536 for (long i = 0; i < RARRAY_LEN(origins); i++) {
537 invalidate_callable_method_entry_in_every_m_table(RARRAY_AREF(origins, i), mid, cme);
538 }
539 RB_GC_GUARD(origins);
540 }
541 }
542
543 vm_cme_invalidate((rb_callable_method_entry_t *)cme);
544 RB_DEBUG_COUNTER_INC(cc_invalidate_tree_cme);
545
546 // In case of refinement ME, also invalidate the wrapped ME that
547 // could be cached at some callsite and is unreachable from any
548 // RCLASS_WRITABLE_CC_TBL.
549 if (cme->def->type == VM_METHOD_TYPE_REFINED && cme->def->body.refined.orig_me) {
550 vm_cme_invalidate((rb_callable_method_entry_t *)cme->def->body.refined.orig_me);
551 }
552
553 if (cme->def->iseq_overload) {
554 rb_callable_method_entry_t *monly_cme = (rb_callable_method_entry_t *)lookup_overloaded_cme(cme);
555 if (monly_cme) {
556 vm_cme_invalidate(monly_cme);
557 }
558 }
559 }
560
561 // invalidate complement tbl
562 if (METHOD_ENTRY_COMPLEMENTED(cme)) {
563 VALUE defined_class = cme->defined_class;
564 struct rb_id_table *cm_tbl = RCLASS_WRITABLE_CALLABLE_M_TBL(defined_class);
565 invalidate_complemented_method_entry_in_callable_m_table(cm_tbl, mid);
566 if (RCLASS_CALLABLE_M_TBL_NOT_PRIME_P(defined_class, cm_tbl)) {
567 struct rb_id_table *prime_cm_table = RCLASS_PRIME_CALLABLE_M_TBL(defined_class);
568 invalidate_complemented_method_entry_in_callable_m_table(prime_cm_table, mid);
569 }
570 }
571
572 RB_DEBUG_COUNTER_INC(cc_invalidate_tree);
573 }
574 else {
575 invalidate_negative_cache(mid);
576 }
577 }
578
579 rb_gccct_clear_table();
580 }
581}
582
583static void
584clear_iclass_method_cache_by_id(VALUE iclass, VALUE d)
585{
586 VM_ASSERT_TYPE(iclass, T_ICLASS);
587 ID mid = (ID)d;
588 clear_method_cache_by_id_in_class(iclass, mid);
589}
590
591static void
592clear_iclass_method_cache_by_id_for_refinements(VALUE klass, VALUE d)
593{
594 if (RB_TYPE_P(klass, T_ICLASS)) {
595 ID mid = (ID)d;
596 clear_method_cache_by_id_in_class(klass, mid);
597 }
598}
599
600void
601rb_clear_method_cache(VALUE klass_or_module, ID mid)
602{
603 if (RB_TYPE_P(klass_or_module, T_MODULE)) {
604 VALUE module = klass_or_module; // alias
605
606 if (FL_TEST(module, RMODULE_IS_REFINEMENT)) {
607 VALUE refined_class = rb_refinement_module_get_refined_class(module);
608 rb_clear_method_cache(refined_class, mid);
609 rb_class_foreach_subclass(refined_class, clear_iclass_method_cache_by_id_for_refinements, mid);
610 rb_clear_all_refinement_method_cache();
611 }
612 rb_class_foreach_subclass(module, clear_iclass_method_cache_by_id, mid);
613 }
614 else {
615 clear_method_cache_by_id_in_class(klass_or_module, mid);
616 }
617}
618
619static enum rb_id_table_iterator_result
620invalidate_method_entry_in_iclass_callable_m_tbl(VALUE cme, void *data)
621{
622 vm_cme_invalidate((rb_callable_method_entry_t *)cme);
623 return ID_TABLE_DELETE;
624}
625
626static enum rb_id_table_iterator_result
627invalidate_ccs_in_iclass_cc_tbl(VALUE value, void *data)
628{
629 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)value;
630 vm_cme_invalidate((rb_callable_method_entry_t *)ccs->cme);
631 ruby_xfree_sized(ccs, vm_ccs_alloc_size(ccs->capa));
632 return ID_TABLE_DELETE;
633}
634
635void
636rb_invalidate_method_caches(struct rb_id_table *cm_tbl, VALUE cc_tbl)
637{
638 if (cm_tbl) {
639 rb_id_table_foreach_values(cm_tbl, invalidate_method_entry_in_iclass_callable_m_tbl, NULL);
640 }
641 if (cc_tbl) {
642 rb_managed_id_table_foreach_values(cc_tbl, invalidate_ccs_in_iclass_cc_tbl, NULL);
643 }
644}
645
646static st_index_t
647vm_ci_hash(VALUE v)
648{
649 const struct rb_callinfo *ci = (const struct rb_callinfo *)v;
650 st_index_t h;
651 h = rb_hash_start(ci->mid);
652 h = rb_hash_uint(h, ci->flag);
653 h = rb_hash_uint(h, ci->argc);
654 if (ci->kwarg) {
655 for (int i = 0; i < ci->kwarg->keyword_len; i++) {
656 h = rb_hash_uint(h, ci->kwarg->keywords[i]);
657 }
658 }
659 return h;
660}
661
662static int
663vm_ci_hash_cmp(VALUE v1, VALUE v2)
664{
665 const struct rb_callinfo *ci1 = (const struct rb_callinfo *)v1;
666 const struct rb_callinfo *ci2 = (const struct rb_callinfo *)v2;
667 if (ci1->mid != ci2->mid) return 1;
668 if (ci1->flag != ci2->flag) return 1;
669 if (ci1->argc != ci2->argc) return 1;
670 if (ci1->kwarg != NULL) {
671 VM_ASSERT(ci2->kwarg != NULL); // implied by matching flags
672
673 if (ci1->kwarg->keyword_len != ci2->kwarg->keyword_len)
674 return 1;
675
676 for (int i = 0; i < ci1->kwarg->keyword_len; i++) {
677 if (ci1->kwarg->keywords[i] != ci2->kwarg->keywords[i]) {
678 return 1;
679 }
680 }
681 }
682 else {
683 VM_ASSERT(ci2->kwarg == NULL); // implied by matching flags
684 }
685 return 0;
686}
687
688static const struct st_hash_type vm_ci_hashtype = {
689 vm_ci_hash_cmp,
690 vm_ci_hash
691};
692
693static int
694ci_lookup_i(st_data_t *key, st_data_t *value, st_data_t data, int existing)
695{
696 const struct rb_callinfo *ci = (const struct rb_callinfo *)*key;
697 st_data_t *ret = (st_data_t *)data;
698
699 if (existing) {
700 if (rb_objspace_garbage_object_p((VALUE)ci)) {
701 *ret = (st_data_t)NULL;
702 return ST_DELETE;
703 }
704 else {
705 *ret = *key;
706 return ST_STOP;
707 }
708 }
709 else {
710 *key = *value = *ret = (st_data_t)ci;
711 return ST_CONTINUE;
712 }
713}
714
715const struct rb_callinfo *
716rb_vm_ci_lookup(ID mid, unsigned int flag, unsigned int argc, const struct rb_callinfo_kwarg *kwarg)
717{
718 rb_vm_t *vm = GET_VM();
719 const struct rb_callinfo *ci = NULL;
720
721 if (kwarg) {
722 RUBY_ATOMIC_FETCH_ADD(((struct rb_callinfo_kwarg *)kwarg)->references, 1);
723 }
724
725 struct rb_callinfo *new_ci = SHAREABLE_IMEMO_NEW(struct rb_callinfo, imemo_callinfo, (VALUE)kwarg);
726 new_ci->mid = mid;
727 new_ci->flag = flag;
728 new_ci->argc = argc;
729
730 RB_VM_LOCKING() {
731 st_table *ci_table = &vm->ci_table;
732
733 do {
734 st_update(ci_table, (st_data_t)new_ci, ci_lookup_i, (st_data_t)&ci);
735 } while (ci == NULL);
736 }
737
738 VM_ASSERT(ci);
739
740 return ci;
741}
742
743void
744rb_vm_ci_free(const struct rb_callinfo *ci)
745{
746 ASSERT_vm_locking();
747
748 rb_vm_t *vm = GET_VM();
749
750 st_data_t key = (st_data_t)ci;
751 st_delete(&vm->ci_table, &key, NULL);
752}
753
755 VALUE *entries;
756 size_t len;
757 size_t capa;
758};
759
760static void
761cc_refinement_set_free(void *ptr)
762{
763 struct cc_refinement_entries *e = ptr;
764 xfree(e->entries);
765}
766
767static size_t
768cc_refinement_set_memsize(const void *ptr)
769{
770 const struct cc_refinement_entries *e = ptr;
771 return e->capa * sizeof(VALUE);
772}
773
774static void
775cc_refinement_set_compact(void *ptr)
776{
777 struct cc_refinement_entries *e = ptr;
778 for (size_t i = 0; i < e->len; i++) {
779 rb_gc_update_moved(&e->entries[i]);
780 }
781}
782
783static void
784cc_refinement_set_handle_weak_references(void *ptr)
785{
786 struct cc_refinement_entries *e = ptr;
787 size_t write = 0;
788 for (size_t read = 0; read < e->len; read++) {
789 if (rb_gc_handle_weak_references_alive_p(e->entries[read])) {
790 e->entries[write++] = e->entries[read];
791 }
792 }
793 e->len = write;
794}
795
796static const rb_data_type_t cc_refinement_set_type = {
797 "VM/cc_refinement_set",
798 {
799 NULL,
800 cc_refinement_set_free,
801 cc_refinement_set_memsize,
802 cc_refinement_set_compact,
803 cc_refinement_set_handle_weak_references,
804 },
805 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
806};
807
808VALUE
809rb_cc_refinement_set_create(void)
810{
811 struct cc_refinement_entries *e;
812 VALUE obj = TypedData_Make_Struct(0, struct cc_refinement_entries, &cc_refinement_set_type, e);
813
814 e->entries = NULL;
815 e->len = 0;
816 e->capa = 0;
817
818 rb_gc_declare_weak_references(obj);
819
820 return obj;
821}
822
823void
824rb_vm_insert_cc_refinement(const struct rb_callcache *cc)
825{
826 rb_vm_t *vm = GET_VM();
827 RB_VM_LOCK_ENTER();
828 {
829 struct cc_refinement_entries *e = RTYPEDDATA_GET_DATA(vm->cc_refinement_set);
830 if (e->len == e->capa) {
831 size_t new_capa = e->capa == 0 ? 16 : e->capa * 2;
832 SIZED_REALLOC_N(e->entries, VALUE, new_capa, e->capa);
833 e->capa = new_capa;
834 }
835 e->entries[e->len++] = (VALUE)cc;
836
837 // We never mark the cc, but we need to issue a writebarrier so that
838 // the refinement set can be added to the remembered set
839 RB_OBJ_WRITTEN(vm->cc_refinement_set, Qundef, (VALUE)cc);
840 }
841 RB_VM_LOCK_LEAVE();
842}
843
844void
845rb_clear_all_refinement_method_cache(void)
846{
847 rb_vm_t *vm = GET_VM();
848
849 RB_VM_LOCK_ENTER();
850 {
851 struct cc_refinement_entries *e = RTYPEDDATA_GET_DATA(vm->cc_refinement_set);
852 for (size_t i = 0; i < e->len; i++) {
853 VALUE v = e->entries[i];
854
855 // All objects should be live as weak references are pruned in
856 // cc_refinement_set_handle_weak_references
857 VM_ASSERT(!rb_objspace_garbage_object_p(v));
858
859 const struct rb_callcache *cc = (const struct rb_callcache *)v;
860 VM_ASSERT(vm_cc_refinement_p(cc));
861
862 if (vm_cc_valid(cc)) {
863 vm_cc_invalidate(cc);
864 }
865 }
866 e->len = 0;
867 }
868 RB_VM_LOCK_LEAVE();
869
870 rb_yjit_invalidate_all_method_lookup_assumptions();
871}
872
873void
874rb_method_table_insert(VALUE klass, struct rb_id_table *table, ID method_id, const rb_method_entry_t *me)
875{
876 RB_VM_LOCKING() {
877 rb_method_table_insert0(klass, table, method_id, me, RB_TYPE_P(klass, T_ICLASS) && !RICLASS_OWNS_M_TBL_P(klass));
878 }
879}
880
881void
882rb_method_table_insert0(VALUE klass, struct rb_id_table *table, ID method_id, const rb_method_entry_t *me, bool iclass_shared_mtbl)
883{
884 VALUE table_owner = klass;
885 if (iclass_shared_mtbl) {
886 table_owner = RBASIC(table_owner)->klass;
887 }
888 VM_ASSERT_TYPE3(table_owner, T_CLASS, T_ICLASS, T_MODULE);
889 rb_id_table_insert(table, method_id, (VALUE)me);
890 RB_OBJ_WRITTEN(table_owner, Qundef, (VALUE)me);
891}
892
893// rb_f_notimplement has an extra trailing argument to distinguish it from other methods
894// at compile-time to override arity to be -1. But the trailing argument introduces a
895// signature mismatch between caller and callee, so rb_define_method family inserts a
896// method entry with rb_f_notimplement_internal, which has canonical arity=-1 signature,
897// instead of rb_f_notimplement.
898NORETURN(static VALUE rb_f_notimplement_internal(int argc, const VALUE *argv, VALUE obj));
899
900static VALUE
901rb_f_notimplement_internal(int argc, const VALUE *argv, VALUE obj)
902{
903 rb_notimplement();
904
906}
907
908VALUE
909rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
910{
911 rb_f_notimplement_internal(argc, argv, obj);
912}
913
914static void
915rb_define_notimplement_method_id(VALUE mod, ID id, rb_method_visibility_t visi)
916{
917 rb_add_method(mod, id, VM_METHOD_TYPE_NOTIMPLEMENTED, (void *)1, visi);
918}
919
920void
921rb_add_method_cfunc(VALUE klass, ID mid, VALUE (*func)(ANYARGS), int argc, rb_method_visibility_t visi)
922{
923 if (argc < -2 || 15 < argc) rb_raise(rb_eArgError, "arity out of range: %d for -2..15", argc);
924 if (func != (VALUE(*)(ANYARGS))rb_f_notimplement) {
926 opt.func = func;
927 opt.argc = argc;
928 rb_add_method(klass, mid, VM_METHOD_TYPE_CFUNC, &opt, visi);
929 }
930 else {
931 rb_define_notimplement_method_id(klass, mid, visi);
932 }
933}
934
935void
936rb_add_method_optimized(VALUE klass, ID mid, enum method_optimized_type opt_type, unsigned int index, rb_method_visibility_t visi)
937{
939 .type = opt_type,
940 .index = index,
941 };
942 rb_add_method(klass, mid, VM_METHOD_TYPE_OPTIMIZED, &opt, visi);
943}
944
945static void
946method_definition_release(rb_method_definition_t *def)
947{
948 if (def != NULL) {
949 const unsigned int reference_count_was = RUBY_ATOMIC_FETCH_SUB(def->reference_count, 1);
950
951 RUBY_ASSERT_ALWAYS(reference_count_was != 0);
952
953 if (reference_count_was == 1) {
954 if (METHOD_DEBUG) fprintf(stderr, "-%p-%s:1->0 (remove)\n", (void *)def,
955 rb_id2name(def->original_id));
956 SIZED_FREE(def);
957 }
958 else {
959 if (METHOD_DEBUG) fprintf(stderr, "-%p-%s:%d->%d (dec)\n", (void *)def, rb_id2name(def->original_id),
960 reference_count_was, reference_count_was - 1);
961 }
962 }
963}
964
965void
966rb_method_definition_release(rb_method_definition_t *def)
967{
968 method_definition_release(def);
969}
970
971static void delete_overloaded_cme(const rb_callable_method_entry_t *cme);
972
973void
974rb_free_method_entry_vm_weak_references(const rb_method_entry_t *me)
975{
976 if (me->def && me->def->iseq_overload) {
977 delete_overloaded_cme((const rb_callable_method_entry_t *)me);
978 }
979}
980
981void
982rb_free_method_entry(const rb_method_entry_t *me)
983{
984#if USE_ZJIT
985 if (METHOD_ENTRY_CACHED(me)) {
986 rb_zjit_cme_free((const rb_callable_method_entry_t *)me);
987 }
988#endif
989
990#if USE_YJIT
991 // YJIT rb_yjit_root_mark() roots CMEs in `Invariants`,
992 // to remove from `Invariants` here.
993#endif
994
995 method_definition_release(me->def);
996}
997
998static inline rb_method_entry_t *search_method(VALUE klass, ID id, VALUE *defined_class_ptr);
999extern int rb_method_definition_eq(const rb_method_definition_t *d1, const rb_method_definition_t *d2);
1000
1001static VALUE
1002(*call_cfunc_invoker_func(int argc))(VALUE recv, int argc, const VALUE *, VALUE (*func)(ANYARGS))
1003{
1004 if (!GET_THREAD()->ext_config.ractor_safe) {
1005 switch (argc) {
1006 case -2: return &call_cfunc_m2;
1007 case -1: return &call_cfunc_m1;
1008 case 0: return &call_cfunc_0;
1009 case 1: return &call_cfunc_1;
1010 case 2: return &call_cfunc_2;
1011 case 3: return &call_cfunc_3;
1012 case 4: return &call_cfunc_4;
1013 case 5: return &call_cfunc_5;
1014 case 6: return &call_cfunc_6;
1015 case 7: return &call_cfunc_7;
1016 case 8: return &call_cfunc_8;
1017 case 9: return &call_cfunc_9;
1018 case 10: return &call_cfunc_10;
1019 case 11: return &call_cfunc_11;
1020 case 12: return &call_cfunc_12;
1021 case 13: return &call_cfunc_13;
1022 case 14: return &call_cfunc_14;
1023 case 15: return &call_cfunc_15;
1024 default:
1025 rb_bug("unsupported length: %d", argc);
1026 }
1027 }
1028 else {
1029 switch (argc) {
1030 case -2: return &ractor_safe_call_cfunc_m2;
1031 case -1: return &ractor_safe_call_cfunc_m1;
1032 case 0: return &ractor_safe_call_cfunc_0;
1033 case 1: return &ractor_safe_call_cfunc_1;
1034 case 2: return &ractor_safe_call_cfunc_2;
1035 case 3: return &ractor_safe_call_cfunc_3;
1036 case 4: return &ractor_safe_call_cfunc_4;
1037 case 5: return &ractor_safe_call_cfunc_5;
1038 case 6: return &ractor_safe_call_cfunc_6;
1039 case 7: return &ractor_safe_call_cfunc_7;
1040 case 8: return &ractor_safe_call_cfunc_8;
1041 case 9: return &ractor_safe_call_cfunc_9;
1042 case 10: return &ractor_safe_call_cfunc_10;
1043 case 11: return &ractor_safe_call_cfunc_11;
1044 case 12: return &ractor_safe_call_cfunc_12;
1045 case 13: return &ractor_safe_call_cfunc_13;
1046 case 14: return &ractor_safe_call_cfunc_14;
1047 case 15: return &ractor_safe_call_cfunc_15;
1048 default:
1049 rb_bug("unsupported length: %d", argc);
1050 }
1051 }
1052}
1053
1054static void
1055setup_method_cfunc_struct(rb_method_cfunc_t *cfunc, VALUE (*func)(ANYARGS), int argc)
1056{
1057 cfunc->func = func;
1058 cfunc->argc = argc;
1059 cfunc->invoker = call_cfunc_invoker_func(argc);
1060}
1061
1062
1064method_definition_addref(rb_method_definition_t *def, bool complemented)
1065{
1066 unsigned int reference_count_was = RUBY_ATOMIC_FETCH_ADD(def->reference_count, 1);
1067 if (!complemented && reference_count_was > 0) {
1068 /* TODO: A Ractor can reach this via UnboundMethod#bind */
1069 def->aliased = true;
1070 }
1071 if (METHOD_DEBUG) fprintf(stderr, "+%p-%s:%d->%d\n", (void *)def, rb_id2name(def->original_id), reference_count_was, reference_count_was+1);
1072
1073 return def;
1074}
1075
1076void
1077rb_method_definition_addref(rb_method_definition_t *def)
1078{
1079 method_definition_addref(def, false);
1080}
1081
1082void
1083rb_method_definition_set(const rb_method_entry_t *me, rb_method_definition_t *def, void *opts)
1084{
1085 method_definition_release(me->def);
1086 *(rb_method_definition_t **)&me->def = method_definition_addref(def, METHOD_ENTRY_COMPLEMENTED(me));
1087
1088 if (!ruby_running) add_opt_method_entry(me);
1089
1090 if (opts != NULL) {
1091 switch (def->type) {
1092 case VM_METHOD_TYPE_ISEQ:
1093 {
1094 rb_method_iseq_t *iseq_body = (rb_method_iseq_t *)opts;
1095 const rb_iseq_t *iseq = iseq_body->iseqptr;
1096 rb_cref_t *method_cref, *cref = iseq_body->cref;
1097
1098 /* setup iseq first (before invoking GC) */
1099 RB_OBJ_WRITE(me, &def->body.iseq.iseqptr, iseq);
1100
1101 // Methods defined in `with_jit` should be considered METHOD_ENTRY_BASIC
1102 if (rb_iseq_attr_p(iseq, BUILTIN_ATTR_C_TRACE)) {
1103 METHOD_ENTRY_BASIC_SET((rb_method_entry_t *)me, TRUE);
1104 }
1105
1106 if (ISEQ_BODY(iseq)->mandatory_only_iseq) def->iseq_overload = 1;
1107
1108 if (0) vm_cref_dump("rb_method_definition_create", cref);
1109
1110 if (cref) {
1111 method_cref = cref;
1112 }
1113 else {
1114 method_cref = vm_cref_new_toplevel(GET_EC()); /* TODO: can we reuse? */
1115 }
1116
1117 RB_OBJ_WRITE(me, &def->body.iseq.cref, method_cref);
1118 return;
1119 }
1120 case VM_METHOD_TYPE_CFUNC:
1121 {
1122 rb_method_cfunc_t *cfunc = (rb_method_cfunc_t *)opts;
1123 setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), cfunc->func, cfunc->argc);
1124 return;
1125 }
1126 case VM_METHOD_TYPE_ATTRSET:
1127 case VM_METHOD_TYPE_IVAR:
1128 {
1129 const rb_execution_context_t *ec = GET_EC();
1130 rb_control_frame_t *cfp;
1131 int line;
1132
1133 def->body.attr.id = (ID)(VALUE)opts;
1134
1135 cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
1136
1137 if (cfp && (line = rb_vm_get_sourceline(cfp))) {
1138 VALUE location = rb_ary_new3(2, rb_iseq_path(CFP_ISEQ(cfp)), INT2FIX(line));
1139 rb_ary_freeze(location);
1140 RB_OBJ_SET_SHAREABLE(location);
1141 RB_OBJ_WRITE(me, &def->body.attr.location, location);
1142 }
1143 else {
1144 VM_ASSERT(def->body.attr.location == 0);
1145 }
1146 return;
1147 }
1148 case VM_METHOD_TYPE_BMETHOD:
1149 RB_OBJ_WRITE(me, &def->body.bmethod.proc, (VALUE)opts);
1150 def->body.bmethod.defined_ractor_id = rb_ec_ractor_id(GET_EC());
1151 return;
1152 case VM_METHOD_TYPE_NOTIMPLEMENTED:
1153 setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), (VALUE(*)(ANYARGS))rb_f_notimplement_internal, -1);
1154 return;
1155 case VM_METHOD_TYPE_OPTIMIZED:
1156 def->body.optimized = *(rb_method_optimized_t *)opts;
1157 return;
1158 case VM_METHOD_TYPE_REFINED:
1159 {
1160 const rb_method_entry_t *orig_me = (const rb_method_entry_t *)opts;
1161 RB_OBJ_WRITE(me, &def->body.refined.orig_me, orig_me);
1162 RB_OBJ_WRITE(me, &def->original_module, orig_me->def->original_module);
1163 return;
1164 }
1165 case VM_METHOD_TYPE_ALIAS:
1166 {
1167 const rb_method_entry_t *orig_me = (const rb_method_entry_t *)opts;
1168 RB_OBJ_WRITE(me, &def->body.alias.original_me, orig_me);
1169 RB_OBJ_WRITE(me, &def->original_module, orig_me->def->original_module);
1170 return;
1171 }
1172 case VM_METHOD_TYPE_ZSUPER:
1173 case VM_METHOD_TYPE_UNDEF:
1174 case VM_METHOD_TYPE_MISSING:
1175 return;
1176 }
1177 }
1178}
1179
1180static void
1181method_definition_reset(const rb_method_entry_t *me)
1182{
1183 rb_method_definition_t *def = me->def;
1184
1185 RB_OBJ_WRITTEN(me, Qundef, def->original_module);
1186
1187 switch (def->type) {
1188 case VM_METHOD_TYPE_ISEQ:
1189 RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.iseqptr);
1190 RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.cref);
1191 break;
1192 case VM_METHOD_TYPE_ATTRSET:
1193 case VM_METHOD_TYPE_IVAR:
1194 RB_OBJ_WRITTEN(me, Qundef, def->body.attr.location);
1195 break;
1196 case VM_METHOD_TYPE_BMETHOD:
1197 RB_OBJ_WRITTEN(me, Qundef, def->body.bmethod.proc);
1198 break;
1199 case VM_METHOD_TYPE_REFINED:
1200 RB_OBJ_WRITTEN(me, Qundef, def->body.refined.orig_me);
1201 break;
1202 case VM_METHOD_TYPE_ALIAS:
1203 RB_OBJ_WRITTEN(me, Qundef, def->body.alias.original_me);
1204 break;
1205 case VM_METHOD_TYPE_CFUNC:
1206 case VM_METHOD_TYPE_ZSUPER:
1207 case VM_METHOD_TYPE_MISSING:
1208 case VM_METHOD_TYPE_OPTIMIZED:
1209 case VM_METHOD_TYPE_UNDEF:
1210 case VM_METHOD_TYPE_NOTIMPLEMENTED:
1211 break;
1212 }
1213}
1214
1215static rb_atomic_t method_serial = 1;
1216
1218rb_method_definition_create(rb_method_type_t type, ID mid)
1219{
1222 def->type = type;
1223 def->original_id = mid;
1224 def->method_serial = (uintptr_t)RUBY_ATOMIC_FETCH_ADD(method_serial, 1);
1225 def->box = rb_current_box();
1226 return def;
1227}
1228
1229static rb_method_entry_t *
1230rb_method_entry_alloc(ID called_id, VALUE owner, VALUE defined_class, rb_method_definition_t *def, bool complement)
1231{
1232 if (def) method_definition_addref(def, complement);
1233 if (RTEST(defined_class)) {
1234 // not negative cache
1235 VM_ASSERT_TYPE2(defined_class, T_CLASS, T_ICLASS);
1236 }
1237 rb_method_entry_t *me = SHAREABLE_IMEMO_NEW(rb_method_entry_t, imemo_ment, defined_class);
1238
1239 // mark_and_move_method_entry pins itself when it is in the overloaded_cme table
1240 rb_gc_register_pinning_obj((VALUE)me);
1241
1242 *((rb_method_definition_t **)&me->def) = def;
1243 me->called_id = called_id;
1244 me->owner = owner;
1245
1246 return me;
1247}
1248
1249static VALUE
1250filter_defined_class(VALUE klass)
1251{
1252 switch (BUILTIN_TYPE(klass)) {
1253 case T_CLASS:
1254 return klass;
1255 case T_MODULE:
1256 return 0;
1257 case T_ICLASS:
1258 break;
1259 default:
1260 break;
1261 }
1262 rb_bug("filter_defined_class: %s", rb_obj_info(klass));
1263}
1264
1266rb_method_entry_create(ID called_id, VALUE klass, rb_method_visibility_t visi, rb_method_definition_t *def)
1267{
1268 rb_method_entry_t *me = rb_method_entry_alloc(called_id, klass, filter_defined_class(klass), def, false);
1269 METHOD_ENTRY_FLAGS_SET(me, visi, ruby_running ? FALSE : TRUE);
1270 if (def != NULL) method_definition_reset(me);
1271 return me;
1272}
1273
1274// Return a cloned ME that's not invalidated (MEs are disposable for caching).
1275const rb_method_entry_t *
1276rb_method_entry_clone(const rb_method_entry_t *src_me)
1277{
1278 rb_method_entry_t *me = rb_method_entry_alloc(src_me->called_id, src_me->owner, src_me->defined_class, src_me->def, METHOD_ENTRY_COMPLEMENTED(src_me));
1279
1280 METHOD_ENTRY_FLAGS_COPY(me, src_me);
1281
1282 // Also clone inner ME in case of refinement ME
1283 if (src_me->def &&
1284 src_me->def->type == VM_METHOD_TYPE_REFINED &&
1285 src_me->def->body.refined.orig_me) {
1286 const rb_method_entry_t *orig_me = src_me->def->body.refined.orig_me;
1287 VM_ASSERT(orig_me->def->type != VM_METHOD_TYPE_REFINED);
1288
1289 rb_method_entry_t *orig_clone = rb_method_entry_alloc(orig_me->called_id,
1290 orig_me->owner, orig_me->defined_class, orig_me->def, METHOD_ENTRY_COMPLEMENTED(orig_me));
1291 METHOD_ENTRY_FLAGS_COPY(orig_clone, orig_me);
1292
1293 // Clone definition, since writing a VALUE to a shared definition
1294 // can create reference edges we can't run WBs for.
1295 rb_method_definition_t *clone_def =
1296 rb_method_definition_create(VM_METHOD_TYPE_REFINED, src_me->called_id);
1297 rb_method_definition_set(me, clone_def, orig_clone);
1298 }
1299 return me;
1300}
1301
1303rb_method_entry_complement_defined_class(const rb_method_entry_t *src_me, ID called_id, VALUE defined_class)
1304{
1305 rb_method_definition_t *def = src_me->def;
1307 const rb_method_entry_t *refined_orig_me = NULL;
1308
1309 if (!src_me->defined_class &&
1310 def->type == VM_METHOD_TYPE_REFINED &&
1311 def->body.refined.orig_me) {
1312 const rb_method_entry_t *orig_me =
1313 rb_method_entry_clone(def->body.refined.orig_me);
1314 RB_OBJ_WRITE((VALUE)orig_me, &orig_me->defined_class, defined_class);
1315 refined_orig_me = orig_me;
1316 def = NULL;
1317 }
1318
1319 me = rb_method_entry_alloc(called_id, src_me->owner, defined_class, def, true);
1320 METHOD_ENTRY_FLAGS_COPY(me, src_me);
1321 METHOD_ENTRY_COMPLEMENTED_SET(me);
1322 if (!def) {
1323 def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, called_id);
1324 rb_method_definition_set(me, def, (void *)refined_orig_me);
1325 }
1326
1327 VM_ASSERT_TYPE(me->owner, T_MODULE);
1328
1329 return (rb_callable_method_entry_t *)me;
1330}
1331
1332void
1333rb_method_entry_copy(rb_method_entry_t *dst, const rb_method_entry_t *src)
1334{
1335 method_definition_release(dst->def);
1336 *(rb_method_definition_t **)&dst->def = method_definition_addref(src->def, METHOD_ENTRY_COMPLEMENTED(src));
1337 method_definition_reset(dst);
1338 dst->called_id = src->called_id;
1339 RB_OBJ_WRITE((VALUE)dst, &dst->owner, src->owner);
1340 RB_OBJ_WRITE((VALUE)dst, &dst->defined_class, src->defined_class);
1341 METHOD_ENTRY_FLAGS_COPY(dst, src);
1342}
1343
1344static void
1345make_method_entry_refined(VALUE owner, rb_method_entry_t *me)
1346{
1347 if (me->def->type == VM_METHOD_TYPE_REFINED) {
1348 return;
1349 }
1350 else {
1352
1353 rb_vm_check_redefinition_opt_method(me, me->owner);
1354
1355 struct rb_method_entry_struct *orig_me =
1356 rb_method_entry_alloc(me->called_id,
1357 me->owner,
1358 me->defined_class,
1359 me->def,
1360 true);
1361 METHOD_ENTRY_FLAGS_COPY(orig_me, me);
1362
1363 def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, me->called_id);
1364 rb_method_definition_set(me, def, orig_me);
1365 METHOD_ENTRY_VISI_SET(me, METHOD_VISI_PUBLIC);
1366 }
1367}
1368
1369static inline rb_method_entry_t *
1370lookup_method_table(VALUE klass, ID id)
1371{
1372 st_data_t body;
1373 struct rb_id_table *m_tbl = RCLASS_M_TBL(klass);
1374
1375 if (rb_id_table_lookup(m_tbl, id, &body)) {
1376 return (rb_method_entry_t *) body;
1377 }
1378 else {
1379 return 0;
1380 }
1381}
1382
1383void
1384rb_add_refined_method_entry(VALUE refined_class, ID mid)
1385{
1386 rb_method_entry_t *me = lookup_method_table(refined_class, mid);
1387
1388 if (me) {
1389 make_method_entry_refined(refined_class, me);
1390 rb_clear_method_cache(refined_class, mid);
1391 }
1392 else {
1393 rb_add_method(refined_class, mid, VM_METHOD_TYPE_REFINED, 0, METHOD_VISI_PUBLIC);
1394 }
1395}
1396
1397static void
1398check_override_opt_method_i(VALUE klass, VALUE arg)
1399{
1400 if (RB_TYPE_P(klass, T_ICLASS)) {
1401 // ICLASS from a module's subclass list: check the includer and
1402 // recurse into the includer's T_CLASS subclasses.
1403 VALUE includer = RCLASS_INCLUDER(klass);
1404 if (!UNDEF_P(includer) && includer) {
1405 check_override_opt_method_i(includer, arg);
1406 }
1407 return;
1408 }
1409
1410 ID mid = (ID)arg;
1411 const rb_method_entry_t *me, *newme;
1412
1413 if (vm_redefinition_check_flag(klass)) {
1414 me = lookup_method_table(RCLASS_ORIGIN(klass), mid);
1415 if (me) {
1416 newme = rb_method_entry(klass, mid);
1417 if (newme != me) rb_vm_check_redefinition_opt_method(me, me->owner);
1418 }
1419 }
1420 rb_class_foreach_subclass(klass, check_override_opt_method_i, (VALUE)mid);
1421}
1422
1423static void
1424check_override_opt_method(VALUE klass, VALUE mid)
1425{
1426 if (rb_vm_check_optimizable_mid(mid)) {
1427 check_override_opt_method_i(klass, mid);
1428 }
1429}
1430
1431VALUE
1432rb_zsuper_to_super(int argc, VALUE *argv, VALUE self)
1433{
1434 return rb_call_super_kw(argc, argv, RB_PASS_CALLED_KEYWORDS);
1435}
1436
1437static inline rb_method_entry_t* search_method0(VALUE klass, ID id, VALUE *defined_class_ptr, bool skip_refined);
1438static void
1439method_entry_modify_check(VALUE klass, rb_method_type_t type)
1440{
1441 ASSERT_vm_unlocking();
1442 if (type != VM_METHOD_TYPE_REFINED) {
1443 rb_class_modify_check(NIL_P(klass) ? rb_cObject : klass);
1444 }
1445}
1446
1447/* rb_method_entry_make() runs under the VM lock, where it must not warn:
1448 * rb_warn() dispatches Warning.warn and writes to $stderr, either of which can
1449 * check for interrupts. It formats the message instead, and the caller emits
1450 * it once the lock is released. */
1452 VALUE redefined; /* $VERBOSE only */
1453 VALUE problem;
1454};
1455
1456static void
1457method_entry_warnings_emit(const struct method_entry_warnings *warnings)
1458{
1459 if (warnings->redefined) rb_warning("%"PRIsVALUE, warnings->redefined);
1460 if (warnings->problem) rb_warn("%"PRIsVALUE, warnings->problem);
1461}
1462
1463/*
1464 * klass->method_table[mid] = method_entry(defined_class, visi, def)
1465 *
1466 * If def is given (!= NULL), then just use it and ignore original_id and otps.
1467 * If not given, then make a new def with original_id and opts.
1468 */
1469static rb_method_entry_t *
1470rb_method_entry_make(VALUE klass, ID mid, VALUE defined_class, rb_method_visibility_t visi,
1471 rb_method_type_t type, rb_method_definition_t *def, ID original_id, void *opts,
1472 struct method_entry_warnings *warnings)
1473{
1475 struct rb_id_table *mtbl;
1476 st_data_t data;
1477 int make_refined = 0;
1478 VALUE orig_klass;
1479 bool turn_zsuper_to_super = false;
1480
1481 if (NIL_P(klass)) {
1482 klass = rb_cObject;
1483 }
1484 orig_klass = klass;
1485
1486 if (!RCLASS_SINGLETON_P(klass) &&
1487 type != VM_METHOD_TYPE_NOTIMPLEMENTED &&
1488 type != VM_METHOD_TYPE_ZSUPER) {
1489 switch (mid) {
1490 case idInitialize:
1491 case idInitialize_copy:
1492 case idInitialize_clone:
1493 case idInitialize_dup:
1494 case idRespond_to_missing:
1495 visi = METHOD_VISI_PRIVATE;
1496 }
1497 }
1498
1499 if (RB_TYPE_P(klass, T_MODULE) && FL_TEST(klass, RMODULE_IS_REFINEMENT)) {
1500 VALUE refined_class = rb_refinement_module_get_refined_class(klass);
1501 if (type == VM_METHOD_TYPE_ZSUPER) {
1502 turn_zsuper_to_super = true;
1503 }
1504 rb_add_refined_method_entry(refined_class, mid);
1505 }
1506 if (type == VM_METHOD_TYPE_REFINED) {
1507 rb_method_entry_t *old_me = lookup_method_table(RCLASS_ORIGIN(klass), mid);
1508 if (old_me) rb_vm_check_redefinition_opt_method(old_me, klass);
1509 }
1510 else {
1511 klass = RCLASS_ORIGIN(klass);
1512 if (klass != orig_klass) {
1513 rb_clear_method_cache(orig_klass, mid);
1514 }
1515 }
1516 mtbl = RCLASS_WRITABLE_M_TBL(klass);
1517
1518 /* check re-definition */
1519 if (rb_id_table_lookup(mtbl, mid, &data)) {
1520 rb_method_entry_t *old_me = (rb_method_entry_t *)data;
1521 rb_method_definition_t *old_def = old_me->def;
1522
1523 if (rb_method_definition_eq(old_def, def)) return old_me;
1524 rb_vm_check_redefinition_opt_method(old_me, klass);
1525
1526 if (old_def->type == VM_METHOD_TYPE_REFINED) make_refined = 1;
1527
1528 if (RTEST(ruby_verbose) &&
1529 type != VM_METHOD_TYPE_UNDEF &&
1530 (old_def->aliased == false) &&
1531 (!old_def->no_redef_warning) &&
1532 !make_refined &&
1533 old_def->type != VM_METHOD_TYPE_UNDEF &&
1534 old_def->type != VM_METHOD_TYPE_ZSUPER &&
1535 old_def->type != VM_METHOD_TYPE_ALIAS) {
1536 const rb_iseq_t *iseq = 0;
1537
1538 switch (old_def->type) {
1539 case VM_METHOD_TYPE_ISEQ:
1540 iseq = def_iseq_ptr(old_def);
1541 break;
1542 case VM_METHOD_TYPE_BMETHOD:
1543 iseq = rb_proc_get_iseq(old_def->body.bmethod.proc, 0);
1544 break;
1545 default:
1546 break;
1547 }
1548 if (iseq) {
1549 warnings->redefined = rb_sprintf(
1550 "method redefined; discarding old %"PRIsVALUE"\n%"PRIsVALUE":%d: warning: previous definition of %"PRIsVALUE" was here",
1551 rb_id2str(mid),
1552 rb_iseq_path(iseq),
1553 ISEQ_BODY(iseq)->location.first_lineno,
1554 rb_id2str(old_def->original_id)
1555 );
1556 }
1557 else {
1558 warnings->redefined = rb_sprintf("method redefined; discarding old %"PRIsVALUE, rb_id2str(mid));
1559 }
1560 }
1561 }
1562
1563 /* create method entry */
1564 me = rb_method_entry_create(mid, defined_class, visi, NULL);
1565 if (def == NULL) {
1566 def = rb_method_definition_create(type, original_id);
1567 if (turn_zsuper_to_super) {
1568 def->type = VM_METHOD_TYPE_CFUNC;
1569 def->body.cfunc.func = (rb_cfunc_t)rb_zsuper_to_super;
1570 def->body.cfunc.invoker = ractor_safe_call_cfunc_m1;
1571 def->body.cfunc.argc = -1;
1572 }
1573 RB_OBJ_WRITE(me, &def->original_module, me->owner);
1574 }
1575 rb_method_definition_set(me, def, opts);
1576
1577 rb_clear_method_cache(klass, mid);
1578
1579 /* check mid */
1580 if (klass == rb_cObject) {
1581 switch (mid) {
1582 case idInitialize:
1583 case idRespond_to_missing:
1584 case idMethodMissing:
1585 case idRespond_to:
1586 warnings->problem = rb_sprintf("redefining Object#%s may cause infinite loop", rb_id2name(mid));
1587 }
1588 }
1589 /* check mid */
1590 if (mid == object_id || mid == id__id__ || mid == id__send__) {
1591 if (type != VM_METHOD_TYPE_CFUNC && search_method(klass, mid, 0)) {
1592 warnings->problem = rb_sprintf("redefining '%s' may cause serious problems", rb_id2name(mid));
1593 }
1594 }
1595
1596 if (make_refined) {
1597 make_method_entry_refined(klass, me);
1598 }
1599
1600 rb_method_table_insert(klass, mtbl, mid, me);
1601
1602 VM_ASSERT(me->def != NULL);
1603
1604 /* check optimized method override by a prepended module */
1605 if (RB_TYPE_P(orig_klass, T_MODULE)) {
1606 check_override_opt_method(klass, (VALUE)mid);
1607 }
1608
1609 return me;
1610}
1611
1612static st_table *
1613overloaded_cme_table(void)
1614{
1615 return &GET_VM()->overloaded_cme_table;
1616}
1617
1618#if VM_CHECK_MODE > 0
1619static int
1620vm_dump_overloaded_cme_table(st_data_t key, st_data_t val, st_data_t dmy)
1621{
1622 fprintf(stderr, "key: "); rp(key);
1623 fprintf(stderr, "val: "); rp(val);
1624 return ST_CONTINUE;
1625}
1626
1627void
1628rb_vm_dump_overloaded_cme_table(void)
1629{
1630 fprintf(stderr, "== rb_vm_dump_overloaded_cme_table\n");
1631 st_foreach(overloaded_cme_table(), vm_dump_overloaded_cme_table, 0);
1632}
1633#endif
1634
1635static int
1636lookup_overloaded_cme_i(st_data_t *key, st_data_t *value, st_data_t data, int existing)
1637{
1638 if (existing) {
1639 const rb_callable_method_entry_t *cme = (const rb_callable_method_entry_t *)*key;
1640 const rb_callable_method_entry_t *monly_cme = (const rb_callable_method_entry_t *)*value;
1641 const rb_callable_method_entry_t **ptr = (const rb_callable_method_entry_t **)data;
1642
1643 if (rb_objspace_garbage_object_p((VALUE)cme) ||
1644 rb_objspace_garbage_object_p((VALUE)monly_cme)) {
1645 *ptr = NULL;
1646 return ST_DELETE;
1647 }
1648 else {
1649 *ptr = monly_cme;
1650 }
1651 }
1652
1653 return ST_STOP;
1654}
1655
1656static const rb_callable_method_entry_t *
1657lookup_overloaded_cme(const rb_callable_method_entry_t *cme)
1658{
1659 ASSERT_vm_locking();
1660
1661 const rb_callable_method_entry_t *monly_cme = NULL;
1662 st_update(overloaded_cme_table(), (st_data_t)cme, lookup_overloaded_cme_i, (st_data_t)&monly_cme);
1663 return monly_cme;
1664}
1665
1666#if VM_CHECK_MODE > 0
1668rb_vm_lookup_overloaded_cme(const rb_callable_method_entry_t *cme)
1669{
1670 return lookup_overloaded_cme(cme);
1671}
1672#endif
1673
1674static void
1675delete_overloaded_cme(const rb_callable_method_entry_t *cme)
1676{
1677 st_data_t cme_data = (st_data_t)cme;
1678 ASSERT_vm_locking();
1679 st_delete(overloaded_cme_table(), &cme_data, NULL);
1680}
1681
1682static const rb_callable_method_entry_t *
1683get_overloaded_cme(const rb_callable_method_entry_t *cme)
1684{
1685 const rb_callable_method_entry_t *monly_cme = lookup_overloaded_cme(cme);
1686
1687 if (monly_cme && !METHOD_ENTRY_INVALIDATED(monly_cme)) {
1688 return monly_cme;
1689 }
1690 else {
1691 // create
1692 rb_method_definition_t *def = rb_method_definition_create(VM_METHOD_TYPE_ISEQ, cme->def->original_id);
1693 rb_method_entry_t *me = rb_method_entry_alloc(cme->called_id,
1694 cme->owner,
1695 cme->defined_class,
1696 def,
1697 false);
1698
1699 RB_OBJ_WRITE(me, &def->body.iseq.cref, cme->def->body.iseq.cref);
1700 RB_OBJ_WRITE(me, &def->body.iseq.iseqptr, ISEQ_BODY(cme->def->body.iseq.iseqptr)->mandatory_only_iseq);
1701 RB_OBJ_WRITE(me, &def->original_module, cme->def->original_module);
1702
1703 ASSERT_vm_locking();
1704 st_insert(overloaded_cme_table(), (st_data_t)cme, (st_data_t)me);
1705
1706 METHOD_ENTRY_VISI_SET(me, METHOD_ENTRY_VISI(cme));
1707 return (rb_callable_method_entry_t *)me;
1708 }
1709}
1710
1712rb_check_overloaded_cme(const rb_callable_method_entry_t *cme, const struct rb_callinfo * const ci)
1713{
1714 if (UNLIKELY(cme->def->iseq_overload) &&
1715 (vm_ci_flag(ci) & (VM_CALL_ARGS_SIMPLE)) &&
1716 (!(vm_ci_flag(ci) & VM_CALL_FORWARDING)) &&
1717 (int)vm_ci_argc(ci) == ISEQ_BODY(method_entry_iseqptr(cme))->param.lead_num) {
1718 VM_ASSERT(cme->def->type == VM_METHOD_TYPE_ISEQ, "type: %d", cme->def->type); // iseq_overload is marked only on ISEQ methods
1719
1720 cme = get_overloaded_cme(cme);
1721
1722 VM_ASSERT(cme != NULL);
1723 METHOD_ENTRY_CACHED_SET((struct rb_callable_method_entry_struct *)cme);
1724 }
1725
1726 return cme;
1727}
1728
1729static inline void stack_check(rb_execution_context_t *ec);
1730
1731#define CALL_METHOD_HOOK(klass, hook, mid) do { \
1732 const VALUE arg = ID2SYM(mid); \
1733 VALUE recv_class = (klass); \
1734 ID hook_id = (hook); \
1735 if (RCLASS_SINGLETON_P((klass))) { \
1736 recv_class = RCLASS_ATTACHED_OBJECT((klass)); \
1737 hook_id = singleton_##hook; \
1738 } \
1739 rb_funcallv_uncached(recv_class, hook_id, 1, &arg); \
1740 } while (0)
1741
1742static void
1743method_added(VALUE klass, ID mid, const rb_method_entry_t *me)
1744{
1745 if (ruby_running) {
1746 /* [Bug #22179] Record the just-defined method entry for method coverage
1747 * so the result no longer depends on walking the heap (and thus on GC
1748 * timing). */
1749 if (me) rb_vm_coverage_record_me(me);
1750 CALL_METHOD_HOOK(klass, added, mid);
1751 }
1752}
1753
1754void
1755rb_add_method(VALUE klass, ID mid, rb_method_type_t type, void *opts, rb_method_visibility_t visi)
1756{
1757 const rb_method_entry_t *me;
1758 struct method_entry_warnings warnings = {0};
1759
1760 method_entry_modify_check(klass, type);
1761
1762 RB_VM_LOCKING() {
1763 me = rb_method_entry_make(klass, mid, klass, visi, type, NULL, mid, opts, &warnings);
1764 }
1765
1766 method_entry_warnings_emit(&warnings);
1767
1768 if (type != VM_METHOD_TYPE_UNDEF && type != VM_METHOD_TYPE_REFINED) {
1769 method_added(klass, mid, me);
1770 }
1771}
1772
1773void
1774rb_add_method_iseq(VALUE klass, ID mid, const rb_iseq_t *iseq, rb_cref_t *cref, rb_method_visibility_t visi)
1775{
1776 struct { /* should be same fields with rb_method_iseq_struct */
1777 const rb_iseq_t *iseqptr;
1778 rb_cref_t *cref;
1779 } iseq_body;
1780
1781 iseq_body.iseqptr = iseq;
1782 iseq_body.cref = cref;
1783
1784 rb_add_method(klass, mid, VM_METHOD_TYPE_ISEQ, &iseq_body, visi);
1785}
1786
1787static rb_method_entry_t *
1788method_entry_set(VALUE klass, ID mid, const rb_method_entry_t *me,
1789 rb_method_visibility_t visi, VALUE defined_class)
1790{
1791 rb_method_entry_t *newme;
1792 struct method_entry_warnings warnings = {0};
1793
1794 method_entry_modify_check(klass, me->def->type);
1795
1796 RB_VM_LOCKING() {
1797 newme = rb_method_entry_make(klass, mid, defined_class, visi,
1798 me->def->type, me->def, 0, NULL, &warnings);
1799 if (newme == me) {
1800 me->def->no_redef_warning = TRUE;
1801 METHOD_ENTRY_FLAGS_SET(newme, visi, FALSE);
1802 }
1803 }
1804
1805 method_entry_warnings_emit(&warnings);
1806
1807 method_added(klass, mid, newme);
1808 return newme;
1809}
1810
1812rb_method_entry_set(VALUE klass, ID mid, const rb_method_entry_t *me, rb_method_visibility_t visi)
1813{
1814 return method_entry_set(klass, mid, me, visi, klass);
1815}
1816
1817#define UNDEF_ALLOC_FUNC ((rb_alloc_func_t)-1)
1818
1819static void
1820propagate_alloc_func(VALUE subclass, VALUE arg)
1821{
1822 if (RB_TYPE_P(subclass, T_CLASS) &&
1823 !RCLASS_SINGLETON_P(subclass) &&
1824 !FL_TEST_RAW(subclass, RCLASS_ALLOCATOR_DEFINED)) {
1825 RCLASS_SET_ALLOCATOR(subclass, (rb_alloc_func_t)arg);
1826 rb_class_foreach_subclass(subclass, propagate_alloc_func, arg);
1827 }
1828}
1829
1830void
1831rb_define_alloc_func(VALUE klass, VALUE (*func)(VALUE))
1832{
1833 Check_Type(klass, T_CLASS);
1834 if (RCLASS_SINGLETON_P(klass)) {
1835 rb_raise(rb_eTypeError, "can't define an allocator for a singleton class");
1836 }
1837 RCLASS_SET_ALLOCATOR(klass, func);
1838 FL_SET_RAW(klass, RCLASS_ALLOCATOR_DEFINED);
1839 rb_class_foreach_subclass(klass, propagate_alloc_func, (VALUE)func);
1840}
1841
1842void
1844{
1845 Check_Type(klass, T_CLASS);
1846 RCLASS_SET_ALLOCATOR(klass, UNDEF_ALLOC_FUNC);
1847 FL_SET_RAW(klass, RCLASS_ALLOCATOR_DEFINED);
1848 rb_class_foreach_subclass(klass, propagate_alloc_func, (VALUE)UNDEF_ALLOC_FUNC);
1849}
1850
1853{
1854 RBIMPL_ASSERT_TYPE(klass, T_CLASS);
1855
1856 rb_alloc_func_t allocator = RCLASS_ALLOCATOR(klass);
1857 if (allocator == UNDEF_ALLOC_FUNC) return 0;
1858 RUBY_ASSERT(allocator);
1859 return allocator;
1860}
1861
1862const rb_method_entry_t *
1863rb_method_entry_at(VALUE klass, ID id)
1864{
1865 return lookup_method_table(klass, id);
1866}
1867
1868static inline rb_method_entry_t*
1869search_method0(VALUE klass, ID id, VALUE *defined_class_ptr, bool skip_refined)
1870{
1871 rb_method_entry_t *me = NULL;
1872
1873 RB_DEBUG_COUNTER_INC(mc_search);
1874
1875 for (; klass; klass = RCLASS_SUPER(klass)) {
1876 RB_DEBUG_COUNTER_INC(mc_search_super);
1877 if ((me = lookup_method_table(klass, id)) != 0) {
1878 if (!skip_refined || me->def->type != VM_METHOD_TYPE_REFINED ||
1879 me->def->body.refined.orig_me) {
1880 break;
1881 }
1882 }
1883 }
1884
1885 if (defined_class_ptr) *defined_class_ptr = klass;
1886
1887 if (me == NULL) RB_DEBUG_COUNTER_INC(mc_search_notfound);
1888
1889 VM_ASSERT(me == NULL || !METHOD_ENTRY_INVALIDATED(me),
1890 "invalid me, mid:%s, klass:%"PRIsVALUE"(%s)",
1891 rb_id2name(id),
1892 RTEST(rb_mod_name(klass)) ? rb_mod_name(klass) : rb_str_new_lit("anonymous"),
1893 rb_obj_info(klass));
1894 return me;
1895}
1896
1897static inline rb_method_entry_t*
1898search_method(VALUE klass, ID id, VALUE *defined_class_ptr)
1899{
1900 return search_method0(klass, id, defined_class_ptr, false);
1901}
1902
1903static rb_method_entry_t *
1904search_method_protect(VALUE klass, ID id, VALUE *defined_class_ptr)
1905{
1906 rb_method_entry_t *me = search_method(klass, id, defined_class_ptr);
1907
1908 if (!UNDEFINED_METHOD_ENTRY_P(me)) {
1909 return me;
1910 }
1911 else {
1912 return NULL;
1913 }
1914}
1915
1916const rb_method_entry_t *
1917rb_method_entry(VALUE klass, ID id)
1918{
1919 return search_method_protect(klass, id, NULL);
1920}
1921
1922static inline const rb_callable_method_entry_t *
1923prepare_callable_method_entry(VALUE defined_class, ID id, const rb_method_entry_t * const me, int create)
1924{
1925 struct rb_id_table *mtbl;
1926 const rb_callable_method_entry_t *cme;
1927 VALUE cme_data;
1928 int cme_found = 0;
1929
1930 if (me) {
1931 if (me->defined_class == 0) {
1932 RB_DEBUG_COUNTER_INC(mc_cme_complement);
1933 VM_ASSERT_TYPE2(defined_class, T_ICLASS, T_MODULE);
1934
1935 mtbl = RCLASS_WRITABLE_CALLABLE_M_TBL(defined_class);
1936 if (mtbl && rb_id_table_lookup(mtbl, id, &cme_data)) {
1937 cme = (rb_callable_method_entry_t *)cme_data;
1938 cme_found = 1;
1939 }
1940 if (cme_found) {
1941 RB_DEBUG_COUNTER_INC(mc_cme_complement_hit);
1942 VM_ASSERT(callable_method_entry_p(cme));
1943 VM_ASSERT(!METHOD_ENTRY_INVALIDATED(cme));
1944 }
1945 else if (create) {
1946 if (!mtbl) {
1947 mtbl = rb_id_table_create(0);
1948 RCLASS_WRITE_CALLABLE_M_TBL(defined_class, mtbl);
1949 }
1950 cme = rb_method_entry_complement_defined_class(me, me->called_id, defined_class);
1951 rb_id_table_insert(mtbl, id, (VALUE)cme);
1952 RB_OBJ_WRITTEN(defined_class, Qundef, (VALUE)cme);
1953 VM_ASSERT(callable_method_entry_p(cme));
1954 }
1955 else {
1956 return NULL;
1957 }
1958 }
1959 else {
1960 cme = (const rb_callable_method_entry_t *)me;
1961 VM_ASSERT(callable_method_entry_p(cme));
1962 VM_ASSERT(!METHOD_ENTRY_INVALIDATED(cme));
1963 }
1964 return cme;
1965 }
1966 else {
1967 return NULL;
1968 }
1969}
1970
1971/* A hook like this fires from C with no call site to cache into except for the gccct table,
1972 * which is often cleared anyway. It would leave a permanent CC behind (tied to the class) if it
1973 * created one, so we try to avoid it. */
1974VALUE
1975rb_funcallv_uncached(VALUE recv, ID mid, int argc, const VALUE *argv)
1976{
1977 VALUE defined_class;
1978 const rb_method_entry_t *me = search_method(CLASS_OF(recv), mid, &defined_class);
1979
1980 if (UNLIKELY(UNDEFINED_METHOD_ENTRY_P(me))) {
1981 return rb_funcallv(recv, mid, argc, argv);
1982 }
1983
1984 const rb_callable_method_entry_t *cme;
1985
1986 if (UNLIKELY(me->defined_class == 0)) {
1987 // produce a transient CME that will get collected
1988 cme = rb_method_entry_complement_defined_class(me, me->called_id, defined_class);
1989 }
1990 else {
1991 cme = (const rb_callable_method_entry_t *)me;
1992 }
1993
1994 rb_execution_context_t *ec = GET_EC();
1995 stack_check(ec);
1996 return rb_vm_call_kw(ec, recv, mid, argc, argv, cme, RB_NO_KEYWORDS);
1997}
1998
1999static const rb_callable_method_entry_t *
2000complemented_callable_method_entry(VALUE klass, ID id)
2001{
2002 VALUE defined_class;
2003 rb_method_entry_t *me = search_method(klass, id, &defined_class);
2004 return prepare_callable_method_entry(defined_class, id, me, FALSE);
2005}
2006
2007static const rb_callable_method_entry_t *
2008cached_callable_method_entry(VALUE klass, ID mid)
2009{
2010 ASSERT_vm_locking();
2011
2012 VALUE cc_tbl = RCLASS_WRITABLE_CC_TBL(klass);
2013 VALUE ccs_data;
2014
2015 if (cc_tbl && rb_managed_id_table_lookup(cc_tbl, mid, &ccs_data)) {
2016 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_data;
2017 VM_ASSERT(vm_ccs_p(ccs));
2018
2019 if (LIKELY(!METHOD_ENTRY_INVALIDATED(ccs->cme))) {
2020 VM_ASSERT(ccs->cme->called_id == mid);
2021 RB_DEBUG_COUNTER_INC(ccs_found);
2022 return ccs->cme;
2023 }
2024 else {
2025 rb_vm_barrier();
2026
2027 rb_managed_id_table_delete(cc_tbl, mid);
2028 rb_vm_ccs_invalidate_and_free(ccs);
2029 }
2030 }
2031
2032 RB_DEBUG_COUNTER_INC(ccs_not_found);
2033 return NULL;
2034}
2035
2036static void
2037cache_callable_method_entry(VALUE klass, ID mid, const rb_callable_method_entry_t *cme)
2038{
2039 ASSERT_vm_locking();
2040 VM_ASSERT(cme != NULL);
2041
2042 VALUE cc_tbl = RCLASS_WRITABLE_CC_TBL(klass);
2043 VALUE ccs_data;
2044
2045 if (!cc_tbl) {
2046 cc_tbl = rb_vm_cc_table_create(2);
2047 RCLASS_WRITE_CC_TBL(klass, cc_tbl);
2048 }
2049
2050 if (rb_managed_id_table_lookup(cc_tbl, mid, &ccs_data)) {
2051#if VM_CHECK_MODE > 0
2052 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_data;
2053 VM_ASSERT(ccs->cme == cme);
2054#endif
2055 }
2056 else {
2057 if (rb_multi_ractor_p()) {
2058 VALUE new_cc_tbl = rb_vm_cc_table_dup(cc_tbl);
2059 vm_ccs_create(klass, new_cc_tbl, mid, cme);
2060 RB_OBJ_ATOMIC_WRITE(klass, &RCLASSEXT_CC_TBL(RCLASS_EXT_WRITABLE(klass)), new_cc_tbl);
2061 }
2062 else {
2063 vm_ccs_create(klass, cc_tbl, mid, cme);
2064 }
2065 }
2066}
2067
2068static const rb_callable_method_entry_t *
2069negative_cme(ID mid)
2070{
2071 rb_vm_t *vm = GET_VM();
2072 const rb_callable_method_entry_t *cme;
2073 VALUE cme_data;
2074
2075 if (rb_id_table_lookup(&vm->negative_cme_table, mid, &cme_data)) {
2076 cme = (rb_callable_method_entry_t *)cme_data;
2077 }
2078 else {
2079 cme = (rb_callable_method_entry_t *)rb_method_entry_alloc(mid, Qnil, Qnil, NULL, false);
2080 rb_id_table_insert(&vm->negative_cme_table, mid, (VALUE)cme);
2081 }
2082
2083 VM_ASSERT(cme != NULL);
2084 return cme;
2085}
2086
2087static const rb_callable_method_entry_t *
2088callable_method_entry_or_negative(VALUE klass, ID mid, VALUE *defined_class_ptr)
2089{
2090 const rb_callable_method_entry_t *cme;
2091
2092 VM_ASSERT(!SPECIAL_CONST_P(klass));
2093
2094 if (RB_BUILTIN_TYPE(klass) == T_NONE) {
2095 // If we find a T_NONE here, it's most likely we called CLASS_OF(obj) on a
2096 // garbage collected object (the freelist is stored in the class pointer),
2097 // but it's possible that just the class was GC'd.
2098 // This message intentionally tries to imply the former, but make an
2099 // accurate statement for either case.
2100 rb_bug("attempted to search method '%s' on a garbage collected object",
2101 rb_id2name(mid));
2102 }
2103
2104 VM_ASSERT_TYPE2(klass, T_CLASS, T_ICLASS);
2105
2106 /* Fast path: lock-free read from cache */
2107 VALUE cc_tbl = RUBY_ATOMIC_VALUE_LOAD(RCLASS_WRITABLE_CC_TBL(klass));
2108 if (cc_tbl) {
2109 VALUE ccs_data;
2110 if (rb_managed_id_table_lookup(cc_tbl, mid, &ccs_data)) {
2111 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_data;
2112 VM_ASSERT(vm_ccs_p(ccs));
2113
2114 if (LIKELY(!METHOD_ENTRY_INVALIDATED(ccs->cme))) {
2115 VM_ASSERT(ccs->cme->called_id == mid);
2116 if (defined_class_ptr != NULL) *defined_class_ptr = ccs->cme->defined_class;
2117 RB_DEBUG_COUNTER_INC(ccs_found);
2118 return ccs->cme;
2119 }
2120 }
2121 }
2122
2123 /* Slow path: need to lock and potentially populate cache */
2124 RB_VM_LOCKING() {
2125 cme = cached_callable_method_entry(klass, mid);
2126
2127 if (cme) {
2128 if (defined_class_ptr != NULL) *defined_class_ptr = cme->defined_class;
2129 }
2130 else {
2131 VALUE defined_class;
2132 rb_method_entry_t *me = search_method(klass, mid, &defined_class);
2133 if (defined_class_ptr) *defined_class_ptr = defined_class;
2134
2135 if (me != NULL) {
2136 cme = prepare_callable_method_entry(defined_class, mid, me, TRUE);
2137 }
2138 else {
2139 cme = negative_cme(mid);
2140 }
2141
2142 cache_callable_method_entry(klass, mid, cme);
2143 }
2144 }
2145
2146 return cme;
2147}
2148
2149// This is exposed for YJIT so that we can make assumptions that methods are
2150// not defined.
2152rb_callable_method_entry_or_negative(VALUE klass, ID mid)
2153{
2154 return callable_method_entry_or_negative(klass, mid, NULL);
2155}
2156
2157static const rb_callable_method_entry_t *
2158callable_method_entry(VALUE klass, ID mid, VALUE *defined_class_ptr)
2159{
2160 const rb_callable_method_entry_t *cme;
2161 cme = callable_method_entry_or_negative(klass, mid, defined_class_ptr);
2162 return !UNDEFINED_METHOD_ENTRY_P(cme) ? cme : NULL;
2163}
2164
2166rb_callable_method_entry(VALUE klass, ID mid)
2167{
2168 return callable_method_entry(klass, mid, NULL);
2169}
2170
2171static const rb_method_entry_t *resolve_refined_method(VALUE refinements, const rb_method_entry_t *me, VALUE *defined_class_ptr);
2172
2173static const rb_method_entry_t *
2174method_entry_resolve_refinement(VALUE klass, ID id, int with_refinement, VALUE *defined_class_ptr)
2175{
2176 const rb_method_entry_t *me = search_method_protect(klass, id, defined_class_ptr);
2177
2178 if (me) {
2179 if (me->def->type == VM_METHOD_TYPE_REFINED) {
2180 if (with_refinement) {
2181 const rb_cref_t *cref = rb_vm_cref();
2182 VALUE refinements = cref ? CREF_REFINEMENTS(cref) : Qnil;
2183 me = resolve_refined_method(refinements, me, defined_class_ptr);
2184 }
2185 else {
2186 me = resolve_refined_method(Qnil, me, defined_class_ptr);
2187 }
2188
2189 if (UNDEFINED_METHOD_ENTRY_P(me)) me = NULL;
2190 }
2191 }
2192
2193 return me;
2194}
2195
2196const rb_method_entry_t *
2197rb_method_entry_with_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
2198{
2199 return method_entry_resolve_refinement(klass, id, TRUE, defined_class_ptr);
2200}
2201
2202static const rb_callable_method_entry_t *
2203callable_method_entry_refinements0(VALUE klass, ID id, VALUE *defined_class_ptr, bool with_refinements,
2204 const rb_callable_method_entry_t *cme)
2205{
2206 if (cme == NULL || LIKELY(cme->def->type != VM_METHOD_TYPE_REFINED)) {
2207 return cme;
2208 }
2209 else {
2210 VALUE defined_class, *dcp = defined_class_ptr ? defined_class_ptr : &defined_class;
2211 const rb_method_entry_t *me = method_entry_resolve_refinement(klass, id, with_refinements, dcp);
2212 return prepare_callable_method_entry(*dcp, id, me, TRUE);
2213 }
2214}
2215
2216static const rb_callable_method_entry_t *
2217callable_method_entry_refinements(VALUE klass, ID id, VALUE *defined_class_ptr, bool with_refinements)
2218{
2219 const rb_callable_method_entry_t *cme = callable_method_entry(klass, id, defined_class_ptr);
2220 return callable_method_entry_refinements0(klass, id, defined_class_ptr, with_refinements, cme);
2221}
2222
2224rb_callable_method_entry_with_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
2225{
2226 return callable_method_entry_refinements(klass, id, defined_class_ptr, true);
2227}
2228
2229static const rb_callable_method_entry_t *
2230callable_method_entry_without_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
2231{
2232 return callable_method_entry_refinements(klass, id, defined_class_ptr, false);
2233}
2234
2235const rb_method_entry_t *
2236rb_method_entry_without_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
2237{
2238 return method_entry_resolve_refinement(klass, id, FALSE, defined_class_ptr);
2239}
2240
2242rb_callable_method_entry_without_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
2243{
2244 VALUE defined_class, *dcp = defined_class_ptr ? defined_class_ptr : &defined_class;
2245 const rb_method_entry_t *me = method_entry_resolve_refinement(klass, id, FALSE, dcp);
2246 return prepare_callable_method_entry(*dcp, id, me, TRUE);
2247}
2248
2249static const rb_method_entry_t *
2250resolve_refined_method(VALUE refinements, const rb_method_entry_t *me, VALUE *defined_class_ptr)
2251{
2252 while (me && me->def->type == VM_METHOD_TYPE_REFINED) {
2253 VALUE refinement;
2254 const rb_method_entry_t *tmp_me;
2255 VALUE super;
2256
2257 refinement = find_refinement(refinements, me->owner);
2258 if (!NIL_P(refinement)) {
2259 tmp_me = search_method_protect(refinement, me->called_id, defined_class_ptr);
2260
2261 if (tmp_me && tmp_me->def->type != VM_METHOD_TYPE_REFINED) {
2262 return tmp_me;
2263 }
2264 }
2265
2266 tmp_me = me->def->body.refined.orig_me;
2267 if (tmp_me) {
2268 if (!tmp_me->defined_class) {
2269 VM_ASSERT_TYPE(tmp_me->owner, T_MODULE);
2270 }
2271 else if (defined_class_ptr) {
2272 *defined_class_ptr = tmp_me->defined_class;
2273 }
2274 return tmp_me;
2275 }
2276
2277 super = RCLASS_SUPER(me->owner);
2278 if (!super) {
2279 return 0;
2280 }
2281
2282 me = search_method_protect(super, me->called_id, defined_class_ptr);
2283 }
2284 return me;
2285}
2286
2287const rb_method_entry_t *
2288rb_resolve_refined_method(VALUE refinements, const rb_method_entry_t *me)
2289{
2290 return resolve_refined_method(refinements, me, NULL);
2291}
2292
2294rb_resolve_refined_method_callable(VALUE refinements, const rb_callable_method_entry_t *me)
2295{
2296 VALUE defined_class = me->defined_class;
2297 const rb_method_entry_t *resolved_me = resolve_refined_method(refinements, (const rb_method_entry_t *)me, &defined_class);
2298
2299 if (resolved_me && resolved_me->defined_class == 0) {
2300 return rb_method_entry_complement_defined_class(resolved_me, me->called_id, defined_class);
2301 }
2302 else {
2303 return (const rb_callable_method_entry_t *)resolved_me;
2304 }
2305}
2306
2307static void
2308remove_method(VALUE klass, ID mid)
2309{
2310 VALUE data;
2311 rb_method_entry_t *me = 0;
2312 VALUE self = klass;
2313
2314 rb_class_modify_check(klass);
2315 klass = RCLASS_ORIGIN(klass);
2316 if (mid == object_id || mid == id__id__ || mid == id__send__ || mid == idInitialize) {
2317 rb_warn("removing '%s' may cause serious problems", rb_id2name(mid));
2318 }
2319
2320 if (!rb_id_table_lookup(RCLASS_M_TBL(klass), mid, &data) ||
2321 !(me = (rb_method_entry_t *)data) ||
2322 (!me->def || me->def->type == VM_METHOD_TYPE_UNDEF) ||
2323 UNDEFINED_REFINED_METHOD_P(me->def)) {
2324 rb_name_err_raise("method '%1$s' not defined in %2$s",
2325 klass, ID2SYM(mid));
2326 }
2327
2328 if (klass != self) {
2329 rb_clear_method_cache(self, mid);
2330 }
2331 rb_clear_method_cache(klass, mid);
2332 rb_id_table_delete(RCLASS_WRITABLE_M_TBL(klass), mid);
2333
2334 rb_vm_check_redefinition_opt_method(me, klass);
2335
2336 if (me->def->type == VM_METHOD_TYPE_REFINED) {
2337 rb_add_refined_method_entry(klass, mid);
2338 }
2339
2340 CALL_METHOD_HOOK(self, removed, mid);
2341}
2342
2343void
2345{
2346 remove_method(klass, mid);
2347}
2348
2349void
2350rb_remove_method(VALUE klass, const char *name)
2351{
2352 remove_method(klass, rb_intern(name));
2353}
2354
2355/*
2356 * call-seq:
2357 * remove_method(symbol) -> self
2358 * remove_method(string) -> self
2359 *
2360 * Removes the method identified by _symbol_ from the current
2361 * class. For an example, see Module#undef_method.
2362 * String arguments are converted to symbols.
2363 */
2364
2365static VALUE
2366rb_mod_remove_method(int argc, VALUE *argv, VALUE mod)
2367{
2368 int i;
2369
2370 for (i = 0; i < argc; i++) {
2371 VALUE v = argv[i];
2372 ID id = rb_check_id(&v);
2373 if (!id) {
2374 rb_name_err_raise("method '%1$s' not defined in %2$s",
2375 mod, v);
2376 }
2377 remove_method(mod, id);
2378 }
2379 return mod;
2380}
2381
2382static void
2383rb_export_method(VALUE klass, ID name, rb_method_visibility_t visi)
2384{
2386 VALUE defined_class;
2387 VALUE origin_class = RCLASS_ORIGIN(klass);
2388
2389 me = search_method0(origin_class, name, &defined_class, true);
2390
2391 if (!me && RB_TYPE_P(klass, T_MODULE)) {
2392 me = search_method(rb_cObject, name, &defined_class);
2393 }
2394
2395 if (UNDEFINED_METHOD_ENTRY_P(me) ||
2396 UNDEFINED_REFINED_METHOD_P(me->def)) {
2397 rb_print_undef(klass, name, METHOD_VISI_UNDEF);
2398 }
2399
2400 if (METHOD_ENTRY_VISI(me) != visi) {
2401 rb_vm_check_redefinition_opt_method(me, klass);
2402
2403 if (klass == defined_class || origin_class == defined_class) {
2404 if (me->def->type == VM_METHOD_TYPE_REFINED) {
2405 // Refinement method entries should always be public because the refinement
2406 // search is always performed.
2407 if (me->def->body.refined.orig_me) {
2408 METHOD_ENTRY_VISI_SET((rb_method_entry_t *)me->def->body.refined.orig_me, visi);
2409 }
2410 }
2411 else {
2412 METHOD_ENTRY_VISI_SET(me, visi);
2413 }
2414 rb_clear_method_cache(klass, name);
2415 }
2416 else {
2417 rb_add_method(klass, name, VM_METHOD_TYPE_ZSUPER, 0, visi);
2418 }
2419 }
2420}
2421
2422#define BOUND_PRIVATE 0x01
2423#define BOUND_RESPONDS 0x02
2424
2425static int
2426method_boundp(VALUE klass, ID id, int ex)
2427{
2428 const rb_callable_method_entry_t *cme;
2429
2430 VM_ASSERT_TYPE2(klass, T_CLASS, T_ICLASS);
2431
2432 if (ex & BOUND_RESPONDS) {
2433 cme = rb_callable_method_entry_with_refinements(klass, id, NULL);
2434 }
2435 else {
2436 cme = callable_method_entry_without_refinements(klass, id, NULL);
2437 }
2438
2439 if (cme != NULL) {
2440 if (ex & ~BOUND_RESPONDS) {
2441 switch (METHOD_ENTRY_VISI(cme)) {
2442 case METHOD_VISI_PRIVATE:
2443 return 0;
2444 case METHOD_VISI_PROTECTED:
2445 if (ex & BOUND_RESPONDS) return 0;
2446 default:
2447 break;
2448 }
2449 }
2450
2451 if (cme->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
2452 if (ex & BOUND_RESPONDS) return 2;
2453 return 0;
2454 }
2455 return 1;
2456 }
2457 return 0;
2458}
2459
2460// deprecated
2461int
2462rb_method_boundp(VALUE klass, ID id, int ex)
2463{
2464 return method_boundp(klass, id, ex);
2465}
2466
2467static void
2468vm_cref_set_visibility(rb_method_visibility_t method_visi, int module_func)
2469{
2470 rb_scope_visibility_t *scope_visi = (rb_scope_visibility_t *)&rb_vm_cref()->scope_visi;
2471 scope_visi->method_visi = method_visi;
2472 scope_visi->module_func = module_func;
2473}
2474
2475void
2476rb_scope_visibility_set(rb_method_visibility_t visi)
2477{
2478 vm_cref_set_visibility(visi, FALSE);
2479}
2480
2481static void
2482scope_visibility_check(void)
2483{
2484 /* Check for public/protected/private/module_function called inside a method */
2485 rb_control_frame_t *cfp = GET_EC()->cfp+1;
2486 if (cfp && CFP_ISEQ(cfp) && ISEQ_BODY(CFP_ISEQ(cfp))->type == ISEQ_TYPE_METHOD) {
2487 rb_warn("calling %s without arguments inside a method may not have the intended effect",
2488 rb_id2name(rb_frame_this_func()));
2489 }
2490}
2491
2492static void
2493rb_scope_module_func_set(void)
2494{
2495 scope_visibility_check();
2496 vm_cref_set_visibility(METHOD_VISI_PRIVATE, TRUE);
2497}
2498
2499const rb_cref_t *rb_vm_cref_in_context(VALUE self, VALUE cbase);
2500void
2501rb_attr(VALUE klass, ID id, int read, int write, int ex)
2502{
2503 ID attriv;
2504 rb_method_visibility_t visi;
2505 const rb_execution_context_t *ec = GET_EC();
2506 const rb_cref_t *cref = rb_vm_cref_in_context(klass, klass);
2507
2508 if (!ex || !cref) {
2509 visi = METHOD_VISI_PUBLIC;
2510 }
2511 else {
2512 switch (vm_scope_visibility_get(ec)) {
2513 case METHOD_VISI_PRIVATE:
2514 if (vm_scope_module_func_check(ec)) {
2515 rb_warning("attribute accessor as module_function");
2516 }
2517 visi = METHOD_VISI_PRIVATE;
2518 break;
2519 case METHOD_VISI_PROTECTED:
2520 visi = METHOD_VISI_PROTECTED;
2521 break;
2522 default:
2523 visi = METHOD_VISI_PUBLIC;
2524 break;
2525 }
2526 }
2527
2528 attriv = rb_intern_str(rb_sprintf("@%"PRIsVALUE, rb_id2str(id)));
2529 if (read) {
2530 rb_add_method(klass, id, VM_METHOD_TYPE_IVAR, (void *)attriv, visi);
2531 }
2532 if (write) {
2533 rb_add_method(klass, rb_id_attrset(id), VM_METHOD_TYPE_ATTRSET, (void *)attriv, visi);
2534 }
2535}
2536
2537void
2539{
2540 const rb_method_entry_t *me;
2541
2542 if (NIL_P(klass)) {
2543 rb_raise(rb_eTypeError, "no class to undef method");
2544 }
2545 rb_class_modify_check(klass);
2546 if (id == object_id || id == id__id__ || id == id__send__ || id == idInitialize) {
2547 rb_warn("undefining '%s' may cause serious problems", rb_id2name(id));
2548 }
2549
2550 me = search_method(klass, id, 0);
2551 if (me && me->def->type == VM_METHOD_TYPE_REFINED) {
2552 me = rb_resolve_refined_method(Qnil, me);
2553 }
2554
2555 if (UNDEFINED_METHOD_ENTRY_P(me) ||
2556 UNDEFINED_REFINED_METHOD_P(me->def)) {
2557 rb_method_name_error(klass, rb_id2str(id));
2558 }
2559
2560 rb_add_method(klass, id, VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_PUBLIC);
2561
2562 CALL_METHOD_HOOK(klass, undefined, id);
2563}
2564
2565/*
2566 * call-seq:
2567 * undef_method(symbol) -> self
2568 * undef_method(string) -> self
2569 *
2570 * Prevents the current class from responding to calls to the named
2571 * method. Contrast this with <code>remove_method</code>, which deletes
2572 * the method from the particular class; Ruby will still search
2573 * superclasses and mixed-in modules for a possible receiver.
2574 * String arguments are converted to symbols.
2575 *
2576 * class Parent
2577 * def hello
2578 * puts "In parent"
2579 * end
2580 * end
2581 * class Child < Parent
2582 * def hello
2583 * puts "In child"
2584 * end
2585 * end
2586 *
2587 *
2588 * c = Child.new
2589 * c.hello
2590 *
2591 *
2592 * class Child
2593 * remove_method :hello # remove from child, still in parent
2594 * end
2595 * c.hello
2596 *
2597 *
2598 * class Child
2599 * undef_method :hello # prevent any calls to 'hello'
2600 * end
2601 * c.hello
2602 *
2603 * <em>produces:</em>
2604 *
2605 * In child
2606 * In parent
2607 * prog.rb:23: undefined method 'hello' for #<Child:0x401b3bb4> (NoMethodError)
2608 */
2609
2610static VALUE
2611rb_mod_undef_method(int argc, VALUE *argv, VALUE mod)
2612{
2613 int i;
2614 for (i = 0; i < argc; i++) {
2615 VALUE v = argv[i];
2616 ID id = rb_check_id(&v);
2617 if (!id) {
2618 rb_method_name_error(mod, v);
2619 }
2620 rb_undef(mod, id);
2621 }
2622 return mod;
2623}
2624
2625static rb_method_visibility_t
2626check_definition_visibility(VALUE mod, VALUE mid, bool inc_super)
2627{
2628 ID id = rb_check_id(&mid);
2629 if (!id) return METHOD_VISI_UNDEF;
2630
2631 VALUE lookup_mod = inc_super ? mod : RCLASS_ORIGIN(mod);
2632
2633 const rb_method_entry_t *me = rb_method_entry_without_refinements(lookup_mod, id, NULL);
2634 if (me) {
2635 if (me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) return METHOD_VISI_UNDEF;
2636 if (!inc_super && me->owner != mod) return METHOD_VISI_UNDEF;
2637 return METHOD_ENTRY_VISI(me);
2638 }
2639 return METHOD_VISI_UNDEF;
2640}
2641
2642/*
2643 * call-seq:
2644 * mod.method_defined?(symbol, inherit=true, include_all = false) -> true or false
2645 * mod.method_defined?(string, inherit=true, include_all = false) -> true or false
2646 *
2647 * Returns +true+ if the named method is defined by
2648 * _mod_. If _inherit_ is set, the lookup will also search _mod_'s
2649 * ancestors.
2650 * By default only public and protected methods are matched, but if _include_all_
2651 * is set the lookup will also consider private methods.
2652 * String arguments are converted to symbols.
2653 *
2654 * module A
2655 * def method1() end
2656 * def protected_method1() end
2657 * protected :protected_method1
2658 * end
2659 * class B
2660 * def method2() end
2661 * def private_method2() end
2662 * private :private_method2
2663 * end
2664 * class C < B
2665 * include A
2666 * def method3() end
2667 * end
2668 *
2669 * A.method_defined? :method1 #=> true
2670 * C.method_defined? "method1" #=> true
2671 * C.method_defined? "method2" #=> true
2672 * C.method_defined? "method2", true #=> true
2673 * C.method_defined? "method2", false #=> false
2674 * C.method_defined? "method3" #=> true
2675 * C.method_defined? "protected_method1" #=> true
2676 * C.method_defined? "method4" #=> false
2677 * C.method_defined? "private_method2" #=> false
2678 * C.method_defined? "private_method2", true, true #=> true
2679 * C.method_defined? "private_method2", false, true #=> false
2680 */
2681
2682static VALUE
2683rb_mod_method_defined(int argc, VALUE *argv, VALUE mod)
2684{
2685 VALUE mid, include_super, include_private;
2686
2687 rb_scan_args(argc, argv, "12", &mid, &include_super, &include_private);
2688 if (argc < 3) {
2689 include_private = Qfalse;
2690 if (argc < 2) {
2691 include_super = Qtrue;
2692 }
2693 }
2694
2695 rb_method_visibility_t visi = check_definition_visibility(mod, mid, RTEST(include_super));
2696 switch (visi) {
2697 case METHOD_VISI_UNDEF:
2698 return Qfalse;
2699 case METHOD_VISI_PUBLIC:
2700 case METHOD_VISI_PROTECTED:
2701 return Qtrue;
2702 case METHOD_VISI_PRIVATE:
2703 return RBOOL(RTEST(include_private));
2704 default:
2706 }
2707}
2708
2709static VALUE
2710check_definition(VALUE mod, int argc, VALUE *argv, rb_method_visibility_t visi)
2711{
2712 VALUE mid, include_super;
2713 rb_scan_args(argc, argv, "11", &mid, &include_super);
2714 if (argc < 2) {
2715 include_super = Qtrue;
2716 }
2717 return RBOOL(check_definition_visibility(mod, mid, RTEST(include_super)) == visi);
2718}
2719
2720/*
2721 * call-seq:
2722 * mod.public_method_defined?(symbol, inherit=true) -> true or false
2723 * mod.public_method_defined?(string, inherit=true) -> true or false
2724 *
2725 * Returns +true+ if the named public method is defined by
2726 * _mod_. If _inherit_ is set, the lookup will also search _mod_'s
2727 * ancestors.
2728 * String arguments are converted to symbols.
2729 *
2730 * module A
2731 * def method1() end
2732 * end
2733 * class B
2734 * protected
2735 * def method2() end
2736 * end
2737 * class C < B
2738 * include A
2739 * def method3() end
2740 * end
2741 *
2742 * A.method_defined? :method1 #=> true
2743 * C.public_method_defined? "method1" #=> true
2744 * C.public_method_defined? "method1", true #=> true
2745 * C.public_method_defined? "method1", false #=> true
2746 * C.public_method_defined? "method2" #=> false
2747 * C.method_defined? "method2" #=> true
2748 */
2749
2750static VALUE
2751rb_mod_public_method_defined(int argc, VALUE *argv, VALUE mod)
2752{
2753 return check_definition(mod, argc, argv, METHOD_VISI_PUBLIC);
2754}
2755
2756/*
2757 * call-seq:
2758 * mod.private_method_defined?(symbol, inherit=true) -> true or false
2759 * mod.private_method_defined?(string, inherit=true) -> true or false
2760 *
2761 * Returns +true+ if the named private method is defined by
2762 * _mod_. If _inherit_ is set, the lookup will also search _mod_'s
2763 * ancestors.
2764 * String arguments are converted to symbols.
2765 *
2766 * module A
2767 * def method1() end
2768 * end
2769 * class B
2770 * private
2771 * def method2() end
2772 * end
2773 * class C < B
2774 * include A
2775 * def method3() end
2776 * end
2777 *
2778 * A.method_defined? :method1 #=> true
2779 * C.private_method_defined? "method1" #=> false
2780 * C.private_method_defined? "method2" #=> true
2781 * C.private_method_defined? "method2", true #=> true
2782 * C.private_method_defined? "method2", false #=> false
2783 * C.method_defined? "method2" #=> false
2784 */
2785
2786static VALUE
2787rb_mod_private_method_defined(int argc, VALUE *argv, VALUE mod)
2788{
2789 return check_definition(mod, argc, argv, METHOD_VISI_PRIVATE);
2790}
2791
2792/*
2793 * call-seq:
2794 * mod.protected_method_defined?(symbol, inherit=true) -> true or false
2795 * mod.protected_method_defined?(string, inherit=true) -> true or false
2796 *
2797 * Returns +true+ if the named protected method is defined
2798 * _mod_. If _inherit_ is set, the lookup will also search _mod_'s
2799 * ancestors.
2800 * String arguments are converted to symbols.
2801 *
2802 * module A
2803 * def method1() end
2804 * end
2805 * class B
2806 * protected
2807 * def method2() end
2808 * end
2809 * class C < B
2810 * include A
2811 * def method3() end
2812 * end
2813 *
2814 * A.method_defined? :method1 #=> true
2815 * C.protected_method_defined? "method1" #=> false
2816 * C.protected_method_defined? "method2" #=> true
2817 * C.protected_method_defined? "method2", true #=> true
2818 * C.protected_method_defined? "method2", false #=> false
2819 * C.method_defined? "method2" #=> true
2820 */
2821
2822static VALUE
2823rb_mod_protected_method_defined(int argc, VALUE *argv, VALUE mod)
2824{
2825 return check_definition(mod, argc, argv, METHOD_VISI_PROTECTED);
2826}
2827
2828int
2829rb_method_entry_eq(const rb_method_entry_t *m1, const rb_method_entry_t *m2)
2830{
2831 return rb_method_definition_eq(m1->def, m2->def);
2832}
2833
2834static const rb_method_definition_t *
2835original_method_definition(const rb_method_definition_t *def)
2836{
2837 again:
2838 if (def) {
2839 switch (def->type) {
2840 case VM_METHOD_TYPE_REFINED:
2841 if (def->body.refined.orig_me) {
2842 def = def->body.refined.orig_me->def;
2843 goto again;
2844 }
2845 break;
2846 case VM_METHOD_TYPE_ALIAS:
2847 def = def->body.alias.original_me->def;
2848 goto again;
2849 default:
2850 break;
2851 }
2852 }
2853 return def;
2854}
2855
2856int
2857rb_method_definition_eq(const rb_method_definition_t *d1, const rb_method_definition_t *d2)
2858{
2859 d1 = original_method_definition(d1);
2860 d2 = original_method_definition(d2);
2861
2862 if (d1 == d2) return 1;
2863 if (!d1 || !d2) return 0;
2864 if (d1->type != d2->type) return 0;
2865
2866 switch (d1->type) {
2867 case VM_METHOD_TYPE_ISEQ:
2868 return d1->body.iseq.iseqptr == d2->body.iseq.iseqptr;
2869 case VM_METHOD_TYPE_CFUNC:
2870 return
2871 d1->body.cfunc.func == d2->body.cfunc.func &&
2872 d1->body.cfunc.argc == d2->body.cfunc.argc;
2873 case VM_METHOD_TYPE_ATTRSET:
2874 case VM_METHOD_TYPE_IVAR:
2875 return d1->body.attr.id == d2->body.attr.id;
2876 case VM_METHOD_TYPE_BMETHOD:
2877 return RTEST(rb_equal(d1->body.bmethod.proc, d2->body.bmethod.proc));
2878 case VM_METHOD_TYPE_MISSING:
2879 return d1->original_id == d2->original_id;
2880 case VM_METHOD_TYPE_ZSUPER:
2881 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2882 case VM_METHOD_TYPE_UNDEF:
2883 return 1;
2884 case VM_METHOD_TYPE_OPTIMIZED:
2885 return (d1->body.optimized.type == d2->body.optimized.type) &&
2886 (d1->body.optimized.index == d2->body.optimized.index);
2887 case VM_METHOD_TYPE_REFINED:
2888 case VM_METHOD_TYPE_ALIAS:
2889 break;
2890 }
2891 rb_bug("rb_method_definition_eq: unsupported type: %d", d1->type);
2892}
2893
2894static st_index_t
2895rb_hash_method_definition(st_index_t hash, const rb_method_definition_t *def)
2896{
2897 hash = rb_hash_uint(hash, def->type);
2898 def = original_method_definition(def);
2899
2900 if (!def) return hash;
2901
2902 switch (def->type) {
2903 case VM_METHOD_TYPE_ISEQ:
2904 return rb_hash_uint(hash, (st_index_t)def->body.iseq.iseqptr->body);
2905 case VM_METHOD_TYPE_CFUNC:
2906 hash = rb_hash_uint(hash, (st_index_t)def->body.cfunc.func);
2907 return rb_hash_uint(hash, def->body.cfunc.argc);
2908 case VM_METHOD_TYPE_ATTRSET:
2909 case VM_METHOD_TYPE_IVAR:
2910 return rb_hash_uint(hash, def->body.attr.id);
2911 case VM_METHOD_TYPE_BMETHOD:
2912 return rb_hash_proc(hash, def->body.bmethod.proc);
2913 case VM_METHOD_TYPE_MISSING:
2914 return rb_hash_uint(hash, def->original_id);
2915 case VM_METHOD_TYPE_ZSUPER:
2916 case VM_METHOD_TYPE_NOTIMPLEMENTED:
2917 case VM_METHOD_TYPE_UNDEF:
2918 return hash;
2919 case VM_METHOD_TYPE_OPTIMIZED:
2920 hash = rb_hash_uint(hash, def->body.optimized.index);
2921 return rb_hash_uint(hash, def->body.optimized.type);
2922 case VM_METHOD_TYPE_REFINED:
2923 case VM_METHOD_TYPE_ALIAS:
2924 break; /* unreachable */
2925 }
2926 rb_bug("rb_hash_method_definition: unsupported method type (%d)", def->type);
2927}
2928
2929st_index_t
2930rb_hash_method_entry(st_index_t hash, const rb_method_entry_t *me)
2931{
2932 return rb_hash_method_definition(hash, me->def);
2933}
2934
2935void
2936rb_alias(VALUE klass, ID alias_name, ID original_name)
2937{
2938 const VALUE target_klass = klass;
2939 VALUE defined_class;
2940 const rb_method_entry_t *orig_me;
2941 rb_method_visibility_t visi = METHOD_VISI_UNDEF;
2942
2943 if (NIL_P(klass)) {
2944 rb_raise(rb_eTypeError, "no class to make alias");
2945 }
2946
2947 rb_class_modify_check(target_klass);
2948
2949 again:
2950 orig_me = search_method(klass, original_name, &defined_class);
2951
2952 if (orig_me && orig_me->def->type == VM_METHOD_TYPE_REFINED) {
2953 orig_me = rb_resolve_refined_method(Qnil, orig_me);
2954 }
2955
2956 if (UNDEFINED_METHOD_ENTRY_P(orig_me) ||
2957 UNDEFINED_REFINED_METHOD_P(orig_me->def)) {
2958 if ((!RB_TYPE_P(klass, T_MODULE)) ||
2959 (orig_me = search_method(rb_cObject, original_name, &defined_class),
2960 UNDEFINED_METHOD_ENTRY_P(orig_me))) {
2961 rb_print_undef(target_klass, original_name, METHOD_VISI_UNDEF);
2962 }
2963 rb_warn_scheduled_deprecation(4.2, 4.3,
2964 "the fallback to Object for alias of '%"PRIsVALUE"' in module '%"PRIsVALUE"'",
2965 NULL, QUOTE_ID(original_name), rb_class_path(target_klass));
2966 }
2967
2968 switch (orig_me->def->type) {
2969 case VM_METHOD_TYPE_ZSUPER:
2970 klass = RCLASS_SUPER(klass);
2971 original_name = orig_me->def->original_id;
2972 visi = METHOD_ENTRY_VISI(orig_me);
2973 goto again;
2974 case VM_METHOD_TYPE_ALIAS:
2975 visi = METHOD_ENTRY_VISI(orig_me);
2976 orig_me = orig_me->def->body.alias.original_me;
2977 VM_ASSERT(orig_me->def->type != VM_METHOD_TYPE_ALIAS);
2978 break;
2979 default: break;
2980 }
2981
2982 if (visi == METHOD_VISI_UNDEF) visi = METHOD_ENTRY_VISI(orig_me);
2983
2984 if (!NIL_P(ruby_verbose) && rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) {
2985 VALUE owner_class = orig_me->defined_class ? orig_me->defined_class : defined_class;
2986 VALUE origin = RCLASS_ORIGIN(target_klass);
2987 bool in_prepended_module = false;
2988
2989 if (origin != target_klass) {
2990 for (VALUE p = RCLASS_SUPER(target_klass); !in_prepended_module && p && p != origin; p = RCLASS_SUPER(p)) {
2991 if (p == owner_class) {
2992 in_prepended_module = true;
2993 }
2994 }
2995 }
2996
2997 if (in_prepended_module) {
2998 rb_warn_scheduled_deprecation(4.2, 4.3,
2999 "aliasing %"PRIsVALUE"#%"PRIsVALUE" defined in a prepended module %"PRIsVALUE,
3000 NULL,
3001 rb_class_path(target_klass), QUOTE_ID(original_name),
3002 rb_class_path(orig_me->owner));
3003 }
3004 }
3005
3006 if (orig_me->defined_class == 0) {
3007 struct method_entry_warnings warnings = {0};
3008 const rb_method_entry_t *alias_me =
3009 // TODO: needs vm lock?
3010 rb_method_entry_make(target_klass, alias_name, target_klass, visi,
3011 VM_METHOD_TYPE_ALIAS, NULL, orig_me->called_id,
3012 (void *)rb_method_entry_clone(orig_me), &warnings);
3013
3014 method_entry_warnings_emit(&warnings);
3015 method_added(target_klass, alias_name, alias_me);
3016 }
3017 else {
3018 rb_method_entry_t *alias_me;
3019
3020 alias_me = method_entry_set(target_klass, alias_name, orig_me, visi, orig_me->owner);
3021 RB_OBJ_WRITE(alias_me, &alias_me->owner, target_klass);
3022
3023 if (RB_TYPE_P(target_klass, T_MODULE)) {
3024 // defined_class should not be set
3025 }
3026 else {
3027 RB_OBJ_WRITE(alias_me, &alias_me->defined_class, orig_me->defined_class);
3028 }
3029 }
3030}
3031
3032/*
3033 * call-seq:
3034 * alias_method(new_name, old_name) -> symbol
3035 *
3036 * Makes <i>new_name</i> a new copy of the method <i>old_name</i>. This can
3037 * be used to retain access to methods that are overridden.
3038 *
3039 * class Greeter
3040 * def hello
3041 * "hello"
3042 * end
3043 * alias_method :orig_hello, :hello #=> :orig_hello
3044 * def hello
3045 * "#{orig_hello}, world"
3046 * end
3047 * end
3048 * Greeter.new.hello #=> "hello, world"
3049 *
3050 * In a module, <i>old_name</i> must be a method of the module or its
3051 * ancestors. Aliasing a method found only through the fallback to
3052 * Object is deprecated, and will raise a NameError in Ruby 4.3.
3053 */
3054
3055static VALUE
3056rb_mod_alias_method(VALUE mod, VALUE newname, VALUE oldname)
3057{
3058 ID oldid = rb_check_id(&oldname);
3059 if (!oldid) {
3060 rb_print_undef_str(mod, oldname);
3061 }
3062 VALUE id = rb_to_id(newname);
3063 rb_alias(mod, id, oldid);
3064 return ID2SYM(id);
3065}
3066
3067static void
3068check_and_export_method(VALUE self, VALUE name, rb_method_visibility_t visi)
3069{
3070 ID id = rb_check_id(&name);
3071 if (!id) {
3072 rb_print_undef_str(self, name);
3073 }
3074 rb_export_method(self, id, visi);
3075}
3076
3077static void
3078set_method_visibility(VALUE self, int argc, const VALUE *argv, rb_method_visibility_t visi)
3079{
3080 int i;
3081
3082 // Not rb_class_modify_check: that also marks a module initialized, which this
3083 // path has never done.
3084 rb_check_frozen(self);
3085 rb_class_owner_check(self);
3086 if (argc == 0) {
3087 rb_warning("%"PRIsVALUE" with no argument is just ignored",
3088 QUOTE_ID(rb_frame_callee()));
3089 return;
3090 }
3091
3092
3093 VALUE v;
3094
3095 if (argc == 1 && (v = rb_check_array_type(argv[0])) != Qnil) {
3096 long j;
3097
3098 for (j = 0; j < RARRAY_LEN(v); j++) {
3099 check_and_export_method(self, RARRAY_AREF(v, j), visi);
3100 }
3101 }
3102 else {
3103 for (i = 0; i < argc; i++) {
3104 check_and_export_method(self, argv[i], visi);
3105 }
3106 }
3107}
3108
3109static VALUE
3110set_visibility(int argc, const VALUE *argv, VALUE module, rb_method_visibility_t visi)
3111{
3112 if (argc == 0) {
3113 scope_visibility_check();
3114 rb_scope_visibility_set(visi);
3115 return Qnil;
3116 }
3117
3118 set_method_visibility(module, argc, argv, visi);
3119 if (argc == 1) {
3120 return argv[0];
3121 }
3122 return rb_ary_new_from_values(argc, argv);
3123}
3124
3125/*
3126 * call-seq:
3127 * public -> nil
3128 * public(method_name) -> method_name
3129 * public(method_name, method_name, ...) -> array
3130 * public(array) -> array
3131 *
3132 * With no arguments, sets the default visibility for subsequently
3133 * defined methods to public. With arguments, sets the named methods to
3134 * have public visibility.
3135 * String arguments are converted to symbols.
3136 * An Array of Symbols and/or Strings is also accepted.
3137 * If a single argument is passed, it is returned.
3138 * If no argument is passed, nil is returned.
3139 * If multiple arguments are passed, the arguments are returned as an array.
3140 */
3141
3142static VALUE
3143rb_mod_public(int argc, VALUE *argv, VALUE module)
3144{
3145 return set_visibility(argc, argv, module, METHOD_VISI_PUBLIC);
3146}
3147
3148/*
3149 * call-seq:
3150 * protected -> nil
3151 * protected(method_name) -> method_name
3152 * protected(method_name, method_name, ...) -> array
3153 * protected(array) -> array
3154 *
3155 * Sets the visibility of a section or of a list of method names as protected.
3156 * Accepts no arguments, a splat of method names (symbols or strings) or an
3157 * array of method names. Returns the arguments that it received.
3158 *
3159 * == Important difference between protected in other languages
3160 *
3161 * Protected methods in Ruby are different from other languages such as Java,
3162 * where methods are marked as protected to give access to subclasses. In Ruby,
3163 * subclasses <b>already have access to all methods defined in the parent
3164 * class</b>, even private ones.
3165 *
3166 * Marking a method as protected allows <b>different objects of the same
3167 * class</b> to call it.
3168 *
3169 * One use case is for comparison methods, such as <code>==</code>, if we want
3170 * to expose a method for comparison between objects of the same class without
3171 * making the method public to objects of other classes.
3172 *
3173 * == Performance considerations
3174 *
3175 * Protected methods are slower than others because they can't use inline
3176 * cache.
3177 *
3178 * == Example
3179 *
3180 * class Account
3181 * # Mark balance as protected, so that we can compare between accounts
3182 * # without making it public.
3183 * attr_reader :balance
3184 * protected :balance
3185 *
3186 * def initialize(balance)
3187 * @balance = balance
3188 * end
3189 *
3190 * def >(other)
3191 * # The invocation to `other.balance` is allowed because `other` is a
3192 * # different object of the same class (Account).
3193 * balance > other.balance
3194 * end
3195 * end
3196 *
3197 * account1 = Account.new(100)
3198 * account2 = Account.new(50)
3199 *
3200 * account1 > account2 # => true (works)
3201 * account1.balance # => NoMethodError (fails because balance is not public)
3202 *
3203 * To show a private method on RDoc, use <code>:doc:</code> instead of this.
3204 */
3205
3206static VALUE
3207rb_mod_protected(int argc, VALUE *argv, VALUE module)
3208{
3209 return set_visibility(argc, argv, module, METHOD_VISI_PROTECTED);
3210}
3211
3212/*
3213 * call-seq:
3214 * private -> nil
3215 * private(method_name) -> method_name
3216 * private(method_name, method_name, ...) -> array
3217 * private(array) -> array
3218 *
3219 * With no arguments, sets the default visibility for subsequently
3220 * defined methods to private. With arguments, sets the named methods
3221 * to have private visibility.
3222 * String arguments are converted to symbols.
3223 * An Array of Symbols and/or Strings is also accepted.
3224 * If a single argument is passed, it is returned.
3225 * If no argument is passed, nil is returned.
3226 * If multiple arguments are passed, the arguments are returned as an array.
3227 *
3228 * module Mod
3229 * def a() end
3230 * def b() end
3231 * private
3232 * def c() end
3233 * private :a
3234 * end
3235 * Mod.private_instance_methods #=> [:a, :c]
3236 *
3237 * Note that to show a private method on RDoc, use <code>:doc:</code>.
3238 */
3239
3240static VALUE
3241rb_mod_private(int argc, VALUE *argv, VALUE module)
3242{
3243 return set_visibility(argc, argv, module, METHOD_VISI_PRIVATE);
3244}
3245
3246/*
3247 * call-seq:
3248 * ruby2_keywords(method_name, ...) -> nil
3249 *
3250 * Deprecated: will be removed in Ruby 4.4. Use <tt>...</tt>
3251 * {argument forwarding}[rdoc-ref:syntax/methods.rdoc@Argument+Forwarding]
3252 * or other delegation styles instead; they work correctly on Ruby 3.0
3253 * and later. See https://bugs.ruby-lang.org/issues/22205 for the
3254 * schedule.
3255 *
3256 * For the given method names, marks the method as passing keywords through
3257 * a normal argument splat. This should only be called on methods that
3258 * accept an argument splat (<tt>*args</tt>) but not explicit keywords or
3259 * a keyword splat. It marks the method such that if the method is called
3260 * with keyword arguments, the final hash argument is marked with a special
3261 * flag such that if it is the final element of a normal argument splat to
3262 * another method call, and that method call does not include explicit
3263 * keywords or a keyword splat, the final element is interpreted as keywords.
3264 * In other words, keywords will be passed through the method to other
3265 * methods.
3266 *
3267 * This should only be used for methods that delegate keywords to another
3268 * method, and only for backwards compatibility with Ruby versions before 3.0.
3269 * See https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/
3270 * for details on why +ruby2_keywords+ exists and when and how to use it.
3271 */
3272
3273static VALUE
3274rb_mod_ruby2_keywords(int argc, VALUE *argv, VALUE module)
3275{
3276 int i;
3277 VALUE origin_class = RCLASS_ORIGIN(module);
3278
3280 rb_check_frozen(module);
3281 rb_class_owner_check(module);
3282
3283 for (i = 0; i < argc; i++) {
3284 VALUE v = argv[i];
3285 ID name = rb_check_id(&v);
3287 VALUE defined_class;
3288
3289 if (!name) {
3290 rb_print_undef_str(module, v);
3291 }
3292
3293 me = search_method(origin_class, name, &defined_class);
3294 if (!me && RB_TYPE_P(module, T_MODULE)) {
3295 me = search_method(rb_cObject, name, &defined_class);
3296 }
3297
3298 if (UNDEFINED_METHOD_ENTRY_P(me) ||
3299 UNDEFINED_REFINED_METHOD_P(me->def)) {
3300 rb_print_undef(module, name, METHOD_VISI_UNDEF);
3301 }
3302
3303 if (module == defined_class || origin_class == defined_class) {
3304 switch (me->def->type) {
3305 case VM_METHOD_TYPE_ISEQ:
3306 if (ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_rest &&
3307 !ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_post &&
3308 !ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_kw &&
3309 !ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_kwrest) {
3310 ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.ruby2_keywords = 1;
3311 rb_clear_method_cache(module, name);
3312 }
3313 else {
3314 rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (method accepts keywords or post arguments or method does not accept argument splat)", QUOTE_ID(name));
3315 }
3316 break;
3317 case VM_METHOD_TYPE_BMETHOD: {
3318 VALUE procval = me->def->body.bmethod.proc;
3319 if (vm_block_handler_type(procval) == block_handler_type_proc) {
3320 procval = vm_proc_to_block_handler(VM_BH_TO_PROC(procval));
3321 }
3322
3323 if (vm_block_handler_type(procval) == block_handler_type_iseq) {
3324 const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(procval);
3325 const rb_iseq_t *iseq = rb_iseq_check(captured->code.iseq);
3326 if (ISEQ_BODY(iseq)->param.flags.has_rest &&
3327 !ISEQ_BODY(iseq)->param.flags.has_post &&
3328 !ISEQ_BODY(iseq)->param.flags.has_kw &&
3329 !ISEQ_BODY(iseq)->param.flags.has_kwrest) {
3330 ISEQ_BODY(iseq)->param.flags.ruby2_keywords = 1;
3331 rb_clear_method_cache(module, name);
3332 }
3333 else {
3334 rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (method accepts keywords or post arguments or method does not accept argument splat)", QUOTE_ID(name));
3335 }
3336 break;
3337 }
3338 }
3339 /* fallthrough */
3340 default:
3341 rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (method not defined in Ruby)", QUOTE_ID(name));
3342 break;
3343 }
3344 }
3345 else {
3346 rb_warn("Skipping set of ruby2_keywords flag for %"PRIsVALUE" (can only set in method defining module)", QUOTE_ID(name));
3347 }
3348 }
3349 return Qnil;
3350}
3351
3352/*
3353 * call-seq:
3354 * mod.public_class_method(symbol, ...) -> mod
3355 * mod.public_class_method(string, ...) -> mod
3356 * mod.public_class_method(array) -> mod
3357 *
3358 * Makes a list of existing class methods public.
3359 *
3360 * String arguments are converted to symbols.
3361 * An Array of Symbols and/or Strings is also accepted.
3362 */
3363
3364static VALUE
3365rb_mod_public_method(int argc, VALUE *argv, VALUE obj)
3366{
3367 set_method_visibility(rb_singleton_class(obj), argc, argv, METHOD_VISI_PUBLIC);
3368 return obj;
3369}
3370
3371/*
3372 * call-seq:
3373 * mod.private_class_method(symbol, ...) -> mod
3374 * mod.private_class_method(string, ...) -> mod
3375 * mod.private_class_method(array) -> mod
3376 *
3377 * Makes existing class methods private. Often used to hide the default
3378 * constructor <code>new</code>.
3379 *
3380 * String arguments are converted to symbols.
3381 * An Array of Symbols and/or Strings is also accepted.
3382 *
3383 * class SimpleSingleton # Not thread safe
3384 * private_class_method :new
3385 * def SimpleSingleton.create(*args, &block)
3386 * @me = new(*args, &block) if ! @me
3387 * @me
3388 * end
3389 * end
3390 */
3391
3392static VALUE
3393rb_mod_private_method(int argc, VALUE *argv, VALUE obj)
3394{
3395 set_method_visibility(rb_singleton_class(obj), argc, argv, METHOD_VISI_PRIVATE);
3396 return obj;
3397}
3398
3399/*
3400 * call-seq:
3401 * public
3402 * public(symbol, ...)
3403 * public(string, ...)
3404 * public(array)
3405 *
3406 * With no arguments, sets the default visibility for subsequently
3407 * defined methods to public. With arguments, sets the named methods to
3408 * have public visibility.
3409 *
3410 * String arguments are converted to symbols.
3411 * An Array of Symbols and/or Strings is also accepted.
3412 */
3413
3414static VALUE
3415top_public(int argc, VALUE *argv, VALUE _)
3416{
3417 return rb_mod_public(argc, argv, rb_top_main_class("public"));
3418}
3419
3420/*
3421 * call-seq:
3422 * private
3423 * private(symbol, ...)
3424 * private(string, ...)
3425 * private(array)
3426 *
3427 * With no arguments, sets the default visibility for subsequently
3428 * defined methods to private. With arguments, sets the named methods to
3429 * have private visibility.
3430 *
3431 * String arguments are converted to symbols.
3432 * An Array of Symbols and/or Strings is also accepted.
3433 */
3434static VALUE
3435top_private(int argc, VALUE *argv, VALUE _)
3436{
3437 return rb_mod_private(argc, argv, rb_top_main_class("private"));
3438}
3439
3440/*
3441 * call-seq:
3442 * ruby2_keywords(method_name, ...) -> self
3443 *
3444 * Deprecated: will be removed in Ruby 4.4. Use <tt>...</tt>
3445 * {argument forwarding}[rdoc-ref:syntax/methods.rdoc@Argument+Forwarding]
3446 * or other delegation styles instead; they work correctly on Ruby 3.0
3447 * and later. See https://bugs.ruby-lang.org/issues/22205 for the
3448 * schedule.
3449 *
3450 * For the given method names, marks the method as passing keywords through
3451 * a normal argument splat. See Module#ruby2_keywords in detail.
3452 */
3453static VALUE
3454top_ruby2_keywords(int argc, VALUE *argv, VALUE module)
3455{
3456 return rb_mod_ruby2_keywords(argc, argv, rb_top_main_class("ruby2_keywords"));
3457}
3458
3459/*
3460 * call-seq:
3461 * module_function -> nil
3462 * module_function(method_name) -> method_name
3463 * module_function(method_name, method_name, ...) -> array
3464 *
3465 * Creates module functions for the named methods. These functions may
3466 * be called with the module as a receiver, and also become available
3467 * as instance methods to classes that mix in the module. Module
3468 * functions are copies of the original, and so may be changed
3469 * independently. The instance-method versions are made private.
3470 * String arguments are converted to symbols.
3471 * If a single argument is passed, it is returned.
3472 * If no argument is passed, nil is returned.
3473 * If multiple arguments are passed, the arguments are returned as an array.
3474 *
3475 * module Mod
3476 * def one
3477 * "This is one"
3478 * end
3479 * module_function :one
3480 * end
3481 * class Cls
3482 * include Mod
3483 * def call_one
3484 * one
3485 * end
3486 * end
3487 * Mod.one #=> "This is one"
3488 * c = Cls.new
3489 * c.call_one #=> "This is one"
3490 * module Mod
3491 * def one
3492 * "This is the new one"
3493 * end
3494 * end
3495 * Mod.one #=> "This is one"
3496 * c.call_one #=> "This is the new one"
3497 *
3498 * If used with no arguments, subsequently defined methods become module
3499 * functions:
3500 *
3501 * module Mod
3502 * module_function
3503 *
3504 * def two
3505 * "This is two"
3506 * end
3507 * end
3508 * Mod.two #=> "This is two"
3509 */
3510
3511static VALUE
3512rb_mod_modfunc(int argc, VALUE *argv, VALUE module)
3513{
3514 int i;
3515 ID id;
3516 const rb_method_entry_t *me;
3517
3518 if (!RB_TYPE_P(module, T_MODULE)) {
3519 rb_raise(rb_eTypeError, "module_function must be called for modules");
3520 }
3521
3522 if (argc == 0) {
3523 rb_scope_module_func_set();
3524 return Qnil;
3525 }
3526
3527 set_method_visibility(module, argc, argv, METHOD_VISI_PRIVATE);
3528
3529 for (i = 0; i < argc; i++) {
3530 VALUE m = module;
3531
3532 id = rb_to_id(argv[i]);
3533 for (;;) {
3534 me = search_method(m, id, 0);
3535 if (me == 0) {
3536 me = search_method(rb_cObject, id, 0);
3537 }
3538 if (UNDEFINED_METHOD_ENTRY_P(me)) {
3539 rb_print_undef(module, id, METHOD_VISI_UNDEF);
3540 }
3541 if (me->def->type != VM_METHOD_TYPE_ZSUPER) {
3542 break; /* normal case: need not to follow 'super' link */
3543 }
3544 m = RCLASS_SUPER(m);
3545 if (!m)
3546 break;
3547 }
3548 rb_method_entry_set(rb_singleton_class(module), id, me, METHOD_VISI_PUBLIC);
3549 }
3550 if (argc == 1) {
3551 return argv[0];
3552 }
3553 return rb_ary_new_from_values(argc, argv);
3554}
3555
3556#ifdef __GNUC__
3557#pragma push_macro("rb_method_basic_definition_p")
3558#undef rb_method_basic_definition_p
3559#endif
3560int
3562{
3563 const rb_callable_method_entry_t *cme;
3564 if (!klass) return TRUE; /* hidden object cannot be overridden */
3565 cme = rb_callable_method_entry(klass, id);
3566 return (cme && METHOD_ENTRY_BASIC(cme)) ? TRUE : FALSE;
3567}
3568#ifdef __GNUC__
3569#pragma pop_macro("rb_method_basic_definition_p")
3570#endif
3571
3572static VALUE
3573call_method_entry(rb_execution_context_t *ec, VALUE defined_class, VALUE obj, ID id,
3574 const rb_callable_method_entry_t *cme, int argc, const VALUE *argv, int kw_splat)
3575{
3576 VALUE passed_block_handler = vm_passed_block_handler(ec);
3577 VALUE result = rb_vm_call_kw(ec, obj, id, argc, argv, cme, kw_splat);
3578 vm_passed_block_handler_set(ec, passed_block_handler);
3579 return result;
3580}
3581
3582static VALUE
3583basic_obj_respond_to_missing(rb_execution_context_t *ec, VALUE klass, VALUE obj,
3584 VALUE mid, VALUE priv)
3585{
3586 VALUE defined_class, args[2];
3587 const ID rtmid = idRespond_to_missing;
3588 const rb_callable_method_entry_t *const cme = callable_method_entry(klass, rtmid, &defined_class);
3589
3590 if (!cme || METHOD_ENTRY_BASIC(cme)) return Qundef;
3591 args[0] = mid;
3592 args[1] = priv;
3593 return call_method_entry(ec, defined_class, obj, rtmid, cme, 2, args, RB_NO_KEYWORDS);
3594}
3595
3596static inline int
3597basic_obj_respond_to(rb_execution_context_t *ec, VALUE obj, ID id, int pub)
3598{
3599 VALUE klass = CLASS_OF(obj);
3600 VALUE ret;
3601
3602 switch (method_boundp(klass, id, pub|BOUND_RESPONDS)) {
3603 case 2:
3604 return FALSE;
3605 case 0:
3606 ret = basic_obj_respond_to_missing(ec, klass, obj, ID2SYM(id),
3607 RBOOL(!pub));
3608 return RTEST(ret) && !UNDEF_P(ret);
3609 default:
3610 return TRUE;
3611 }
3612}
3613
3614static int
3615vm_respond_to(rb_execution_context_t *ec, VALUE klass, VALUE obj, ID id, int priv)
3616{
3617 VALUE defined_class;
3618 const ID resid = idRespond_to;
3619 const rb_callable_method_entry_t *const cme = callable_method_entry(klass, resid, &defined_class);
3620
3621 if (!cme) return -1;
3622 if (METHOD_ENTRY_BASIC(cme)) {
3623 return -1;
3624 }
3625 else {
3626 int argc = 1;
3627 VALUE args[2];
3628 VALUE result;
3629
3630 args[0] = ID2SYM(id);
3631 args[1] = Qtrue;
3632 if (priv) {
3633 argc = rb_method_entry_arity((const rb_method_entry_t *)cme);
3634 if (argc > 2) {
3635 rb_raise(rb_eArgError,
3636 "respond_to? must accept 1 or 2 arguments (requires %d)",
3637 argc);
3638 }
3639 if (argc != 1) {
3640 argc = 2;
3641 }
3642 else if (!NIL_P(ruby_verbose)) {
3643 VALUE location = rb_method_entry_location((const rb_method_entry_t *)cme);
3645 "%"PRIsVALUE"%c""respond_to?(:%"PRIsVALUE") uses"
3646 " the deprecated method signature, which takes one parameter",
3647 (RCLASS_SINGLETON_P(klass) ? obj : klass),
3648 (RCLASS_SINGLETON_P(klass) ? '.' : '#'),
3649 QUOTE_ID(id));
3650 if (!NIL_P(location)) {
3651 VALUE path = RARRAY_AREF(location, 0);
3652 VALUE line = RARRAY_AREF(location, 1);
3653 if (!NIL_P(path)) {
3655 RSTRING_PTR(path), NUM2INT(line),
3656 "respond_to? is defined here");
3657 }
3658 }
3659 }
3660 }
3661 result = call_method_entry(ec, defined_class, obj, resid, cme, argc, args, RB_NO_KEYWORDS);
3662 return RTEST(result);
3663 }
3664}
3665
3666int
3667rb_obj_respond_to(VALUE obj, ID id, int priv)
3668{
3669 rb_execution_context_t *ec = GET_EC();
3670 return rb_ec_obj_respond_to(ec, obj, id, priv);
3671}
3672
3673int
3674rb_ec_obj_respond_to(rb_execution_context_t *ec, VALUE obj, ID id, int priv)
3675{
3676 VALUE klass = CLASS_OF(obj);
3677 int ret = vm_respond_to(ec, klass, obj, id, priv);
3678 if (ret == -1) ret = basic_obj_respond_to(ec, obj, id, !priv);
3679 return ret;
3680}
3681
3682int
3684{
3685 return rb_obj_respond_to(obj, id, FALSE);
3686}
3687
3688
3689/*
3690 * call-seq:
3691 * obj.respond_to?(symbol, include_all=false) -> true or false
3692 * obj.respond_to?(string, include_all=false) -> true or false
3693 *
3694 * Returns +true+ if _obj_ responds to the given method. Private and
3695 * protected methods are included in the search only if the optional
3696 * second parameter evaluates to +true+.
3697 *
3698 * If the method is not implemented,
3699 * as Process.fork on Windows, File.lchmod on GNU/Linux, etc.,
3700 * false is returned.
3701 *
3702 * If the method is not defined, <code>respond_to_missing?</code>
3703 * method is called and the result is returned.
3704 *
3705 * When the method name parameter is given as a string, the string is
3706 * converted to a symbol.
3707 */
3708
3709static VALUE
3710obj_respond_to(int argc, VALUE *argv, VALUE obj)
3711{
3712 VALUE mid, priv;
3713 ID id;
3714 rb_execution_context_t *ec = GET_EC();
3715
3716 rb_scan_args(argc, argv, "11", &mid, &priv);
3717 if (!(id = rb_check_id(&mid))) {
3718 VALUE ret = basic_obj_respond_to_missing(ec, CLASS_OF(obj), obj,
3719 rb_to_symbol(mid), priv);
3720 if (UNDEF_P(ret)) ret = Qfalse;
3721 return ret;
3722 }
3723 return RBOOL(basic_obj_respond_to(ec, obj, id, !RTEST(priv)));
3724}
3725
3726/*
3727 * call-seq:
3728 * obj.respond_to_missing?(symbol, include_all) -> true or false
3729 * obj.respond_to_missing?(string, include_all) -> true or false
3730 *
3731 * DO NOT USE THIS DIRECTLY.
3732 *
3733 * Hook method to return whether the _obj_ can respond to _id_ method
3734 * or not.
3735 *
3736 * When the method name parameter is given as a string, the string is
3737 * converted to a symbol.
3738 *
3739 * See #respond_to?, and the example of BasicObject.
3740 */
3741static VALUE
3742obj_respond_to_missing(VALUE obj, VALUE mid, VALUE priv)
3743{
3744 return Qfalse;
3745}
3746
3747void
3748Init_eval_method(void)
3749{
3750 rb_define_method(rb_mKernel, "respond_to?", obj_respond_to, -1);
3751 rb_define_method(rb_mKernel, "respond_to_missing?", obj_respond_to_missing, 2);
3752
3753 rb_define_method(rb_cModule, "remove_method", rb_mod_remove_method, -1);
3754 rb_define_method(rb_cModule, "undef_method", rb_mod_undef_method, -1);
3755 rb_define_method(rb_cModule, "alias_method", rb_mod_alias_method, 2);
3756 rb_define_private_method(rb_cModule, "public", rb_mod_public, -1);
3757 rb_define_private_method(rb_cModule, "protected", rb_mod_protected, -1);
3758 rb_define_private_method(rb_cModule, "private", rb_mod_private, -1);
3759 rb_define_private_method(rb_cModule, "module_function", rb_mod_modfunc, -1);
3760 rb_define_private_method(rb_cModule, "ruby2_keywords", rb_mod_ruby2_keywords, -1);
3761
3762 rb_define_method(rb_cModule, "method_defined?", rb_mod_method_defined, -1);
3763 rb_define_method(rb_cModule, "public_method_defined?", rb_mod_public_method_defined, -1);
3764 rb_define_method(rb_cModule, "private_method_defined?", rb_mod_private_method_defined, -1);
3765 rb_define_method(rb_cModule, "protected_method_defined?", rb_mod_protected_method_defined, -1);
3766 rb_define_method(rb_cModule, "public_class_method", rb_mod_public_method, -1);
3767 rb_define_method(rb_cModule, "private_class_method", rb_mod_private_method, -1);
3768
3770 "public", top_public, -1);
3772 "private", top_private, -1);
3774 "ruby2_keywords", top_ruby2_keywords, -1);
3775
3776 {
3777#define REPLICATE_METHOD(klass, id) do { \
3778 const rb_method_entry_t *me = rb_method_entry((klass), (id)); \
3779 rb_method_entry_set((klass), (id), me, METHOD_ENTRY_VISI(me)); \
3780 } while (0)
3781
3782 REPLICATE_METHOD(rb_eException, idMethodMissing);
3783 REPLICATE_METHOD(rb_eException, idRespond_to);
3784 REPLICATE_METHOD(rb_eException, idRespond_to_missing);
3785 }
3786}
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
Definition assert.h:199
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define RUBY_ATOMIC_FETCH_ADD(var, val)
Atomically replaces the value pointed by var with the result of addition of val to the old value of v...
Definition atomic.h:118
#define RUBY_ATOMIC_FETCH_SUB(var, val)
Atomically replaces the value pointed by var with the result of subtraction of val to the old value o...
Definition atomic.h:129
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3051
void rb_class_modify_check(VALUE klass)
Asserts that klass is not a frozen class.
Definition eval.c:445
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3384
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define T_NONE
Old name of RUBY_T_NONE.
Definition value_type.h:74
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:127
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:126
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:478
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:476
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1473
void rb_category_compile_warn(rb_warning_category_t category, const char *file, int line, const char *fmt,...)
Identical to rb_compile_warn(), except it also accepts category.
Definition error.c:441
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:468
VALUE rb_eException
Mother of all exceptions.
Definition error.c:1465
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:499
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition error.h:48
VALUE rb_mKernel
Kernel module.
Definition object.c:59
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_cModule
Module class.
Definition object.c:61
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:140
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition vm_eval.c:1081
VALUE rb_call_super_kw(int argc, const VALUE *argv, int kw_splat)
Identical to rb_call_super(), except you can specify how to handle the last element of the given arra...
Definition vm_eval.c:355
VALUE rb_ary_new_from_values(long n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
void rb_undef(VALUE mod, ID mid)
Inserts a method entry that hides previous method definition of the given name.
Definition vm_method.c:2538
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:943
#define rb_str_new_lit(str)
Identical to rb_str_new_static(), except it cannot take string variables.
Definition string.h:1706
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1714
VALUE rb_mod_name(VALUE mod)
Queries the name of a module.
Definition variable.c:152
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:398
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3683
VALUE(* rb_alloc_func_t)(VALUE klass)
This is the type of functions that ruby calls when trying to allocate an object.
Definition vm.h:219
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1843
void rb_alias(VALUE klass, ID dst, ID src)
Resembles alias.
Definition vm_method.c:2936
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well... Let us hesitate from describing what a "basic definition" is.
Definition vm_method.c:3561
void rb_attr(VALUE klass, ID name, int need_reader, int need_writer, int honour_visibility)
This function resembles now-deprecated Module#attr.
Definition vm_method.c:2501
void rb_remove_method(VALUE klass, const char *name)
Removes a method.
Definition vm_method.c:2350
rb_alloc_func_t rb_get_alloc_func(VALUE klass)
Queries the allocator function of a class.
Definition vm_method.c:1852
void rb_clear_constant_cache_for_id(ID id)
Clears the inline constant caches associated with a particular ID.
Definition vm_method.c:333
void rb_remove_method_id(VALUE klass, ID mid)
Identical to rb_remove_method(), except it accepts the method name as ID.
Definition vm_method.c:2344
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
Definition vm_method.c:909
int rb_method_boundp(VALUE klass, ID id, int ex)
Queries if the klass has this method.
Definition vm_method.c:2462
int rb_obj_respond_to(VALUE obj, ID mid, int private_p)
Identical to rb_respond_to(), except it additionally takes the visibility parameter.
Definition vm_method.c:3667
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1289
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
Definition string.c:14138
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:14128
int capa
Designed capacity of the buffer.
Definition io.h:11
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SET_SHAREABLE(obj)
Wrapper of rb_obj_set_shareable().
Definition ractor.h:290
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_AREF(a, i)
Definition rarray.h:402
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
#define ANYARGS
Functions declared using this macro take arbitrary arguments, including void.
Definition stdarg.h:64
Definition vm_method.c:392
Definition vm_method.c:1451
Definition method.h:63
CREF (Class REFerence)
Definition method.h:45
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:242
size_t(* dsize)(const void *)
This function is to query the size of the underlying memory regions.
Definition rtypeddata.h:282
struct rb_data_type_struct::@64 function
Function pointers.
RUBY_DATA_FUNC dfree
This function is called when the object is no longer used.
Definition rtypeddata.h:272
const char * wrap_struct_name
Name of structs of this kind.
Definition rtypeddata.h:249
VALUE flags
Type-specific behavioural characteristics.
Definition rtypeddata.h:356
Definition method.h:55
rb_cref_t * cref
class reference, should be marked
Definition method.h:144
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition method.h:143
Definition st.h:79
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition value_type.h:182
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:425
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376