-
Notifications
You must be signed in to change notification settings - Fork 838
Expand file tree
/
Copy pathvm.c
More file actions
3723 lines (3360 loc) · 107 KB
/
Copy pathvm.c
File metadata and controls
3723 lines (3360 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** vm.c - virtual machine for mruby
**
** See Copyright Notice in mruby.h
*/
#include <mruby.h>
#include <mruby/array.h>
#include <mruby/class.h>
#include <mruby/hash.h>
#include <mruby/irep.h>
#include <mruby/numeric.h>
#include <mruby/proc.h>
#include <mruby/range.h>
#include <mruby/string.h>
#include <mruby/variable.h>
#include <mruby/error.h>
#include <mruby/opcode.h>
#include "value_array.h"
#include <mruby/throw.h>
#include <mruby/dump.h>
#include <mruby/internal.h>
#ifdef MRB_NO_STDIO
#if defined(__cplusplus)
extern "C" {
#endif
void abort(void);
#if defined(__cplusplus)
} /* extern "C" */
#endif
#endif
#define STACK_INIT_SIZE 128
#define CALLINFO_INIT_SIZE 32
/* Define amount of linear stack growth. */
#ifndef MRB_STACK_GROWTH
#define MRB_STACK_GROWTH 128
#endif
/* Maximum recursive depth. Should be set lower on memory constrained systems. */
#ifdef __clang__
#if __has_feature(address_sanitizer) && !defined(__SANITIZE_ADDRESS__)
#define __SANITIZE_ADDRESS__
#endif
#endif
#ifndef MRB_CALL_LEVEL_MAX
#if defined(__SANITIZE_ADDRESS__)
#define MRB_CALL_LEVEL_MAX 128
#else
#define MRB_CALL_LEVEL_MAX 512
#endif
#endif
/* Maximum stack depth. Should be set lower on memory constrained systems.
The value below allows about 60000 recursive calls in the simplest case. */
#ifndef MRB_STACK_MAX
#define MRB_STACK_MAX (0x40000 - MRB_STACK_GROWTH)
#endif
#ifdef VM_DEBUG
# define DEBUG(x) (x)
#else
# define DEBUG(x)
#endif
#ifndef MRB_GC_FIXED_ARENA
static void
mrb_gc_arena_shrink(mrb_state *mrb, int idx)
{
mrb_gc *gc = &mrb->gc;
int capa = gc->arena_capa;
gc->arena_idx = idx;
if (idx < capa / 4) {
capa >>= 2;
if (capa < MRB_GC_ARENA_SIZE) {
capa = MRB_GC_ARENA_SIZE;
}
if (capa != gc->arena_capa) {
gc->arena = (struct RBasic**)mrb_realloc(mrb, gc->arena, sizeof(struct RBasic*)*capa);
gc->arena_capa = capa;
}
}
}
#else
#define mrb_gc_arena_shrink(mrb, idx) mrb_gc_arena_restore(mrb, idx)
#endif
#define CALL_MAXARGS 15
#define CALL_VARARGS (CALL_MAXARGS<<4 | CALL_MAXARGS)
static inline void
stack_clear(mrb_value *from, size_t count)
{
while (count-- > 0) {
SET_NIL_VALUE(*from);
from++;
}
}
static inline void
stack_copy(mrb_value *dst, const mrb_value *src, size_t size)
{
if (!src) return;
memcpy(dst, src, sizeof(mrb_value)*size);
}
static void
stack_init(mrb_state *mrb)
{
struct mrb_context *c = mrb->c;
/* mrb_assert(mrb->stack == NULL); */
c->stbase = (mrb_value*)mrb_malloc(mrb, STACK_INIT_SIZE * sizeof(mrb_value));
c->stend = c->stbase + STACK_INIT_SIZE;
stack_clear(c->stbase, STACK_INIT_SIZE);
/* mrb_assert(ci == NULL); */
static const mrb_callinfo ci_zero = { 0 };
c->cibase = (mrb_callinfo*)mrb_malloc(mrb, CALLINFO_INIT_SIZE * sizeof(mrb_callinfo));
c->ciend = c->cibase + CALLINFO_INIT_SIZE;
c->cibase[0] = ci_zero;
c->ci = c->cibase;
c->ci->u.target_class = mrb->object_class;
c->ci->stack = c->stbase;
c->ci->vis = 1; /* private (2-bit packed) */
}
static inline void
envadjust(mrb_state *mrb, mrb_value *oldbase, mrb_value *newbase)
{
mrb_callinfo *ci = mrb->c->cibase;
/*
* Byte-level calculation to avoid truncation when allocator alignment is
* smaller than sizeof(mrb_value).
* eg: MRB_NO_BOXING + MRB_INT64 with MRB_32BIT => sizeof(mrb_value)=16
* And when memory allocator's alignment is 8 bytes
* Pointer subtraction on mrb_value* would truncate (8/16 -> 0).
* So, we use char* for pointer calculation to get the correct offset in bytes,
* then apply that offset to mrb_value* pointers.
*/
ptrdiff_t off = (char *)newbase - (char *)oldbase;
if (off == 0) return;
while (ci <= mrb->c->ci) {
struct REnv *e = mrb_vm_ci_env(ci);
mrb_value *new_stack = (mrb_value *)((char *)ci->stack + off);
if (e) {
mrb_assert(e->cxt == mrb->c && MRB_ENV_ONSTACK_P(e));
mrb_assert(e->stack == ci->stack);
e->stack = new_stack;
}
ci->stack = new_stack;
ci++;
}
}
/** def rec; $deep =+ 1; if $deep > 1000; return 0; end; rec; end **/
static void
stack_extend_alloc(mrb_state *mrb, mrb_int room)
{
mrb_value *oldbase = mrb->c->stbase;
size_t oldsize = mrb->c->stend - mrb->c->stbase;
size_t size = oldsize;
size_t off = mrb->c->ci->stack ? mrb->c->stend - mrb->c->ci->stack : 0;
if (off > size) size = off;
#ifdef MRB_STACK_EXTEND_DOUBLING
if ((size_t)room <= size)
size *= 2;
else
size += room;
#else
/* Use 1.5x stack growth.
It is slightly slower than doubling the stack space,
but it saves memory on small devices. */
{
size_t newsize = size + (size >> 1); /* 1.5x growth */
if (newsize < size + MRB_STACK_GROWTH)
newsize = size + MRB_STACK_GROWTH;
if (newsize < size + (size_t)room)
newsize = size + room;
size = newsize;
}
#endif
mrb_value *newstack = (mrb_value*)mrb_realloc(mrb, mrb->c->stbase, sizeof(mrb_value) * size);
stack_clear(&(newstack[oldsize]), size - oldsize);
envadjust(mrb, oldbase, newstack);
mrb->c->stbase = newstack;
mrb->c->stend = mrb->c->stbase + size;
/* Raise an exception if the new stack size will be too large,
to prevent infinite recursion. However, do this only after resizing the stack, so mrb_raise has stack space to work with. */
if (size > MRB_STACK_MAX) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->stack_err));
}
}
static inline void
stack_extend(mrb_state *mrb, mrb_int room)
{
if (mrb_unlikely(!mrb->c->ci->stack || mrb->c->ci->stack + room >= mrb->c->stend)) {
stack_extend_alloc(mrb, room);
}
}
/**
* @brief Extends the VM stack.
*
* This function extends the virtual machine stack to accommodate more values.
* If the current stack size is insufficient, it reallocates the stack
* with a larger size.
*
* @param mrb The mruby state.
* @param room The additional number of mrb_value slots required.
*/
MRB_API void
mrb_stack_extend(mrb_state *mrb, mrb_int room)
{
stack_extend(mrb, room);
}
static void
stack_extend_adjust(mrb_state *mrb, mrb_int room, const mrb_value **argp)
{
const struct mrb_context *c = mrb->c;
ptrdiff_t voff = *argp - c->stbase;
if (voff < 0 || voff >= c->stend - c->stbase) {
stack_extend(mrb, room);
}
else {
stack_extend(mrb, room);
*argp = c->stbase + voff;
}
}
static inline struct REnv*
uvenv(mrb_state *mrb, mrb_int up)
{
const struct RProc *proc = mrb->c->ci->proc;
while (up--) {
proc = proc->upper;
if (!proc) return NULL;
}
struct REnv *e = MRB_PROC_ENV(proc);
if (e) return e; /* proc has enclosed env */
return NULL;
}
static inline const struct RProc*
top_proc(mrb_state *mrb, const struct RProc *proc, const struct REnv **envp)
{
while (proc->upper) {
if (MRB_PROC_SCOPE_P(proc) || MRB_PROC_STRICT_P(proc))
return proc;
*envp = proc->e.env;
proc = proc->upper;
}
return proc;
}
#define CI_PROC_SET(ci, p) do {\
ci->proc = p;\
mrb_assert(!p || !MRB_PROC_ALIAS_P(p));\
ci->pc = (p && !MRB_PROC_CFUNC_P(p) && p->body.irep) ? p->body.irep->iseq : NULL;\
} while (0)
void
mrb_vm_ci_proc_set(mrb_callinfo *ci, const struct RProc *p)
{
CI_PROC_SET(ci, p);
}
#define MRB_PROC_RESOLVE_ALIAS(ci, p) do {\
if (MRB_PROC_ALIAS_P(p)) {\
(ci)->mid = (p)->body.mid;\
(p) = (p)->upper;\
}\
} while (0)
#define CI_TARGET_CLASS(ci) (((ci)->u.env && (ci)->u.env->tt == MRB_TT_ENV)? (ci)->u.env->c : (ci)->u.target_class)
struct RClass*
mrb_vm_ci_target_class(const mrb_callinfo *ci)
{
return CI_TARGET_CLASS(ci);
}
void
mrb_vm_ci_target_class_set(mrb_callinfo *ci, struct RClass *tc)
{
struct REnv *e = ci->u.env;
if (e && e->tt == MRB_TT_ENV) {
e->c = tc;
}
else {
ci->u.target_class = tc;
}
}
#define CI_ENV(ci) (((ci)->u.env && (ci)->u.env->tt == MRB_TT_ENV)? (ci)->u.env : NULL)
struct REnv*
mrb_vm_ci_env(const mrb_callinfo *ci)
{
return CI_ENV(ci);
}
static inline void
ci_env_set(mrb_callinfo *ci, struct REnv *e)
{
if (ci->u.env) {
if (ci->u.env->tt == MRB_TT_ENV) {
if (e) {
e->c = ci->u.env->c;
ci->u.env = e;
}
else {
ci->u.target_class = ci->u.env->c;
}
}
else if (e) {
e->c = ci->u.target_class;
ci->u.env = e;
}
}
else {
ci->u.env = e;
}
}
void
mrb_vm_ci_env_set(mrb_callinfo *ci, struct REnv *e)
{
ci_env_set(ci, e);
}
MRB_API void
mrb_vm_ci_env_clear(mrb_state *mrb, mrb_callinfo *ci)
{
struct REnv *e = ci->u.env;
if (e && e->tt == MRB_TT_ENV) {
ci->u.target_class = e->c;
mrb_env_unshare(mrb, e, FALSE);
}
}
#define CINFO_NONE 0 // called method from mruby VM (without C functions)
#define CINFO_SKIP 1 // ignited mruby VM from C
#define CINFO_DIRECT 2 // called method from C
#define CINFO_RESUMED 3 // resumed by `Fiber.yield` (probably the main call is `mrb_fiber_resume()`)
#define BLK_PTR(b) ((mrb_proc_p(b)) ? mrb_proc_ptr(b) : NULL)
static inline mrb_callinfo*
cipush(mrb_state *mrb, mrb_int push_stacks, uint8_t cci, struct RClass *target_class,
const struct RProc *proc, struct RProc *blk, mrb_sym mid, uint16_t argc)
{
struct mrb_context *c = mrb->c;
mrb_callinfo *ci = c->ci + 1;
if (ci < c->ciend) {
c->ci = ci;
}
else {
ptrdiff_t size = ci - c->cibase;
if (size >= MRB_CALL_LEVEL_MAX) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->stack_err));
}
c->cibase = (mrb_callinfo*)mrb_realloc(mrb, c->cibase, sizeof(mrb_callinfo)*size*2);
c->ci = ci = c->cibase + size;
c->ciend = c->cibase + size * 2;
}
ci->mid = mid;
CI_PROC_SET(ci, proc);
ci->blk = blk;
ci->stack = ci[-1].stack + push_stacks;
ci->n = argc & 0xf;
ci->nk = (argc>>4) & 0xf;
ci->cci = cci;
ci->vis = MRB_METHOD_PUBLIC_FL;
ci->u.target_class = target_class;
return ci;
}
static void
fiber_terminate(mrb_state *mrb, struct mrb_context *c, mrb_callinfo *ci)
{
mrb_assert(c != mrb->root_c);
struct REnv *env = CI_ENV(ci);
mrb_assert(env == NULL || MRB_ENV_LEN(env) <= c->stend - ci->stack);
c->status = MRB_FIBER_TERMINATED;
mrb_free(mrb, c->cibase);
c->cibase = c->ciend = c->ci = NULL;
mrb_value *stack = c->stbase;
c->stbase = c->stend = NULL;
if (!env) {
mrb_free(mrb, stack);
}
else {
size_t len = (size_t)MRB_ENV_LEN(env);
if (len == 0) {
env->stack = NULL;
MRB_ENV_CLOSE(env);
mrb_free(mrb, stack);
}
else {
mrb_assert(stack == env->stack);
mrb_write_barrier(mrb, (struct RBasic*)env);
// don't call MRB_ENV_CLOSE() before mrb_realloc().
// the reason is that env->stack may be freed by mrb_realloc() if MRB_DEBUG + MRB_GC_STRESS are enabled.
// realloc() on a freed heap will cause double-free.
stack = (mrb_value*)mrb_realloc(mrb, stack, len * sizeof(mrb_value));
if (mrb_object_dead_p(mrb, (struct RBasic*)env)) {
mrb_free(mrb, stack);
}
else {
env->stack = stack;
MRB_ENV_CLOSE(env);
}
}
}
/* fiber termination should automatic yield or transfer to root */
mrb->c = c->prev;
if (!mrb->c) mrb->c = mrb->root_c;
else c->prev = NULL;
mrb->c->status = MRB_FIBER_RUNNING;
}
mrb_bool
mrb_env_unshare(mrb_state *mrb, struct REnv *e, mrb_bool noraise)
{
mrb_assert(e != NULL);
mrb_assert(MRB_ENV_ONSTACK_P(e));
size_t len = (size_t)MRB_ENV_LEN(e);
if (len == 0) {
e->stack = NULL;
MRB_ENV_CLOSE(e);
return TRUE;
}
size_t live = mrb->gc.live;
mrb_value *p = (mrb_value*)mrb_malloc_simple(mrb, sizeof(mrb_value)*len);
if (live != mrb->gc.live && mrb_object_dead_p(mrb, (struct RBasic*)e)) {
// The e object is now subject to GC inside mrb_malloc_simple().
// Moreover, if NULL is returned due to mrb_malloc_simple() failure, simply ignore it.
mrb_free(mrb, p);
return TRUE;
}
else if (p) {
stack_copy(p, e->stack, len);
e->stack = p;
MRB_ENV_CLOSE(e);
mrb_write_barrier(mrb, (struct RBasic*)e);
return TRUE;
}
else {
e->stack = NULL;
MRB_ENV_CLOSE(e);
MRB_ENV_SET_LEN(e, 0);
MRB_ENV_SET_BIDX(e, 0);
if (!noraise) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->nomem_err));
}
return FALSE;
}
}
static inline mrb_callinfo*
cipop(mrb_state *mrb)
{
struct mrb_context *c = mrb->c;
mrb_callinfo *ci = c->ci;
struct REnv *env = CI_ENV(ci);
ci_env_set(ci, NULL); // make possible to free env by GC if not needed
struct RProc *b = ci->blk;
if (b && !MRB_PROC_STRICT_P(b) && MRB_PROC_ENV(b) == CI_ENV(&ci[-1])) {
b->flags |= MRB_PROC_ORPHAN;
}
if (env && !mrb_env_unshare(mrb, env, TRUE)) {
c->ci--; // exceptions are handled at the method caller; see #3087
mrb_exc_raise(mrb, mrb_obj_value(mrb->nomem_err));
}
c->ci--;
return c->ci;
}
/**
* @brief Protects a C function call from mruby exceptions.
*
* This function executes a C function (`body`) within a protected environment.
* If an mruby exception occurs during the execution of `body`, this function
* catches the exception, sets the `error` flag, and returns the exception object.
* Otherwise, it returns the result of the `body` function and `error` remains FALSE.
*
* This is crucial for calling mruby-related C functions from within C code
* that needs to handle potential mruby exceptions gracefully.
*
* @param mrb The mruby state.
* @param body A pointer to the C function to be executed.
* The function should have the signature: `mrb_value func(mrb_state *mrb, void *userdata)`
* @param userdata A pointer to arbitrary data that will be passed to the `body` function.
* @param error A pointer to an mrb_bool that will be set to TRUE if an exception
* occurred, and FALSE otherwise. Can be NULL if not needed.
* @return The value returned by the `body` function if no exception occurred,
* or the exception object if an exception occurred.
*/
MRB_API mrb_value
mrb_protect_error(mrb_state *mrb, mrb_protect_error_func *body, void *userdata, mrb_bool *error)
{
struct mrb_jmpbuf *prev_jmp = mrb->jmp;
struct mrb_jmpbuf c_jmp;
mrb_value result;
int ai = mrb_gc_arena_save(mrb);
const struct mrb_context *c = mrb->c;
ptrdiff_t ci_index = c->ci - c->cibase;
if (error) { *error = FALSE; }
MRB_TRY(&c_jmp) {
mrb->jmp = &c_jmp;
result = body(mrb, userdata);
mrb->jmp = prev_jmp;
}
MRB_CATCH(&c_jmp) {
mrb->jmp = prev_jmp;
result = mrb_obj_value(mrb->exc);
mrb->exc = NULL;
if (error) { *error = TRUE; }
if (mrb->c == c) {
while (c->ci - c->cibase > ci_index) {
cipop(mrb);
}
}
else {
// It was probably switched by mrb_fiber_resume().
// Simply destroy all successive CINFO_DIRECTs once the fiber has been switched.
c = mrb->c;
while (c->ci > c->cibase && c->ci->cci == CINFO_DIRECT) {
cipop(mrb);
}
}
}
MRB_END_EXC(&c_jmp);
mrb_gc_arena_restore(mrb, ai);
mrb_gc_protect(mrb, result);
return result;
}
void mrb_exc_set(mrb_state *mrb, mrb_value exc);
static mrb_value mrb_run(mrb_state *mrb, const struct RProc* proc, mrb_value self);
#ifndef MRB_FUNCALL_ARGC_MAX
#define MRB_FUNCALL_ARGC_MAX 16
#endif
/**
* @brief Calls a method on an object.
*
* This function invokes a method identified by its name on the `self` object,
* passing the given arguments.
*
* @param mrb The mruby state.
* @param self The receiver object of the method call.
* @param name The name of the method to call (C string).
* @param argc The number of arguments to pass to the method.
* @param ... The variable arguments to pass to the method.
* Each argument must be of type `mrb_value`.
* @return The result of the method call.
* @raise E_ARGUMENT_ERROR if `argc` is greater than `MRB_FUNCALL_ARGC_MAX`.
*/
MRB_API mrb_value
mrb_funcall(mrb_state *mrb, mrb_value self, const char *name, mrb_int argc, ...)
{
mrb_value argv[MRB_FUNCALL_ARGC_MAX];
mrb_sym mid = mrb_intern_cstr(mrb, name);
if (argc > MRB_FUNCALL_ARGC_MAX) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "Too long arguments. (limit=" MRB_STRINGIZE(MRB_FUNCALL_ARGC_MAX) ")");
}
va_list ap;
va_start(ap, argc);
for (mrb_int i = 0; i < argc; i++) {
argv[i] = va_arg(ap, mrb_value);
}
va_end(ap);
return mrb_funcall_argv(mrb, self, mid, argc, argv);
}
/**
* @brief Calls a method on an object using a method ID.
*
* This function invokes a method identified by its symbol ID (`mid`) on
* the `self` object, passing the given arguments. Using a method ID
* can be more efficient than using a string name if the method is called
* frequently, as it avoids repeated string-to-symbol lookups.
*
* @param mrb The mruby state.
* @param self The receiver object of the method call.
* @param mid The symbol ID of the method to call.
* @param argc The number of arguments to pass to the method.
* @param ... The variable arguments to pass to the method.
* Each argument must be of type `mrb_value`.
* @return The result of the method call.
* @raise E_ARGUMENT_ERROR if `argc` is greater than `MRB_FUNCALL_ARGC_MAX`.
*/
MRB_API mrb_value
mrb_funcall_id(mrb_state *mrb, mrb_value self, mrb_sym mid, mrb_int argc, ...)
{
mrb_value argv[MRB_FUNCALL_ARGC_MAX];
if (argc > MRB_FUNCALL_ARGC_MAX) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "Too long arguments. (limit=" MRB_STRINGIZE(MRB_FUNCALL_ARGC_MAX) ")");
}
va_list ap;
va_start(ap, argc);
for (mrb_int i = 0; i < argc; i++) {
argv[i] = va_arg(ap, mrb_value);
}
va_end(ap);
return mrb_funcall_argv(mrb, self, mid, argc, argv);
}
static mrb_int
mrb_ci_kidx(const mrb_callinfo *ci)
{
if (ci->nk == 0) return -1;
return (ci->n == CALL_MAXARGS) ? 2 : ci->n + 1;
}
static inline mrb_int
mrb_bidx(uint8_t n, uint8_t k)
{
if (n == 15) n = 1;
if (k == 15) n += 1;
else n += k*2;
return n + 1; /* self + args + kargs */
}
static inline mrb_int
ci_bidx(mrb_callinfo *ci)
{
return mrb_bidx(ci->n, ci->nk);
}
mrb_int
mrb_ci_bidx(mrb_callinfo *ci)
{
return ci_bidx(ci);
}
mrb_int
mrb_ci_nregs(mrb_callinfo *ci)
{
if (!ci) return 4;
mrb_int nregs = ci_bidx(ci) + 1; /* self + args + kargs + blk */
const struct RProc *p = ci->proc;
if (p && !MRB_PROC_CFUNC_P(p) && p->body.irep && p->body.irep->nregs > nregs) {
return p->body.irep->nregs;
}
return nregs;
}
mrb_value mrb_obj_missing(mrb_state *mrb, mrb_value mod);
static mrb_method_t
prepare_missing(mrb_state *mrb, mrb_callinfo *ci, mrb_value recv, mrb_sym mid, mrb_value blk, mrb_bool super)
{
mrb_sym missing = MRB_SYM(method_missing);
mrb_value *argv = &ci->stack[1];
mrb_value args;
mrb_method_t m;
/* pack positional arguments */
if (ci->n == 15) args = argv[0];
else args = mrb_ary_new_from_values(mrb, ci->n, argv);
if (mrb_func_basic_p(mrb, recv, missing, mrb_obj_missing)) {
method_missing:
if (super) mrb_no_method_error(mrb, mid, args, "no superclass method '%n' for %T", mid, recv);
else mrb_method_missing(mrb, mid, recv, args);
/* not reached */
}
if (mid != missing) {
ci->u.target_class = mrb_class(mrb, recv);
}
m = mrb_vm_find_method(mrb, ci->u.target_class, &ci->u.target_class, missing);
if (MRB_METHOD_UNDEF_P(m)) goto method_missing; /* just in case */
stack_extend(mrb, 4);
argv = &ci->stack[1]; /* maybe reallocated */
if (ci->nk == 0) {
argv[1] = blk;
}
else {
mrb_assert(ci->nk == 15);
if (ci->n != CALL_MAXARGS) {
argv[1] = argv[ci->n]; /* keyword arguments */
}
argv[2] = blk;
}
argv[0] = args; /* must be replaced after saving argv[0] as it may be a keyword argument */
ci->n = CALL_MAXARGS;
/* ci->nk is already set to zero or CALL_MAXARGS */
mrb_ary_unshift(mrb, args, mrb_symbol_value(mid));
ci->mid = missing;
return m;
}
static void
funcall_args_capture(mrb_state *mrb, int stoff, mrb_int argc, const mrb_value *argv, mrb_value block, mrb_callinfo *ci)
{
if (argc < 0 || argc > INT32_MAX) {
mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative or too big argc for funcall (%i)", argc);
}
ci->nk = 0; /* funcall does not support keyword arguments */
if (argc < CALL_MAXARGS) {
mrb_int extends = stoff + argc + 2 /* self + block */;
stack_extend_adjust(mrb, extends, &argv);
mrb_value *args = mrb->c->ci->stack + stoff + 1 /* self */;
stack_copy(args, argv, argc);
args[argc] = block;
ci->n = (uint8_t)argc;
}
else {
int extends = stoff + 3 /* self + splat + block */;
stack_extend_adjust(mrb, extends, &argv);
mrb_value *args = mrb->c->ci->stack + stoff + 1 /* self */;
args[0] = mrb_ary_new_from_values(mrb, argc, argv);
args[1] = block;
ci->n = CALL_MAXARGS;
}
}
static inline mrb_value
ensure_block(mrb_state *mrb, mrb_value blk)
{
if (!mrb_nil_p(blk) && !mrb_proc_p(blk)) {
blk = mrb_type_convert(mrb, blk, MRB_TT_PROC, MRB_SYM(to_proc));
/* The stack might have been reallocated during mrb_type_convert(), see #3622 */
}
return blk;
}
/**
* @brief Calls a method on an object with a block.
*
* This function invokes a method identified by its symbol ID (`mid`) on
* the `self` object, passing the given arguments (`argv`) and a block (`blk`).
*
* @param mrb The mruby state.
* @param self The receiver object of the method call.
* @param mid The symbol ID of the method to call.
* @param argc The number of arguments in `argv`.
* @param argv A pointer to an array of `mrb_value` arguments.
* @param blk The block to pass to the method. If no block is to be passed,
* use `mrb_nil_value()`. If `blk` is not nil and not a proc,
* it will be converted to a proc using `to_proc`.
* @return The result of the method call.
* @raise E_ARGUMENT_ERROR if `argc` is negative or too large.
* @raise E_STACK_ERROR if the call level exceeds `MRB_CALL_LEVEL_MAX`.
*/
MRB_API mrb_value
mrb_funcall_with_block(mrb_state *mrb, mrb_value self, mrb_sym mid, mrb_int argc, const mrb_value *argv, mrb_value blk)
{
mrb_value val;
int ai = mrb_gc_arena_save(mrb);
if (!mrb->jmp) {
struct mrb_jmpbuf c_jmp;
ptrdiff_t nth_ci = mrb->c->ci - mrb->c->cibase;
MRB_TRY(&c_jmp) {
mrb->jmp = &c_jmp;
/* recursive call */
val = mrb_funcall_with_block(mrb, self, mid, argc, argv, blk);
mrb->jmp = NULL;
}
MRB_CATCH(&c_jmp) { /* error */
while (nth_ci < (mrb->c->ci - mrb->c->cibase)) {
cipop(mrb);
}
mrb->jmp = 0;
val = mrb_obj_value(mrb->exc);
}
MRB_END_EXC(&c_jmp);
mrb->jmp = NULL;
}
else {
mrb_method_t m;
mrb_callinfo *ci = mrb->c->ci;
mrb_int n = mrb_ci_nregs(ci);
if (!mrb->c->stbase) {
stack_init(mrb);
}
if (ci - mrb->c->cibase > MRB_CALL_LEVEL_MAX) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->stack_err));
}
blk = ensure_block(mrb, blk);
ci = cipush(mrb, n, CINFO_DIRECT, NULL, NULL, BLK_PTR(blk), 0, 0);
funcall_args_capture(mrb, 0, argc, argv, blk, ci);
ci->u.target_class = mrb_class(mrb, self);
m = mrb_vm_find_method(mrb, ci->u.target_class, &ci->u.target_class, mid);
if (MRB_METHOD_UNDEF_P(m)) {
m = prepare_missing(mrb, ci, self, mid, mrb_nil_value(), FALSE);
}
else {
ci->mid = mid;
}
ci->proc = MRB_METHOD_PROC_P(m) ? MRB_METHOD_PROC(m) : NULL;
if (MRB_METHOD_CFUNC_P(m)) {
mrb->exc = NULL;
ci->stack[0] = self;
val = MRB_METHOD_CFUNC(m)(mrb, self);
cipop(mrb);
if (mrb->exc != NULL) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->exc));
}
}
else {
/* handle alias */
MRB_PROC_RESOLVE_ALIAS(ci, ci->proc);
ci->cci = CINFO_SKIP;
val = mrb_run(mrb, ci->proc, self);
}
}
mrb_gc_arena_restore(mrb, ai);
mrb_gc_protect(mrb, val);
return val;
}
/**
* @brief Calls a method on an object with an array of arguments.
*
* This function is similar to `mrb_funcall_with_block` but takes arguments
* as a C array (`argv`) and does not take an explicit block argument.
* If a block is needed, `mrb_funcall_with_block` should be used.
* This function is essentially a convenience wrapper around
* `mrb_funcall_with_block` with `mrb_nil_value()` for the block.
*
* @param mrb The mruby state.
* @param self The receiver object of the method call.
* @param mid The symbol ID of the method to call.
* @param argc The number of arguments in `argv`.
* @param argv A pointer to an array of `mrb_value` arguments.
* @return The result of the method call.
* @see mrb_funcall_with_block
*/
MRB_API mrb_value
mrb_funcall_argv(mrb_state *mrb, mrb_value self, mrb_sym mid, mrb_int argc, const mrb_value *argv)
{
return mrb_funcall_with_block(mrb, self, mid, argc, argv, mrb_nil_value());
}
static void
check_argument_count(mrb_state *mrb, const mrb_callinfo *ci, mrb_aspec aspec)
{
mrb_int argc = ci->n;
if (mrb_unlikely(argc == CALL_MAXARGS)) {
argc = RARRAY_LEN(ci->stack[1]);
}
/* keyword hash counts as positional if method doesn't accept keywords */
if (ci->nk > 0 && MRB_ASPEC_KEY(aspec) == 0 && !MRB_ASPEC_KDICT(aspec)) {
mrb_value kdict = ci->stack[mrb_ci_kidx(ci)];
if (mrb_hash_p(kdict) && !mrb_hash_empty_p(mrb, kdict)) {
argc++;
}
}
int min = MRB_ASPEC_REQ(aspec) + MRB_ASPEC_POST(aspec);
int max = MRB_ASPEC_REST(aspec) ? -1 : min + MRB_ASPEC_OPT(aspec);
if (mrb_unlikely(argc < min || (max >= 0 && argc > max))) {
mrb_argnum_error(mrb, argc, min, max);
}
}
static mrb_value
exec_irep(mrb_state *mrb, mrb_value self, const struct RProc *p)
{
mrb_callinfo *ci = mrb->c->ci;
ci->stack[0] = self;
/* handle alias */
MRB_PROC_RESOLVE_ALIAS(ci, p);
CI_PROC_SET(ci, p);
if (MRB_PROC_CFUNC_P(p)) {
if (MRB_PROC_NOARG_P(p) && (ci->n > 0 || ci->nk > 0)) {
check_argument_count(mrb, ci, 0);
}
return MRB_PROC_CFUNC(p)(mrb, self);
}
mrb_int nregs = p->body.irep->nregs;
mrb_int keep = ci_bidx(ci)+1;
if (nregs < keep) {
stack_extend(mrb, keep);
}
else {
stack_extend(mrb, nregs);
stack_clear(ci->stack+keep, nregs-keep);
}
cipush(mrb, 0, 0, NULL, NULL, NULL, 0, 0);
return self;
}
mrb_value
mrb_exec_irep(mrb_state *mrb, mrb_value self, const struct RProc *p)
{
mrb_callinfo *ci = mrb->c->ci;
if (ci->cci == CINFO_NONE) {
return exec_irep(mrb, self, p);
}
else {
mrb_value ret;
if (MRB_PROC_CFUNC_P(p)) {
if (MRB_PROC_NOARG_P(p) && (ci->n > 0 || ci->nk > 0)) {
check_argument_count(mrb, ci, 0);
}
ci = cipush(mrb, 0, CINFO_DIRECT, CI_TARGET_CLASS(ci), p, NULL, ci->mid, ci->n|(ci->nk<<4));
mrb->exc = NULL;
ret = MRB_PROC_CFUNC(p)(mrb, self);
cipop(mrb);
}
else {
mrb_int keep = ci_bidx(ci) + 1; /* receiver + block */
ci = cipush(mrb, 0, CINFO_SKIP, CI_TARGET_CLASS(ci), p, NULL, ci->mid, ci->n|(ci->nk<<4));
ret = mrb_vm_run(mrb, p, self, keep);
}
if (mrb->exc && mrb->jmp) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->exc));
}
return ret;
}
}
mrb_value
mrb_object_exec(mrb_state *mrb, mrb_value self, struct RClass *target_class)
{
mrb_callinfo *ci = mrb->c->ci;
mrb_int bidx = ci_bidx(ci);
mrb_value blk = ci->stack[bidx];
if (mrb_nil_p(blk)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "no block given");
}
mrb_assert(mrb_proc_p(blk));
mrb_gc_protect(mrb, blk);
ci->stack[bidx] = mrb_nil_value();
mrb_vm_ci_target_class_set(ci, target_class);
return mrb_exec_irep(mrb, self, mrb_proc_ptr(blk));
}
static mrb_noreturn void
vis_error(mrb_state *mrb, mrb_sym mid, mrb_value args, mrb_value recv, mrb_bool priv)
{
mrb_no_method_error(mrb, mid, args, "%s method '%n' called for %T", (priv ? "private" : "protected"), mid, recv);
}
static mrb_value
send_method(mrb_state *mrb, mrb_value self, mrb_bool pub)
{
mrb_callinfo *ci = mrb->c->ci;
int n = ci->n;
mrb_sym name;
if (ci->cci > CINFO_NONE) {
funcall:;
const mrb_value *argv;
mrb_int argc;
mrb_value block;
mrb_get_args(mrb, "n*&", &name, &argv, &argc, &block);
return mrb_funcall_with_block(mrb, self, name, argc, argv, block);