summaryrefslogtreecommitdiff
path: root/vm_trace.c
blob: 0b9bd53ebe8d445615c4558b6a8e5396fc8b3af8 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
/**********************************************************************

  vm_trace.c -

  $Author: ko1 $
  created at: Tue Aug 14 19:37:09 2012

  Copyright (C) 1993-2012 Yukihiro Matsumoto

**********************************************************************/

/*
 * This file include two parts:
 *
 * (1) set_trace_func internal mechanisms
 *     and C level API
 *
 * (2) Ruby level API
 *  (2-1) set_trace_func API
 *  (2-2) TracePoint API (not yet)
 *
 */

#include "eval_intern.h"
#include "internal.h"
#include "internal/hash.h"
#include "internal/symbol.h"
#include "iseq.h"
#include "mjit.h"
#include "ruby/debug.h"
#include "vm_core.h"
#include "ruby/ractor.h"
#include "yjit.h"

#include "builtin.h"

static VALUE sym_default;

/* (1) trace mechanisms */

typedef struct rb_event_hook_struct {
    rb_event_hook_flag_t hook_flags;
    rb_event_flag_t events;
    rb_event_hook_func_t func;
    VALUE data;
    struct rb_event_hook_struct *next;

    struct {
        rb_thread_t *th;
        unsigned int target_line;
    } filter;
} rb_event_hook_t;

typedef void (*rb_event_hook_raw_arg_func_t)(VALUE data, const rb_trace_arg_t *arg);

#define MAX_EVENT_NUM 32

void
rb_hook_list_mark(rb_hook_list_t *hooks)
{
    rb_event_hook_t *hook = hooks->hooks;

    while (hook) {
        rb_gc_mark(hook->data);
        hook = hook->next;
    }
}

static void clean_hooks(const rb_execution_context_t *ec, rb_hook_list_t *list);

void
rb_hook_list_free(rb_hook_list_t *hooks)
{
    hooks->need_clean = true;

    if (hooks->running == 0) {
        clean_hooks(GET_EC(), hooks);
    }
}

/* ruby_vm_event_flags management */

void rb_clear_attr_ccs(void);

static void
update_global_event_hook(rb_event_flag_t prev_events, rb_event_flag_t new_events)
{
    rb_event_flag_t new_iseq_events = new_events & ISEQ_TRACE_EVENTS;
    rb_event_flag_t enabled_iseq_events = ruby_vm_event_enabled_global_flags & ISEQ_TRACE_EVENTS;
    bool first_time_iseq_events_p = new_iseq_events & ~enabled_iseq_events;
    bool enable_c_call   = (prev_events & RUBY_EVENT_C_CALL)   == 0 && (new_events & RUBY_EVENT_C_CALL);
    bool enable_c_return = (prev_events & RUBY_EVENT_C_RETURN) == 0 && (new_events & RUBY_EVENT_C_RETURN);

    if (first_time_iseq_events_p) {
        // :class events are triggered only in ISEQ_TYPE_CLASS, but mjit_target_iseq_p ignores such iseqs.
        // Thus we don't need to cancel JIT-ed code for :class events.
        if (new_iseq_events != RUBY_EVENT_CLASS) {
            // Stop calling all JIT-ed code. We can't rewrite existing JIT-ed code to trace_ insns for now.
            mjit_cancel_all("TracePoint is enabled");
        }

        // write all ISeqs only when new events are added for the first time
        rb_iseq_trace_set_all(new_iseq_events | enabled_iseq_events);
    }
    else {
        // if c_call or c_return is activated:
        if (enable_c_call || enable_c_return) {
            rb_clear_attr_ccs();
        }
    }

    ruby_vm_event_flags = new_events;
    ruby_vm_event_enabled_global_flags |= new_events;
    rb_objspace_set_event_hook(new_events);

    if (first_time_iseq_events_p || enable_c_call || enable_c_return) {
        // Invalidate all code when ISEQs are modified to use trace_* insns above.
        // Also invalidate when enabling c_call or c_return because generated code
        // never fires these events.
        // Internal events fire inside C routines so don't need special handling.
        // Do this after event flags updates so other ractors see updated vm events
        // when they wake up.
        rb_yjit_tracing_invalidate_all();
    }
}

/* add/remove hooks */

static rb_event_hook_t *
alloc_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data, rb_event_hook_flag_t hook_flags)
{
    rb_event_hook_t *hook;

    if ((events & RUBY_INTERNAL_EVENT_MASK) && (events & ~RUBY_INTERNAL_EVENT_MASK)) {
        rb_raise(rb_eTypeError, "Can not specify normal event and internal event simultaneously.");
    }

    hook = ALLOC(rb_event_hook_t);
    hook->hook_flags = hook_flags;
    hook->events = events;
    hook->func = func;
    hook->data = data;

    /* no filters */
    hook->filter.th = NULL;
    hook->filter.target_line = 0;

    return hook;
}

static void
hook_list_connect(VALUE list_owner, rb_hook_list_t *list, rb_event_hook_t *hook, int global_p)
{
    rb_event_flag_t prev_events = list->events;
    hook->next = list->hooks;
    list->hooks = hook;
    list->events |= hook->events;

    if (global_p) {
        /* global hooks are root objects at GC mark. */
        update_global_event_hook(prev_events, list->events);
    }
    else {
        RB_OBJ_WRITTEN(list_owner, Qundef, hook->data);
    }
}

static void
connect_event_hook(const rb_execution_context_t *ec, rb_event_hook_t *hook)
{
    rb_hook_list_t *list = rb_ec_ractor_hooks(ec);
    hook_list_connect(Qundef, list, hook, TRUE);
}

static void
rb_threadptr_add_event_hook(const rb_execution_context_t *ec, rb_thread_t *th,
                            rb_event_hook_func_t func, rb_event_flag_t events, VALUE data, rb_event_hook_flag_t hook_flags)
{
    rb_event_hook_t *hook = alloc_event_hook(func, events, data, hook_flags);
    hook->filter.th = th;
    connect_event_hook(ec, hook);
}

void
rb_thread_add_event_hook(VALUE thval, rb_event_hook_func_t func, rb_event_flag_t events, VALUE data)
{
    rb_threadptr_add_event_hook(GET_EC(), rb_thread_ptr(thval), func, events, data, RUBY_EVENT_HOOK_FLAG_SAFE);
}

void
rb_add_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data)
{
    rb_add_event_hook2(func, events, data, RUBY_EVENT_HOOK_FLAG_SAFE);
}

void
rb_thread_add_event_hook2(VALUE thval, rb_event_hook_func_t func, rb_event_flag_t events, VALUE data, rb_event_hook_flag_t hook_flags)
{
    rb_threadptr_add_event_hook(GET_EC(), rb_thread_ptr(thval), func, events, data, hook_flags);
}

void
rb_add_event_hook2(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data, rb_event_hook_flag_t hook_flags)
{
    rb_event_hook_t *hook = alloc_event_hook(func, events, data, hook_flags);
    connect_event_hook(GET_EC(), hook);
}

