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