static void
clean_hooks(const rb_execution_context_t *ec, rb_hook_list_t *list)
{
    rb_event_hook_t *hook, **nextp = &list->hooks;
    rb_event_flag_t prev_events = list->events;

    VM_ASSERT(list->running == 0);
    VM_ASSERT(list->need_clean == true);

    list->events = 0;
    list->need_clean = false;

    while ((hook = *nextp) != 0) {
        if (hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) {
            *nextp = hook->next;
            xfree(hook);
        }
        else {
            list->events |= hook->events; /* update active events */
            nextp = &hook->next;
        }
    }

    if (list->is_local) {
        if (list->events == 0) {
            /* local events */
            ruby_xfree(list);
        }
    }
    else {
        update_global_event_hook(prev_events, list->events);
    }
}

static void
clean_hooks_check(const rb_execution_context_t *ec, rb_hook_list_t *list)
{
    if (UNLIKELY(list->need_clean)) {
        if (list->running == 0) {
            clean_hooks(ec, list);
        }
    }
}

#define MATCH_ANY_FILTER_TH ((rb_thread_t *)1)

/* if func is 0, then clear all funcs */
static int
remove_event_hook(const rb_execution_context_t *ec, const rb_thread_t *filter_th, rb_event_hook_func_t func, VALUE data)
{
    rb_hook_list_t *list = rb_ec_ractor_hooks(ec);
    int ret = 0;
    rb_event_hook_t *hook = list->hooks;

    while (hook) {
        if (func == 0 || hook->func == func) {
            if (hook->filter.th == filter_th || filter_th == MATCH_ANY_FILTER_TH) {
                if (data == Qundef || hook->data == data) {
                    hook->hook_flags |= RUBY_EVENT_HOOK_FLAG_DELETED;
                    ret+=1;
                    list->need_clean = true;
                }
            }
        }
        hook = hook->next;
    }

    clean_hooks_check(ec, list);
    return ret;
}

static int
rb_threadptr_remove_event_hook(const rb_execution_context_t *ec, const rb_thread_t *filter_th, rb_event_hook_func_t func, VALUE data)
{
    return remove_event_hook(ec, filter_th, func, data);
}

int
rb_thread_remove_event_hook(VALUE thval, rb_event_hook_func_t func)
{
    return rb_threadptr_remove_event_hook(GET_EC(), rb_thread_ptr(thval), func, Qundef);
}

int
rb_thread_remove_event_hook_with_data(VALUE thval, rb_event_hook_func_t func, VALUE data)
{
    return rb_threadptr_remove_event_hook(GET_EC(), rb_thread_ptr(thval), func, data);
}

int
rb_remove_event_hook(rb_event_hook_func_t func)
{
    return remove_event_hook(GET_EC(), NULL, func, Qundef);
}

int
rb_remove_event_hook_with_data(rb_event_hook_func_t func, VALUE data)
{
    return remove_event_hook(GET_EC(), NULL, func, data);
}

void
rb_ec_clear_current_thread_trace_func(const rb_execution_context_t *ec)
{
    rb_threadptr_remove_event_hook(ec, rb_ec_thread_ptr(ec), 0, Qundef);
}

void
rb_ec_clear_all_trace_func(const rb_execution_context_t *ec)
{
    rb_threadptr_remove_event_hook(ec, MATCH_ANY_FILTER_TH, 0, Qundef);
}

/* invoke hooks */

static void
exec_hooks_body(const rb_execution_context_t *ec, rb_hook_list_t *list, const rb_trace_arg_t *trace_arg)
{
    rb_event_hook_t *hook;

    for (hook = list->hooks; hook; hook = hook->next) {
        if (!(hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) &&
            (trace_arg->event & hook->events) &&
            (LIKELY(hook->filter.th == 0) || hook->filter.th == rb_ec_thread_ptr(ec)) &&
            (LIKELY(hook->filter.target_line == 0) || (hook->filter.target_line == (unsigned int)rb_vm_get_sourceline(ec->cfp)))) {
            if (!(hook->hook_flags & RUBY_EVENT_HOOK_FLAG_RAW_ARG)) {
                (*hook->func)(trace_arg->event, hook->data, trace_arg->self, trace_arg->id, trace_arg->klass);
            }
            else {
                (*((rb_event_hook_raw_arg_func_t)hook->func))(hook->data, trace_arg);
            }
        }
    }
}

static int
exec_hooks_precheck(const rb_execution_context_t *ec, rb_hook_list_t *list, const rb_trace_arg_t *trace_arg)
{
    if (list->events & trace_arg->event) {
        list->running++;
        return TRUE;
    }
    else {
        return FALSE;
    }
}

static void
exec_hooks_postcheck(const rb_execution_context_t *ec, rb_hook_list_t *list)
{
    list->running--;
    clean_hooks_check(ec, list);
}

static void
exec_hooks_unprotected(const rb_execution_context_t *ec, rb_hook_list_t *list, const rb_trace_arg_t *trace_arg)
{
    if (exec_hooks_precheck(ec, list, trace_arg) == 0) return;
    exec_hooks_body(ec, list, trace_arg);
    exec_hooks_postcheck(ec, list);
}

static int
exec_hooks_protected(rb_execution_context_t *ec, rb_hook_list_t *list, const rb_trace_arg_t *trace_arg)
{
    enum ruby_tag_type state;
    volatile int raised;

    if (exec_hooks_precheck(ec, list, trace_arg) == 0) return 0;

    raised = rb_ec_reset_raised(ec);

    /* TODO: Support !RUBY_EVENT_HOOK_FLAG_SAFE hooks */

    EC_PUSH_TAG(ec);
    if ((state = EC_EXEC_TAG()) == TAG_NONE) {
        exec_hooks_body(ec, list, trace_arg);
    }
    EC_POP_TAG();

    exec_hooks_postcheck(ec, list);

    if (raised) {
        rb_ec_set_raised(ec);
    }

    return state;
}

// pop_p: Whether to pop the frame for the TracePoint when it throws.
MJIT_FUNC_EXPORTED void
rb_exec_event_hooks(rb_trace_arg_t *trace_arg, rb_hook_list_t *hooks, int pop_p)
{
    rb_execution_context_t *ec = trace_arg->ec;

    if (UNLIKELY(trace_arg->event & RUBY_INTERNAL_EVENT_MASK)) {
        if (ec->trace_arg && (ec->trace_arg->event & RUBY_INTERNAL_EVENT_MASK)) {
            /* skip hooks because this thread doing INTERNAL_EVENT */
        }
        else {
            rb_trace_arg_t *prev_trace_arg = ec->trace_arg;

            ec->trace_arg = trace_arg;
            /* only global hooks */
            exec_hooks_unprotected(ec, rb_ec_ractor_hooks(ec), trace_arg);
            ec->trace_arg = prev_trace_arg;
        }
    }
    else {
        if (ec->trace_arg == NULL && /* check reentrant */
            trace_arg->self != rb_mRubyVMFrozenCore /* skip special methods. TODO: remove it. */) {
            const VALUE errinfo = ec->errinfo;
            const VALUE old_recursive = ec->local_storage_recursive_hash;
            int state = 0;

            /* setup */
            ec->local_storage_recursive_hash = ec->local_storage_recursive_hash_for_trace;
            ec->errinfo = Qnil;
            ec->trace_arg = trace_arg;

            /* kick hooks */
            if ((state = exec_hooks_protected(ec, hooks, trace_arg)) == TAG_NONE) {
                ec->errinfo = errinfo;
            }

            /* cleanup */
            ec->trace_arg = NULL;
            ec->local_storage_recursive_hash_for_trace = ec->local_storage_recursive_hash;
            ec->local_storage_recursive_hash = old_recursive;

            if (state) {
                if (pop_p) {
                    if (VM_FRAME_FINISHED_P(ec->cfp)) {
                        ec->tag = ec->tag->prev;
                    }
                    rb_vm_pop_frame(ec);
                }
                EC_JUMP_TAG(ec, state);
            }
        }
    }
}

VALUE
rb_suppress_tracing(VALUE (*func)(VALUE), VALUE arg)
{
    volatile int raised;
    volatile VALUE result = Qnil;
    rb_execution_context_t *const ec = GET_EC();
    rb_vm_t *const vm = rb_ec_vm_ptr(ec);
    enum ruby_tag_type state;
    rb_trace_arg_t dummy_trace_arg;
    dummy_trace_arg.event = 0;

    if (!ec->trace_arg) {
        ec->trace_arg = &dummy_trace_arg;
    }

    raised = rb_ec_reset_raised(ec);

    EC_PUSH_TAG(ec);
    if (LIKELY((state = EC_EXEC_TAG()) == TAG_NONE)) {
        result = (*func)(arg);
    }
    else {
        (void)*&vm; /* suppress "clobbered" warning */
    }
    EC_POP_TAG();

    if (raised) {
        rb_ec_reset_raised(ec);
    }

    if (ec->trace_arg == &dummy_trace_arg) {
        ec->trace_arg = NULL;
    }

    if (state) {
#if defined RUBY_USE_SETJMPEX && RUBY_USE_SETJMPEX
        RB_GC_GUARD(result);
#endif
        EC_JUMP_TAG(ec, state);
    }

    return result;
}

static void call_trace_func(rb_event_flag_t, VALUE data, VALUE self, ID id, VALUE klass);

/* (2-1) set_trace_func (old API) */

/*
 *  call-seq:
 *     set_trace_func(proc)    -> proc
 *     set_trace_func(nil)     -> nil
 *
 *  Establishes _proc_ as the handler for tracing, or disables
 *  tracing if the parameter is +nil+.
 *
 *  *Note:* this method is obsolete, please use TracePoint instead.
 *
 *  _proc_ takes up to six parameters:
 *
 *  *	an event name
 *  *	a filename
 *  *	a line number
 *  *	an object id
 *  *	a binding
 *  *	the name of a class
 *
 *  _proc_ is invoked whenever an event occurs.
 *
 *  Events are:
 *
 *  +c-call+:: call a C-language routine
 *  +c-return+:: return from a C-language routine
 *  +call+:: call a Ruby method
 *  +class+:: start a class or module definition
 *  +end+:: finish a class or module definition
 *  +line+:: execute code on a new line
 *  +raise+:: raise an exception
 *  +return+:: return from a Ruby method
 *
 *  Tracing is disabled within the context of _proc_.
 *
 *      class Test
 *	def test
 *	  a = 1
 *	  b = 2
 *	end
 *      end
 *
 *      set_trace_func proc { |event, file, line, id, binding, classname|
 *	   printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
 *      }
 *      t = Test.new
 *      t.test
 *
 *	  line prog.rb:11               false
 *      c-call prog.rb:11        new    Class
 *      c-call prog.rb:11 initialize   Object
 *    c-return prog.rb:11 initialize   Object
 *    c-return prog.rb:11        new    Class
 *	  line prog.rb:12               false
 *  	  call prog.rb:2        test     Test
 *	  line prog.rb:3        test     Test
 *	  line prog.rb:4        test     Test
 *      return prog.rb:4        test     Test
 *
 * Note that for +c-call+ and +c-return+ events, the binding returned is the
 * binding of the nearest Ruby method calling the C method, since C methods
 * themselves do not have bindings.
 */

static VALUE
set_trace_func(VALUE obj, VALUE trace)
{
    rb_remove_event_hook(call_trace_func);

    if (NIL_P(trace)) {
        return Qnil;
    }

    if (!rb_obj_is_proc(trace)) {
        rb_raise(rb_eTypeError, "trace_func needs to be Proc");
    }

    rb_add_event_hook(call_trace_func, RUBY_EVENT_ALL, trace);
    return trace;
}

static void
thread_add_trace_func(rb_execution_context_t *ec, rb_thread_t *filter_th, VALUE trace)
{
    if (!rb_obj_is_proc(trace)) {
        rb_raise(rb_eTypeError, "trace_func needs to be Proc");
    }

    rb_threadptr_add_event_hook(ec, filter_th, call_trace_func, RUBY_EVENT_ALL, trace, RUBY_EVENT_HOOK_FLAG_SAFE);
}

/*
 *  call-seq:
 *     thr.add_trace_func(proc)    -> proc
 *
 *  Adds _proc_ as a handler for tracing.
 *
 *  See Thread#set_trace_func and Kernel#set_trace_func.
 */

static VALUE
thread_add_trace_func_m(VALUE obj, VALUE trace)
{
    thread_add_trace_func(GET_EC(), rb_thread_ptr(obj), trace);
    return trace;
}

/*
 *  call-seq:
 *     thr.set_trace_func(proc)    -> proc
 *     thr.set_trace_func(nil)     -> nil
 *
 *  Establishes _proc_ on _thr_ as the handler for tracing, or
 *  disables tracing if the parameter is +nil+.
 *
 *  See Kernel#set_trace_func.
 */

static VALUE
thread_set_trace_func_m(VALUE target_thread, VALUE trace)
{
    rb_execution_context_t *ec = GET_EC();
    rb_thread_t *target_th = rb_thread_ptr(target_thread);

    rb_threadptr_remove_event_hook(ec, target_th, call_trace_func, Qundef);

    if (NIL_P(trace)) {
        return Qnil;
    }
    else {
        thread_add_trace_func(ec, target_th, trace);
        return trace;
    }
}

static const char *
get_event_name(rb_event_flag_t event)
{
    switch (event) {
      case RUBY_EVENT_LINE:     return "line";
      case RUBY_EVENT_CLASS:    return "class";
      case RUBY_EVENT_END:      return "end";
      case RUBY_EVENT_CALL:     return "call";
      case RUBY_EVENT_RETURN:	return "return";
      case RUBY_EVENT_C_CALL:	return "c-call";
      case RUBY_EVENT_C_RETURN:	return "c-return";
      case RUBY_EVENT_RAISE:	return "raise";
      default:
        return "unknown";
    }
}

static ID
get_event_id(rb_event_flag_t event)
{
    ID id;

    switch (event) {
#define C(name, NAME) case RUBY_EVENT_##NAME: CONST_ID(id, #name); return id;
        C(line, LINE);
        C(class, CLASS);
        C(end, END);
        C(call, CALL);
        C(return, RETURN);
        C(c_call, C_CALL);
        C(c_return, C_RETURN);
        C(raise, RAISE);
        C(b_call, B_CALL);
        C(b_return, B_RETURN);
        C(thread_begin, THREAD_BEGIN);
        C(thread_end, THREAD_END);
        C(fiber_switch, FIBER_SWITCH);
        C(script_compiled, SCRIPT_COMPILED);
#undef C
      default:
        return 0;
    }
}

static void
get_path_and_lineno(const rb_execution_context_t *ec, const rb_control_frame_t *cfp, rb_event_flag_t event, VALUE *pathp, int *linep)
{
    cfp = rb_vm_get_ruby_level_next_cfp(ec, cfp);

    if (cfp) {
        const rb_iseq_t *iseq = cfp->iseq;
        *pathp = rb_iseq_path(iseq);

        if (event & (RUBY_EVENT_CLASS |
                                RUBY_EVENT_CALL  |
                                RUBY_EVENT_B_CALL)) {
            *linep = FIX2INT(rb_iseq_first_lineno(iseq));
        }
        else {
            *linep = rb_vm_get_sourceline(cfp);
        }
    }
    else {
        *pathp = Qnil;
        *linep = 0;
    }
}

static void
call_trace_func(rb_event_flag_t event, VALUE proc, VALUE self, ID id, VALUE klass)
{
    int line;
    VALUE filename;
    VALUE eventname = rb_str_new2(get_event_name(event));
    VALUE argv[6];
    const rb_execution_context_t *ec = GET_EC();

    get_path_and_lineno(ec, ec->cfp, event, &filename, &line);

    if (!klass) {
        rb_ec_frame_method_id_and_class(ec, &id, 0, &klass);
    }

    if (klass) {
        if (RB_TYPE_P(klass, T_ICLASS)) {
            klass = RBASIC(klass)->klass;
        }
        else if (FL_TEST(klass, FL_SINGLETON)) {
            klass = rb_ivar_get(klass, id__attached__);
        }
    }

    argv[0] = eventname;
    argv[1] = filename;
    argv[2] = INT2FIX(line);
    argv[3] = id ? ID2SYM(id) : Qnil;
    argv[4] = Qnil;
    if (self && (filename != Qnil) &&
        event != RUBY_EVENT_C_CALL &&
        event != RUBY_EVENT_C_RETURN &&
        (VM_FRAME_RUBYFRAME_P(ec->cfp) && imemo_type_p((VALUE)ec->cfp->iseq, imemo_iseq))) {
        argv[4] = rb_binding_new();
    }
    argv[5] = klass ? klass : Qnil;

    rb_proc_call_with_block(proc, 6, argv, Qnil);
}

/* (2-2) TracePoint API */

static VALUE rb_cTracePoint;

typedef struct rb_tp_struct {
    rb_event_flag_t events;
    int tracing; /* bool */
    rb_thread_t *target_th;
    VALUE local_target_set; /* Hash: target ->
                             * Qtrue (if target is iseq) or
                             * Qfalse (if target is bmethod)
                             */
    void (*func)(VALUE tpval, void *data);
    void *data;
    VALUE proc;
    rb_ractor_t *ractor;
    VALUE self;
} rb_tp_t;

static void
tp_mark(void *ptr)
{
    rb_tp_t *tp = ptr;
    rb_gc_mark(tp->proc);
    rb_gc_mark(tp->local_target_set);
    if (tp->target_th) rb_gc_mark(tp->target_th->self);
}

static size_t
tp_memsize(const void *ptr)
{
    return sizeof(rb_tp_t);
}

static const rb_data_type_t tp_data_type = {
    "tracepoint",
    {tp_mark, RUBY_TYPED_DEFAULT_FREE, tp_memsize,},
    0, 0, RUBY_TYPED_FREE_IMMEDIATELY
};

static VALUE
tp_alloc(VALUE klass)
{
    rb_tp_t *tp;
    return TypedData_Make_Struct(klass, rb_tp_t, &tp_data_type, tp);
}

static rb_event_flag_t
symbol2event_flag(VALUE v)
{
    ID id;
    VALUE sym = rb_to_symbol_type(v);
    const rb_event_flag_t RUBY_EVENT_A_CALL =
        RUBY_EVENT_CALL | RUBY_EVENT_B_CALL | RUBY_EVENT_C_CALL;
    const rb_event_flag_t RUBY_EVENT_A_RETURN =
        RUBY_EVENT_RETURN | RUBY_EVENT_B_RETURN | RUBY_EVENT_C_RETURN;

#define C(name, NAME) CONST_ID(id, #name); if (sym == ID2SYM(id)) return RUBY_EVENT_##NAME
    C(line, LINE);
    C(class, CLASS);
    C(end, END);
    C(call, CALL);
    C(return, RETURN);
    C(c_call, C_CALL);
    C(c_return, C_RETURN);
    C(raise, RAISE);
    C(b_call, B_CALL);
    C(b_return, B_RETURN);
    C(thread_begin, THREAD_BEGIN);
    C(thread_end, THREAD_END);
    C(fiber_switch, FIBER_SWITCH);
    C(script_compiled, SCRIPT_COMPILED);

    /* joke */
    C(a_call, A_CALL);
    C(a_return, A_RETURN);
#undef C
    rb_raise(rb_eArgError, "unknown event: %"PRIsVALUE, rb_sym2str(sym));
}

static rb_tp_t *
tpptr(VALUE tpval)
{
    rb_tp_t *tp;
    TypedData_Get_Struct(tpval, rb_tp_t, &tp_data_type, tp);
    return tp;
}

static rb_trace_arg_t *
get_trace_arg(void)
{
    rb_trace_arg_t *trace_arg = GET_EC()->trace_arg;
    if (trace_arg == 0) {
        rb_raise(rb_eRuntimeError, "access from outside");
    }
    return trace_arg;
}

struct rb_trace_arg_struct *
rb_tracearg_from_tracepoint(VALUE tpval)
{
    return get_trace_arg();
}

rb_event_flag_t
rb_tracearg_event_flag(rb_trace_arg_t *trace_arg)
{
    return trace_arg->event;
}

VALUE
rb_tracearg_event(rb_trace_arg_t *trace_arg)
{
    return ID2SYM(get_event_id(trace_arg->event));
}

static void
fill_path_and_lineno(rb_trace_arg_t *trace_arg)
{
    if (trace_arg->path == Qundef) {
        get_path_and_lineno(trace_arg->ec, trace_arg->cfp, trace_arg->event, &trace_arg->path, &trace_arg->lineno);
    }
}

VALUE
rb_tracearg_lineno(rb_trace_arg_t *trace_arg)
{
    fill_path_and_lineno(trace_arg);
    return INT2FIX(trace_arg->lineno);
}
VALUE
rb_tracearg_path(rb_trace_arg_t *trace_arg)
{
    fill_path_and_lineno(trace_arg);
    return trace_arg->path;
}

static void
fill_id_and_klass(rb_trace_arg_t *trace_arg)
{
    if (!trace_arg->klass_solved) {
        if (!trace_arg->klass) {
            rb_vm_control_frame_id_and_class(trace_arg->cfp, &trace_arg->id, &trace_arg->called_id, &trace_arg->klass);
        }

        if (trace_arg->klass) {
            if (RB_TYPE_P(trace_arg->klass, T_ICLASS)) {
                trace_arg->klass = RBASIC(trace_arg->klass)->klass;
            }
        }
        else {
            trace_arg->klass = Qnil;
        }

        trace_arg->klass_solved = 1;
    }
}

VALUE
rb_tracearg_parameters(rb_trace_arg_t *trace_arg)
{
    switch (trace_arg->event) {
      case RUBY_EVENT_CALL:
      case RUBY_EVENT_RETURN:
      case RUBY_EVENT_B_CALL:
      case RUBY_EVENT_B_RETURN: {
        const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(trace_arg->ec, trace_arg->cfp);
        if (cfp) {
            int is_proc = 0;
            if (VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_BLOCK && !VM_FRAME_LAMBDA_P(cfp)) {
                is_proc = 1;
            }
            return rb_iseq_parameters(cfp->iseq, is_proc);
        }
        break;
      }
      case RUBY_EVENT_C_CALL:
      case RUBY_EVENT_C_RETURN: {
        fill_id_and_klass(trace_arg);
        if (trace_arg->klass && trace_arg->id) {
            const rb_method_entry_t *me;
            VALUE iclass = Qnil;
            me = rb_method_entry_without_refinements(trace_arg->klass, trace_arg->id, &iclass);
            return rb_unnamed_parameters(rb_method_entry_arity(me));
        }
        break;
      }
      case RUBY_EVENT_RAISE:
      case RUBY_EVENT_LINE:
      case RUBY_EVENT_CLASS:
      case RUBY_EVENT_END:
      case RUBY_EVENT_SCRIPT_COMPILED:
        rb_raise(rb_eRuntimeError, "not supported by this event");
        break;
    }
    return Qnil;
}

VALUE
rb_tracearg_method_id(rb_trace_arg_t *trace_arg)
{
    fill_id_and_klass(trace_arg);
    return trace_arg->id ? ID2SYM(trace_arg->id) : Qnil;
}

VALUE
rb_tracearg_callee_id(rb_trace_arg_t *trace_arg)
{
    fill_id_and_klass(trace_arg);
    return trace_arg->called_id ? ID2SYM(trace_arg->called_id) : Qnil;
}

VALUE
rb_tracearg_defined_class(rb_trace_arg_t *trace_arg)
{
    fill_id_and_klass(trace_arg);
    return trace_arg->klass;
}

VALUE
rb_tracearg_binding(rb_trace_arg_t *trace_arg)
{
    rb_control_frame_t *cfp;
    cfp = rb_vm_get_binding_creatable_next_cfp(trace_arg->ec, trace_arg->cfp);

    if (cfp && imemo_type_p((VALUE)cfp->iseq, imemo_iseq)) {
        return rb_vm_make_binding(trace_arg->ec, cfp);
    }
    else {
        return Qnil;
    }
}

VALUE
rb_tracearg_self(rb_trace_arg_t *trace_arg)
{
    return trace_arg->self;
}

VALUE
rb_tracearg_return_value(rb_trace_arg_t *trace_arg)
{
    if (trace_arg->event & (RUBY_EVENT_RETURN | RUBY_EVENT_C_RETURN | RUBY_EVENT_B_RETURN)) {
        /* ok */
    }
    else {
        rb_raise(rb_eRuntimeError, "not supported by this event");
    }
    if (trace_arg->data == Qundef) {
        rb_bug("rb_tracearg_return_value: unreachable");
    }
    return trace_arg->data;
}

VALUE
rb_tracearg_raised_exception(rb_trace_arg_t *trace_arg)
{
    if (trace_arg->event & (RUBY_EVENT_RAISE)) {
        /* ok */
    }
    else {
        rb_raise(rb_eRuntimeError, "not supported by this event");
    }
    if (trace_arg->data == Qundef) {
        rb_bug("rb_tracearg_raised_exception: unreachable");
    }
    return trace_arg->data;
}

VALUE
rb_tracearg_eval_script(rb_trace_arg_t *trace_arg)
{
    VALUE data = trace_arg->data;

    if (trace_arg->event & (RUBY_EVENT_SCRIPT_COMPILED)) {
        /* ok */
    }
    else {
        rb_raise(rb_eRuntimeError, "not supported by this event");
    }
    if (data == Qundef) {
        rb_bug("rb_tracearg_raised_exception: unreachable");
    }
    if (rb_obj_is_iseq(data)) {
        return Qnil;
    }
    else {
        VM_ASSERT(RB_TYPE_P(data, T_ARRAY));
        /* [src, iseq] */
        return RARRAY_AREF(data, 0);
    }
}

VALUE
rb_tracearg_instruction_sequence(rb_trace_arg_t *trace_arg)
{
    VALUE data = trace_arg->data;

    if (trace_arg->event & (RUBY_EVENT_SCRIPT_COMPILED)) {
        /* ok */
    }
    else {
        rb_raise(rb_eRuntimeError, "not supported by this event");
    }
    if (data == Qundef) {
        rb_bug("rb_tracearg_raised_exception: unreachable");
    }

    if (rb_obj_is_iseq(data)) {
        return rb_iseqw_new((const rb_iseq_t *)data);
    }
    else {
        VM_ASSERT(RB_TYPE_P(data, T_ARRAY));
        VM_ASSERT(rb_obj_is_iseq(RARRAY_AREF(data, 1)));

        /* [src, iseq] */
        return rb_iseqw_new((const rb_iseq_t *)RARRAY_AREF(data, 1));
    }
}

VALUE
rb_tracearg_object(rb_trace_arg_t *trace_arg)
{
    if (trace_arg->event & (RUBY_INTERNAL_EVENT_NEWOBJ | RUBY_INTERNAL_EVENT_FREEOBJ)) {
        /* ok */
    }
    else {
        rb_raise(rb_eRuntimeError, "not supported by this event");
    }
    if (trace_arg->data == Qundef) {
        rb_bug("rb_tracearg_object: unreachable");
    }
    return trace_arg->data;
}

static VALUE
tracepoint_attr_event(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_event(get_trace_arg());
}

static VALUE
tracepoint_attr_lineno(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_lineno(get_trace_arg());
}
static VALUE
tracepoint_attr_path(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_path(get_trace_arg());
}

static VALUE
tracepoint_attr_parameters(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_parameters(get_trace_arg());
}

static VALUE
tracepoint_attr_method_id(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_method_id(get_trace_arg());
}

static VALUE
tracepoint_attr_callee_id(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_callee_id(get_trace_arg());
}

static VALUE
tracepoint_attr_defined_class(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_defined_class(get_trace_arg());
}

static VALUE
tracepoint_attr_binding(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_binding(get_trace_arg());
}

static VALUE
tracepoint_attr_self(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_self(get_trace_arg());
}

static VALUE
tracepoint_attr_return_value(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_return_value(get_trace_arg());
}

static VALUE
tracepoint_attr_raised_exception(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_raised_exception(get_trace_arg());
}

static VALUE
tracepoint_attr_eval_script(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_eval_script(get_trace_arg());
}

static VALUE
tracepoint_attr_instruction_sequence(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracearg_instruction_sequence(get_trace_arg());
}

static void
tp_call_trace(VALUE tpval, rb_trace_arg_t *trace_arg)
{
    rb_tp_t *tp = tpptr(tpval);

    if (tp->func) {
        (*tp->func)(tpval, tp->data);
    }
    else {
        if (tp->ractor == NULL || tp->ractor == GET_RACTOR()) {
            rb_proc_call_with_block((VALUE)tp->proc, 1, &tpval, Qnil);
        }
    }
}

VALUE
rb_tracepoint_enable(VALUE tpval)
{
    rb_tp_t *tp;
    tp = tpptr(tpval);

    if (tp->local_target_set != Qfalse) {
        rb_raise(rb_eArgError, "can't nest-enable a targeting TracePoint");
    }

    if (tp->target_th) {
        rb_thread_add_event_hook2(tp->target_th->self, (rb_event_hook_func_t)tp_call_trace, tp->events, tpval,
                                  RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
    }
    else {
        rb_add_event_hook2((rb_event_hook_func_t)tp_call_trace, tp->events, tpval,
                           RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
    }
    tp->tracing = 1;
    return Qundef;
}

static const rb_iseq_t *
iseq_of(VALUE target)
{
    VALUE iseqv = rb_funcall(rb_cISeq, rb_intern("of"), 1, target);
    if (NIL_P(iseqv)) {
        rb_raise(rb_eArgError, "specified target is not supported");
    }
    else {
        return rb_iseqw_to_iseq(iseqv);
    }
}

const rb_method_definition_t *rb_method_def(VALUE method); /* proc.c */

static VALUE
rb_tracepoint_enable_for_target(VALUE tpval, VALUE target, VALUE target_line)
{
    rb_tp_t *tp = tpptr(tpval);
    const rb_iseq_t *iseq = iseq_of(target);
    int n = 0;
    unsigned int line = 0;
    bool target_bmethod = false;

    if (tp->tracing > 0) {
        rb_raise(rb_eArgError, "can't nest-enable a targeting TracePoint");
    }

    if (!NIL_P(target_line)) {
        if ((tp->events & RUBY_EVENT_LINE) == 0) {
            rb_raise(rb_eArgError, "target_line is specified, but line event is not specified");
        }
        else {
            line = NUM2UINT(target_line);
        }
    }

    VM_ASSERT(tp->local_target_set == Qfalse);
    tp->local_target_set = rb_obj_hide(rb_ident_hash_new());

    /* bmethod */
    if (rb_obj_is_method(target)) {
        rb_method_definition_t *def = (rb_method_definition_t *)rb_method_def(target);
        if (def->type == VM_METHOD_TYPE_BMETHOD &&
            (tp->events & (RUBY_EVENT_CALL | RUBY_EVENT_RETURN))) {
            if (def->body.bmethod.hooks == NULL) {
                def->body.bmethod.hooks = ZALLOC(rb_hook_list_t);
            }
            rb_hook_list_connect_tracepoint(target, def->body.bmethod.hooks, tpval, 0);
            rb_hash_aset(tp->local_target_set, target, Qfalse);
            target_bmethod = true;

            n++;
        }
    }

    /* iseq */
    n += rb_iseq_add_local_tracepoint_recursively(iseq, tp->events, tpval, line, target_bmethod);
    rb_hash_aset(tp->local_target_set, (VALUE)iseq, Qtrue);


    if (n == 0) {
        rb_raise(rb_eArgError, "can not enable any hooks");
    }

    rb_yjit_tracing_invalidate_all();

    ruby_vm_event_local_num++;

    tp->tracing = 1;

    return Qnil;
}

static int
disable_local_event_iseq_i(VALUE target, VALUE iseq_p, VALUE tpval)
{
    if (iseq_p) {
        rb_iseq_remove_local_tracepoint_recursively((rb_iseq_t *)target, tpval);
    }
    else {
        /* bmethod */
        rb_method_definition_t *def = (rb_method_definition_t *)rb_method_def(target);
        rb_hook_list_t *hooks = def->body.bmethod.hooks;
        VM_ASSERT(hooks != NULL);
        rb_hook_list_remove_tracepoint(hooks, tpval);

        if (hooks->events == 0) {
            rb_hook_list_free(def->body.bmethod.hooks);
            def->body.bmethod.hooks = NULL;
        }
    }
    return ST_CONTINUE;
}

VALUE
rb_tracepoint_disable(VALUE tpval)
{
    rb_tp_t *tp;

    tp = tpptr(tpval);

    if (tp->local_target_set) {
        rb_hash_foreach(tp->local_target_set, disable_local_event_iseq_i, tpval);
        tp->local_target_set = Qfalse;
        ruby_vm_event_local_num--;
    }
    else {
        if (tp->target_th) {
            rb_thread_remove_event_hook_with_data(tp->target_th->self, (rb_event_hook_func_t)tp_call_trace, tpval);
        }
        else {
            rb_remove_event_hook_with_data((rb_event_hook_func_t)tp_call_trace, tpval);
        }
    }
    tp->tracing = 0;
    tp->target_th = NULL;
    return Qundef;
}

void
rb_hook_list_connect_tracepoint(VALUE target, rb_hook_list_t *list, VALUE tpval, unsigned int target_line)
{
    rb_tp_t *tp = tpptr(tpval);
    rb_event_hook_t *hook = alloc_event_hook((rb_event_hook_func_t)tp_call_trace, tp->events, tpval,
                                             RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
    hook->filter.target_line = target_line;
    hook_list_connect(target, list, hook, FALSE);
}

void
rb_hook_list_remove_tracepoint(rb_hook_list_t *list, VALUE tpval)
{
    rb_event_hook_t *hook = list->hooks;
    rb_event_flag_t events = 0;

    while (hook) {
        if (hook->data == tpval) {
            hook->hook_flags |= RUBY_EVENT_HOOK_FLAG_DELETED;
            list->need_clean = true;
        }
        else if ((hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) == 0) {
            events |= hook->events;
        }
        hook = hook->next;
    }

    list->events = events;
}

static VALUE
tracepoint_enable_m(rb_execution_context_t *ec, VALUE tpval, VALUE target, VALUE target_line, VALUE target_thread)
{
    rb_tp_t *tp = tpptr(tpval);
    int previous_tracing = tp->tracing;

    if (target_thread == sym_default) {
        if (rb_block_given_p() && NIL_P(target) && NIL_P(target_line)) {
            target_thread = rb_thread_current();
        }
        else {
            target_thread = Qnil;
        }
    }

    /* check target_thread */
    if (RTEST(target_thread)) {
        if (tp->target_th) {
            rb_raise(rb_eArgError, "can not override target_thread filter");
        }
        tp->target_th = rb_thread_ptr(target_thread);
    }
    else {
        tp->target_th = NULL;
    }

    if (NIL_P(target)) {
        if (!NIL_P(target_line)) {
            rb_raise(rb_eArgError, "only target_line is specified");
        }
        rb_tracepoint_enable(tpval);
    }
    else {
        rb_tracepoint_enable_for_target(tpval, target, target_line);
    }

    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, Qundef,
                         previous_tracing ? rb_tracepoint_enable : rb_tracepoint_disable,
                         tpval);
    }
    else {
        return RBOOL(previous_tracing);
    }
}

static VALUE
tracepoint_disable_m(rb_execution_context_t *ec, VALUE tpval)
{
    rb_tp_t *tp = tpptr(tpval);
    int previous_tracing = tp->tracing;

    if (rb_block_given_p()) {
        if (tp->local_target_set != Qfalse) {
            rb_raise(rb_eArgError, "can't disable a targeting TracePoint in a block");
        }

        rb_tracepoint_disable(tpval);
        return rb_ensure(rb_yield, Qundef,
                         previous_tracing ? rb_tracepoint_enable : rb_tracepoint_disable,
                         tpval);
    }
    else {
        rb_tracepoint_disable(tpval);
        return RBOOL(previous_tracing);
    }
}

VALUE
rb_tracepoint_enabled_p(VALUE tpval)
{
    rb_tp_t *tp = tpptr(tpval);
    return RBOOL(tp->tracing);
}

static VALUE
tracepoint_enabled_p(rb_execution_context_t *ec, VALUE tpval)
{
    return rb_tracepoint_enabled_p(tpval);
}

static VALUE
tracepoint_new(VALUE klass, rb_thread_t *target_th, rb_event_flag_t events, void (func)(VALUE, void*), void *data, VALUE proc)
{
    VALUE tpval = tp_alloc(klass);
    rb_tp_t *tp;
    TypedData_Get_Struct(tpval, rb_tp_t, &tp_data_type, tp);

    tp->proc = proc;
    tp->ractor = rb_ractor_shareable_p(proc) ? NULL : GET_RACTOR();
    tp->func = func;
    tp->data = data;
    tp->events = events;
    tp->self = tpval;

    return tpval;
}

VALUE
rb_tracepoint_new(VALUE target_thval, rb_event_flag_t events, void (*func)(VALUE, void *), void *data)
{
    rb_thread_t *target_th = NULL;

    if (RTEST(target_thval)) {
        target_th = rb_thread_ptr(target_thval);
        /* TODO: Test it!
         * Warning: This function is not tested.
         */
    }
    return tracepoint_new(rb_cTracePoint, target_th, events, func, data, Qundef);
}

static VALUE
tracepoint_new_s(rb_execution_context_t *ec, VALUE self, VALUE args)
{
    rb_event_flag_t events = 0;
    long i;
    long argc = RARRAY_LEN(args);

    if (argc > 0) {
        for (i=0; i<argc; i++) {
            events |= symbol2event_flag(RARRAY_AREF(args, i));
        }
    }
    else {
        events = RUBY_EVENT_TRACEPOINT_ALL;
    }

    if (!rb_block_given_p()) {
        rb_raise(rb_eArgError, "must be called with a block");
    }

    return tracepoint_new(self, 0, events, 0, 0, rb_block_proc());
}

static VALUE
tracepoint_trace_s(rb_execution_context_t *ec, VALUE self, VALUE args)
{
    VALUE trace = tracepoint_new_s(ec, self, args);
    rb_tracepoint_enable(trace);
    return trace;
}

static VALUE
tracepoint_inspect(rb_execution_context_t *ec, VALUE self)
{
    rb_tp_t *tp = tpptr(self);
    rb_trace_arg_t *trace_arg = GET_EC()->trace_arg;

    if (trace_arg) {
        switch (trace_arg->event) {
          case RUBY_EVENT_LINE:
            {
                VALUE sym = rb_tracearg_method_id(trace_arg);
                if (NIL_P(sym))
                    break;
                return rb_sprintf("#<TracePoint:%"PRIsVALUE" %"PRIsVALUE":%d in `%"PRIsVALUE"'>",
                                  rb_tracearg_event(trace_arg),
                                  rb_tracearg_path(trace_arg),
                                  FIX2INT(rb_tracearg_lineno(trace_arg)),
                                  sym);
            }
          case RUBY_EVENT_CALL:
          case RUBY_EVENT_C_CALL:
          case RUBY_EVENT_RETURN:
          case RUBY_EVENT_C_RETURN:
            return rb_sprintf("#<TracePoint:%"PRIsVALUE" `%"PRIsVALUE"' %"PRIsVALUE":%d>",
                              rb_tracearg_event(trace_arg),
                              rb_tracearg_method_id(trace_arg),
                              rb_tracearg_path(trace_arg),
                              FIX2INT(rb_tracearg_lineno(trace_arg)));
          case RUBY_EVENT_THREAD_BEGIN:
          case RUBY_EVENT_THREAD_END:
            return rb_sprintf("#<TracePoint:%"PRIsVALUE" %"PRIsVALUE">",
                              rb_tracearg_event(trace_arg),
                              rb_tracearg_self(trace_arg));
          default:
            break;
        }
        return rb_sprintf("#<TracePoint:%"PRIsVALUE" %"PRIsVALUE":%d>",
                          rb_tracearg_event(trace_arg),
                          rb_tracearg_path(trace_arg),
                          FIX2INT(rb_tracearg_lineno(trace_arg)));
    }
    else {
        return rb_sprintf("#<TracePoint:%s>", tp->tracing ? "enabled" : "disabled");
    }
}

static void
tracepoint_stat_event_hooks(VALUE hash, VALUE key, rb_event_hook_t *hook)
{
    int active = 0, deleted = 0;

    while (hook) {
        if (hook->hook_flags & RUBY_EVENT_HOOK_FLAG_DELETED) {
            deleted++;
        }
        else {
            active++;
        }
        hook = hook->next;
    }

    rb_hash_aset(hash, key, rb_ary_new3(2, INT2FIX(active), INT2FIX(deleted)));
}

static VALUE
tracepoint_stat_s(rb_execution_context_t *ec, VALUE self)
{
    rb_vm_t *vm = GET_VM();
    VALUE stat = rb_hash_new();

    tracepoint_stat_event_hooks(stat, vm->self, rb_ec_ractor_hooks(ec)->hooks);
    /* TODO: thread local hooks */

    return stat;
}

static VALUE
disallow_reentry(VALUE val)
{
    rb_trace_arg_t *arg = (rb_trace_arg_t *)val;
    rb_execution_context_t *ec = GET_EC();
    if (ec->trace_arg != NULL) rb_bug("should be NULL, but %p", (void *)ec->trace_arg);
    ec->trace_arg = arg;
    return Qnil;
}

static VALUE
tracepoint_allow_reentry(rb_execution_context_t *ec, VALUE self)
{
    const rb_trace_arg_t *arg = ec->trace_arg;
    if (arg == NULL) rb_raise(rb_eRuntimeError, "No need to allow reentrance.");
    ec->trace_arg = NULL;
    return rb_ensure(rb_yield, Qnil, disallow_reentry, (VALUE)arg);
}

#include "trace_point.rbinc"

/* This function is called from inits.c */
void
Init_vm_trace(void)
{
    sym_default = ID2SYM(rb_intern_const("default"));

    /* trace_func */
    rb_define_global_function("set_trace_func", set_trace_func, 1);
    rb_define_method(rb_cThread, "set_trace_func", thread_set_trace_func_m, 1);
    rb_define_method(rb_cThread, "add_trace_func", thread_add_trace_func_m, 1);

    rb_cTracePoint = rb_define_class("TracePoint", rb_cObject);
    rb_undef_alloc_func(rb_cTracePoint);
}

typedef struct rb_postponed_job_struct {
    rb_postponed_job_func_t func;
    void *data;
} rb_postponed_job_t;

#define MAX_POSTPONED_JOB                  1000
#define MAX_POSTPONED_JOB_SPECIAL_ADDITION   24

struct rb_workqueue_job {
    struct ccan_list_node jnode; /* <=> vm->workqueue */
    rb_postponed_job_t job;
};

// Used for VM memsize reporting. Returns the size of a list of rb_workqueue_job
// structs. Defined here because the struct definition lives here as well.
size_t
rb_vm_memsize_workqueue(struct ccan_list_head *workqueue)
{
    struct rb_workqueue_job *work = 0;
    size_t size = 0;

    ccan_list_for_each(workqueue, work, jnode) {
        size += sizeof(struct rb_workqueue_job);
    }

    return size;
}

// Used for VM memsize reporting. Returns the total size of the postponed job
// buffer that was allocated at initialization.
size_t
rb_vm_memsize_postponed_job_buffer(void)
{
    return sizeof(rb_postponed_job_t) * MAX_POSTPONED_JOB;
}

void
Init_vm_postponed_job(void)
{
    rb_vm_t *vm = GET_VM();
    vm->postponed_job_buffer = ALLOC_N(rb_postponed_job_t, MAX_POSTPONED_JOB);
    vm->postponed_job_index = 0;
    /* workqueue is initialized when VM locks are initialized */
}

enum postponed_job_register_result {
    PJRR_SUCCESS     = 0,
    PJRR_FULL        = 1,
    PJRR_INTERRUPTED = 2
};

/* Async-signal-safe */
static enum postponed_job_register_result
postponed_job_register(rb_execution_context_t *ec, rb_vm_t *vm,
                       unsigned int flags, rb_postponed_job_func_t func, void *data, rb_atomic_t max, rb_atomic_t expected_index)
{
    rb_postponed_job_t *pjob;

    if (expected_index >= max) return PJRR_FULL; /* failed */

    if (ATOMIC_CAS(vm->postponed_job_index, expected_index, expected_index+1) == expected_index) {
        pjob = &vm->postponed_job_buffer[expected_index];
    }
    else {
        return PJRR_INTERRUPTED;
    }

    /* unused: pjob->flags = flags; */
    pjob->func = func;
    pjob->data = data;

    RUBY_VM_SET_POSTPONED_JOB_INTERRUPT(ec);

    return PJRR_SUCCESS;
}

static rb_execution_context_t *
get_valid_ec(rb_vm_t *vm)
{
    rb_execution_context_t *ec = rb_current_execution_context(false);
    if (ec == NULL) ec = rb_vm_main_ractor_ec(vm);
    return ec;
}

/*
 * return 0 if job buffer is full
 * Async-signal-safe
 */
int
rb_postponed_job_register(unsigned int flags, rb_postponed_job_func_t func, void *data)
{
    rb_vm_t *vm = GET_VM();
    rb_execution_context_t *ec = get_valid_ec(vm);

  begin:
    switch (postponed_job_register(ec, vm, flags, func, data, MAX_POSTPONED_JOB, vm->postponed_job_index)) {
      case PJRR_SUCCESS    : return 1;
      case PJRR_FULL       : return 0;
      case PJRR_INTERRUPTED: goto begin;
      default: rb_bug("unreachable\n");
    }
}

/*
 * return 0 if job buffer is full
 * Async-signal-safe
 */
int
rb_postponed_job_register_one(unsigned int flags, rb_postponed_job_func_t func, void *data)
{
    rb_vm_t *vm = GET_VM();
    rb_execution_context_t *ec = get_valid_ec(vm);
    rb_postponed_job_t *pjob;
    rb_atomic_t i, index;

  begin:
    index = vm->postponed_job_index;
    for (i=0; i<index; i++) {
        pjob = &vm->postponed_job_buffer[i];
        if (pjob->func == func) {
            RUBY_VM_SET_POSTPONED_JOB_INTERRUPT(ec);
            return 2;
        }
    }
    switch (postponed_job_register(ec, vm, flags, func, data, MAX_POSTPONED_JOB + MAX_POSTPONED_JOB_SPECIAL_ADDITION, index)) {
      case PJRR_SUCCESS    : return 1;
      case PJRR_FULL       : return 0;
      case PJRR_INTERRUPTED: goto begin;
      default: rb_bug("unreachable\n");
    }
}

/*
 * thread-safe and called from non-Ruby thread
 * returns FALSE on failure (ENOMEM), TRUE otherwise
 */
int
rb_workqueue_register(unsigned flags, rb_postponed_job_func_t func, void *data)
{
    struct rb_workqueue_job *wq_job = malloc(sizeof(*wq_job));
    rb_vm_t *vm = GET_VM();

    if (!wq_job) return FALSE;
    wq_job->job.func = func;
    wq_job->job.data = data;

    rb_nativethread_lock_lock(&vm->workqueue_lock);
    ccan_list_add_tail(&vm->workqueue, &wq_job->jnode);
    rb_nativethread_lock_unlock(&vm->workqueue_lock);

    // TODO: current implementation affects only main ractor
    RUBY_VM_SET_POSTPONED_JOB_INTERRUPT(rb_vm_main_ractor_ec(vm));

    return TRUE;
}

void
rb_postponed_job_flush(rb_vm_t *vm)
{
    rb_execution_context_t *ec = GET_EC();
    const rb_atomic_t block_mask = POSTPONED_JOB_INTERRUPT_MASK|TRAP_INTERRUPT_MASK;
    volatile rb_atomic_t saved_mask = ec->interrupt_mask & block_mask;
    VALUE volatile saved_errno = ec->errinfo;
    struct ccan_list_head tmp;

    ccan_list_head_init(&tmp);

    rb_nativethread_lock_lock(&vm->workqueue_lock);
    ccan_list_append_list(&tmp, &vm->workqueue);
    rb_nativethread_lock_unlock(&vm->workqueue_lock);

    ec->errinfo = Qnil;
    /* mask POSTPONED_JOB dispatch */
    ec->interrupt_mask |= block_mask;
    {
        EC_PUSH_TAG(ec);
        if (EC_EXEC_TAG() == TAG_NONE) {
            rb_atomic_t index;
            struct rb_workqueue_job *wq_job;

            while ((index = vm->postponed_job_index) > 0) {
                if (ATOMIC_CAS(vm->postponed_job_index, index, index-1) == index) {
                    rb_postponed_job_t *pjob = &vm->postponed_job_buffer[index-1];
                    (*pjob->func)(pjob->data);
                }
            }
            while ((wq_job = ccan_list_pop(&tmp, struct rb_workqueue_job, jnode))) {
                rb_postponed_job_t pjob = wq_job->job;

                free(wq_job);
                (pjob.func)(pjob.data);
            }
        }
        EC_POP_TAG();
    }
    /* restore POSTPONED_JOB mask */
    ec->interrupt_mask &= ~(saved_mask ^ block_mask);
    ec->errinfo = saved_errno;

    /* don't leak memory if a job threw an exception */
    if (!ccan_list_empty(&tmp)) {
        rb_nativethread_lock_lock(&vm->workqueue_lock);
        ccan_list_prepend_list(&vm->workqueue, &tmp);
        rb_nativethread_lock_unlock(&vm->workqueue_lock);

        RUBY_VM_SET_POSTPONED_JOB_INTERRUPT(GET_EC());
    }
}