Ruby: vm_dump.c Source File

Ruby 4.0.6p0 (2026-07-14 revision 03b6d3f8898a28604fe6cb00eae3226b821168f4)

vm_dump.c
1/**********************************************************************
2
3 vm_dump.c -
4
5 $Author$
6
7 Copyright (C) 2004-2007 Koichi Sasada
8
9**********************************************************************/
10
11#include "ruby/internal/config.h"
12#include "ruby/fiber/scheduler.h"
13
14#ifdef HAVE_UCONTEXT_H
15# include <ucontext.h>
16#endif
17
18#ifdef __APPLE__
19# ifdef HAVE_LIBPROC_H
20# include <libproc.h>
21# endif
22# include <mach/vm_map.h>
23# include <mach/mach_init.h>
24# ifdef __LP64__
25# define vm_region_recurse vm_region_recurse_64
26# endif
27/* that is defined in sys/queue.h, and conflicts with
28 * ccan/list/list.h */
29# undef LIST_HEAD
30#endif
31
32#include "addr2line.h"
33#include "internal.h"
34#include "internal/gc.h"
35#include "internal/variable.h"
36#include "internal/vm.h"
37#include "iseq.h"
38#include "vm_core.h"
39#include "ractor_core.h"
40
41#define MAX_POSBUF 128
42
43#define VM_CFP_CNT(ec, cfp) \
44 ((rb_control_frame_t *)((ec)->vm_stack + (ec)->vm_stack_size) - \
45 (rb_control_frame_t *)(cfp))
46
47const char *rb_method_type_name(rb_method_type_t type);
48int ruby_on_ci;
49
50#define kprintf(...) if (fprintf(errout, __VA_ARGS__) < 0) goto error
51#define kputs(s) if (fputs(s, errout) < 0) goto error
52
53static bool
54control_frame_dump(const rb_execution_context_t *ec, const rb_control_frame_t *cfp, FILE *errout)
55{
56 ptrdiff_t pc = -1;
57 ptrdiff_t ep = cfp->ep - ec->vm_stack;
58 char ep_in_heap = ' ';
59 char posbuf[MAX_POSBUF+1];
60 int line = 0;
61 const char *magic, *iseq_name = "-", *selfstr = "-", *biseq_name = "-";
62 VALUE tmp;
63 const rb_iseq_t *iseq = NULL;
64 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry_unchecked(cfp);
65 const rb_box_t *box = NULL;
66
67 if (ep < 0 || (size_t)ep > ec->vm_stack_size) {
68 ep = (ptrdiff_t)cfp->ep;
69 ep_in_heap = 'p';
70 }
71
72 switch (VM_FRAME_TYPE_UNCHECKED(cfp)) {
73 case VM_FRAME_MAGIC_TOP:
74 magic = "TOP";
75 box = VM_ENV_BOX_UNCHECKED(cfp->ep);
76 break;
77 case VM_FRAME_MAGIC_METHOD:
78 magic = "METHOD";
79 if (me) {
80 box = me->def->box;
81 }
82 break;
83 case VM_FRAME_MAGIC_CLASS:
84 magic = "CLASS";
85 box = VM_ENV_BOX_UNCHECKED(cfp->ep);
86 break;
87 case VM_FRAME_MAGIC_BLOCK:
88 magic = "BLOCK";
89 break;
90 case VM_FRAME_MAGIC_CFUNC:
91 magic = "CFUNC";
92 if (me) {
93 box = me->def->box;
94 }
95 break;
96 case VM_FRAME_MAGIC_IFUNC:
97 magic = "IFUNC";
98 break;
99 case VM_FRAME_MAGIC_EVAL:
100 magic = "EVAL";
101 break;
102 case VM_FRAME_MAGIC_RESCUE:
103 magic = "RESCUE";
104 break;
105 case VM_FRAME_MAGIC_DUMMY:
106 magic = "DUMMY";
107 break;
108 case 0:
109 magic = "------";
110 break;
111 default:
112 magic = "(none)";
113 break;
114 }
115
116 if (0) {
117 tmp = rb_inspect(cfp->self);
118 selfstr = StringValueCStr(tmp);
119 }
120 else {
121 selfstr = "";
122 }
123
124 if (cfp->iseq != 0) {
125#define RUBY_VM_IFUNC_P(ptr) IMEMO_TYPE_P(ptr, imemo_ifunc)
126 if (RUBY_VM_IFUNC_P(cfp->iseq)) {
127 iseq_name = "<ifunc>";
128 }
129 else if (SYMBOL_P((VALUE)cfp->iseq)) {
130 tmp = rb_sym2str((VALUE)cfp->iseq);
131 iseq_name = RSTRING_PTR(tmp);
132 snprintf(posbuf, MAX_POSBUF, ":%s", iseq_name);
133 line = -1;
134 }
135 else {
136 if (cfp->pc) {
137 iseq = cfp->iseq;
138 pc = cfp->pc - ISEQ_BODY(iseq)->iseq_encoded;
139 iseq_name = RSTRING_PTR(ISEQ_BODY(iseq)->location.label);
140 if (pc >= 0 && (size_t)pc <= ISEQ_BODY(iseq)->iseq_size) {
141 line = rb_vm_get_sourceline(cfp);
142 }
143 if (line) {
144 snprintf(posbuf, MAX_POSBUF, "%s:%d", RSTRING_PTR(rb_iseq_path(iseq)), line);
145 }
146 }
147 else {
148 iseq_name = "<dummy_frame>";
149 }
150 }
151 }
152 else if (me != NULL && IMEMO_TYPE_P(me, imemo_ment)) {
153 iseq_name = rb_id2name(me->def->original_id);
154 snprintf(posbuf, MAX_POSBUF, ":%s", iseq_name);
155 line = -1;
156 }
157
158 kprintf("c:%04"PRIdPTRDIFF" ",
159 ((rb_control_frame_t *)(ec->vm_stack + ec->vm_stack_size) - cfp));
160 if (pc == -1) {
161 kprintf("p:---- ");
162 }
163 else {
164 kprintf("p:%04"PRIdPTRDIFF" ", pc);
165 }
166 kprintf("s:%04"PRIdPTRDIFF" ", cfp->sp - ec->vm_stack);
167 kprintf(ep_in_heap == ' ' ? "e:%06"PRIdPTRDIFF" " : "E:%06"PRIxPTRDIFF" ", ep % 10000);
168 kprintf("l:%s ", VM_ENV_LOCAL_P(cfp->ep) ? "y" : "n");
169 if (box) {
170 kprintf("b:%04ld ", box->box_id % 10000);
171 }
172 else {
173 kprintf("b:---- ");
174 }
175 kprintf("%-6s", magic);
176 if (line) {
177 kprintf(" %s", posbuf);
178 }
179 if (VM_FRAME_FINISHED_P_UNCHECKED(cfp)) {
180 kprintf(" [FINISH]");
181 }
182 if (0) {
183 kprintf(" \t");
184 kprintf("iseq: %-24s ", iseq_name);
185 kprintf("self: %-24s ", selfstr);
186 kprintf("%-1s ", biseq_name);
187 }
188 kprintf("\n");
189
190 // additional information for CI machines
191 if (ruby_on_ci) {
192 char buff[0x100];
193
194 if (me) {
195 if (IMEMO_TYPE_P(me, imemo_ment)) {
196 kprintf(" me:\n");
197 kprintf(" called_id: %s, type: %s\n", rb_id2name(me->called_id), rb_method_type_name(me->def->type));
198 kprintf(" owner class: %s\n", rb_raw_obj_info(buff, 0x100, me->owner));
199 if (me->owner != me->defined_class) {
200 kprintf(" defined_class: %s\n", rb_raw_obj_info(buff, 0x100, me->defined_class));
201 }
202 }
203 else {
204 kprintf(" me is corrupted (%s)\n", rb_raw_obj_info(buff, 0x100, (VALUE)me));
205 }
206 }
207
208 kprintf(" self: %s\n", rb_raw_obj_info(buff, 0x100, cfp->self));
209
210 if (iseq) {
211 if (ISEQ_BODY(iseq)->local_table_size > 0) {
212 kprintf(" lvars:\n");
213 for (unsigned int i=0; i<ISEQ_BODY(iseq)->local_table_size; i++) {
214 const VALUE *argv = cfp->ep - ISEQ_BODY(cfp->iseq)->local_table_size - VM_ENV_DATA_SIZE + 1;
215 kprintf(" %s: %s\n",
216 rb_id2name(ISEQ_BODY(iseq)->local_table[i]),
217 rb_raw_obj_info(buff, 0x100, argv[i]));
218 }
219 }
220 }
221 }
222 return true;
223 error:
224 return false;
225}
226
227static inline const rb_control_frame_t *
228vmdebug_search_cf_from_ep(const rb_execution_context_t *ec, const rb_control_frame_t *cfp, const VALUE * const ep)
229{
230 if (!ep) {
231 return NULL;
232 }
233 else {
234 const rb_control_frame_t * const eocfp = RUBY_VM_END_CONTROL_FRAME(ec); /* end of control frame pointer */
235
236 while (cfp < eocfp) {
237 if (cfp->ep == ep) {
238 return cfp;
239 }
240 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
241 }
242
243 return NULL;
244 }
245}
246
247static rb_callable_method_entry_t *
248vmdebug_env_method_entry_unchecked(VALUE obj, int can_be_svar)
249{
250 if (obj == Qfalse) return NULL;
251
252 switch (imemo_type(obj)) {
253 case imemo_ment:
254 return (rb_callable_method_entry_t *)obj;
255 case imemo_cref:
256 return NULL;
257 case imemo_svar:
258 if (can_be_svar) {
259 return vmdebug_env_method_entry_unchecked(((struct vm_svar *)obj)->cref_or_me, FALSE);
260 }
261 default:
262 return NULL;
263 }
264}
265
266static const rb_callable_method_entry_t *
267vmdebug_frame_method_entry_unchecked(const VALUE *ep)
268{
269 rb_callable_method_entry_t *me;
270
271 while (!VM_ENV_LOCAL_P_UNCHECKED(ep)) {
272 if ((me = vmdebug_env_method_entry_unchecked(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) != NULL) return me;
273 ep = VM_ENV_PREV_EP_UNCHECKED(ep);
274 }
275
276 return vmdebug_env_method_entry_unchecked(ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE);
277}
278
279static bool
280box_env_dump(const rb_execution_context_t *ec, const VALUE *env, const rb_control_frame_t *checkpoint_cfp, FILE *errout)
281{
282 ptrdiff_t pc = -1;
283 ptrdiff_t ep = env - ec->vm_stack;
284 char ep_in_heap = ' ';
285 char posbuf[MAX_POSBUF+1];
286 int line = 0;
287 const char *magic, *iseq_name = "-";
288 VALUE tmp;
289 const rb_iseq_t *iseq = NULL;
290 const rb_box_t *box = NULL;
291 const rb_control_frame_t *cfp = vmdebug_search_cf_from_ep(ec, checkpoint_cfp, env);
292 const rb_callable_method_entry_t *me = vmdebug_frame_method_entry_unchecked(env);
293
294 if (ep < 0 || (size_t)ep > ec->vm_stack_size) {
295 if (cfp) {
296 ep = (ptrdiff_t)cfp->ep;
297 ep_in_heap = 'p';
298 }
299 }
300
301 switch (VM_ENV_FLAGS_UNCHECKED(env, VM_FRAME_MAGIC_MASK)) {
302 case VM_FRAME_MAGIC_TOP:
303 magic = "TOP";
304 box = VM_ENV_BOX_UNCHECKED(env);
305 break;
306 case VM_FRAME_MAGIC_METHOD:
307 magic = "METHOD";
308 if (me) {
309 box = me->def->box;
310 }
311 break;
312 case VM_FRAME_MAGIC_CLASS:
313 magic = "CLASS";
314 box = VM_ENV_BOX_UNCHECKED(env);
315 break;
316 case VM_FRAME_MAGIC_BLOCK:
317 magic = "BLOCK";
318 break;
319 case VM_FRAME_MAGIC_CFUNC:
320 magic = "CFUNC";
321 if (me) {
322 box = me->def->box;
323 }
324 break;
325 case VM_FRAME_MAGIC_IFUNC:
326 magic = "IFUNC";
327 break;
328 case VM_FRAME_MAGIC_EVAL:
329 magic = "EVAL";
330 break;
331 case VM_FRAME_MAGIC_RESCUE:
332 magic = "RESCUE";
333 break;
334 case VM_FRAME_MAGIC_DUMMY:
335 magic = "DUMMY";
336 break;
337 case 0:
338 magic = "------";
339 break;
340 default:
341 magic = "(none)";
342 break;
343 }
344
345 if (cfp && cfp->iseq != 0) {
346#define RUBY_VM_IFUNC_P(ptr) IMEMO_TYPE_P(ptr, imemo_ifunc)
347 if (RUBY_VM_IFUNC_P(cfp->iseq)) {
348 iseq_name = "<ifunc>";
349 }
350 else if (SYMBOL_P((VALUE)cfp->iseq)) {
351 tmp = rb_sym2str((VALUE)cfp->iseq);
352 iseq_name = RSTRING_PTR(tmp);
353 snprintf(posbuf, MAX_POSBUF, ":%s", iseq_name);
354 line = -1;
355 }
356 else {
357 if (cfp->pc) {
358 iseq = cfp->iseq;
359 pc = cfp->pc - ISEQ_BODY(iseq)->iseq_encoded;
360 iseq_name = RSTRING_PTR(ISEQ_BODY(iseq)->location.label);
361 if (pc >= 0 && (size_t)pc <= ISEQ_BODY(iseq)->iseq_size) {
362 line = rb_vm_get_sourceline(cfp);
363 }
364 if (line) {
365 snprintf(posbuf, MAX_POSBUF, "%s:%d", RSTRING_PTR(rb_iseq_path(iseq)), line);
366 }
367 }
368 else {
369 iseq_name = "<dummy_frame>";
370 }
371 }
372 }
373 else if (me != NULL && IMEMO_TYPE_P(me, imemo_ment)) {
374 iseq_name = rb_id2name(me->def->original_id);
375 snprintf(posbuf, MAX_POSBUF, ":%s", iseq_name);
376 line = -1;
377 }
378
379 if (cfp) {
380 kprintf("c:%04"PRIdPTRDIFF" ",
381 ((rb_control_frame_t *)(ec->vm_stack + ec->vm_stack_size) - cfp));
382 }
383 else {
384 kprintf("c:---- ");
385 }
386 kprintf(ep_in_heap == ' ' ? "e:%06"PRIdPTRDIFF" " : "E:%06"PRIxPTRDIFF" ", ep % 10000);
387 kprintf("l:%s ", VM_ENV_LOCAL_P(env) ? "y" : "n");
388 if (box) {
389 kprintf("b:%04ld ", box->box_id % 10000);
390 }
391 else {
392 kprintf("b:---- ");
393 }
394 kprintf("%-6s", magic);
395 if (line) {
396 kprintf(" %s", posbuf);
397 }
398 if (VM_ENV_FLAGS_UNCHECKED(env, VM_FRAME_FLAG_FINISH) != 0) {
399 kprintf(" [FINISH]");
400 }
401 kprintf("\n");
402 return true;
403 error:
404 return false;
405}
406
407static bool
408box_env_dump_unchecked(const rb_execution_context_t *ec, const VALUE *env, const rb_control_frame_t *checkpoint_cfp, FILE *errout)
409{
410 if (env == NULL) {
411 kprintf("c:---- e:000000 l:- b:---- (none)\n");
412 return true;
413 }
414 else {
415 return box_env_dump(ec, env, checkpoint_cfp, errout);
416 }
417 error:
418 return false;
419}
420
421bool
422rb_vmdebug_box_env_dump_raw(const rb_execution_context_t *ec, const rb_control_frame_t *current_cfp, FILE *errout)
423{
424 // See VM_EP_RUBY_LEP for the original logic
425 const VALUE *ep = current_cfp->ep;
426 const rb_control_frame_t * const eocfp = RUBY_VM_END_CONTROL_FRAME(ec); /* end of control frame pointer */
427 const rb_control_frame_t *cfp = current_cfp, *checkpoint_cfp = current_cfp;
428
429 kprintf("-- Ruby Box detection information "
430 "-----------------------------------------\n");
431
432 box_env_dump_unchecked(ec, ep, checkpoint_cfp, errout);
433
434 if (VM_ENV_FRAME_TYPE_P(ep, VM_FRAME_MAGIC_IFUNC)) {
435 while (!VM_ENV_LOCAL_P(ep)) {
436 ep = VM_ENV_PREV_EP(ep);
437 box_env_dump_unchecked(ec, ep, checkpoint_cfp, errout);
438 }
439 goto stop;
440 }
441
442 while (VM_ENV_FRAME_TYPE_P(ep, VM_FRAME_MAGIC_CFUNC)) {
443 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
444 if (!cfp) {
445 goto stop;
446 }
447 if (cfp >= eocfp) {
448 kprintf("[PREVIOUS CONTROL FRAME IS OUT OF BOUND]\n");
449 goto stop;
450 }
451 ep = cfp->ep;
452 box_env_dump_unchecked(ec, ep, checkpoint_cfp, errout);
453 if (!ep) {
454 goto stop;
455 }
456 }
457
458 while (!VM_ENV_LOCAL_P(ep)) {
459 ep = VM_ENV_PREV_EP(ep);
460 box_env_dump_unchecked(ec, ep, checkpoint_cfp, errout);
461 }
462
463 stop:
464 kprintf("\n");
465 return true;
466
467 error:
468 return false;
469}
470
471bool
472rb_vmdebug_stack_dump_raw(const rb_execution_context_t *ec, const rb_control_frame_t *cfp, FILE *errout)
473{
474#if 0
475 VALUE *sp = cfp->sp;
476 const VALUE *ep = cfp->ep;
477 VALUE *p, *st, *t;
478
479 kprintf("-- stack frame ------------\n");
480 for (p = st = ec->vm_stack; p < sp; p++) {
481 kprintf("%04ld (%p): %08"PRIxVALUE, (long)(p - st), p, *p);
482
483 t = (VALUE *)*p;
484 if (ec->vm_stack <= t && t < sp) {
485 kprintf(" (= %ld)", (long)((VALUE *)GC_GUARDED_PTR_REF((VALUE)t) - ec->vm_stack));
486 }
487
488 if (p == ep)
489 kprintf(" <- ep");
490
491 kprintf("\n");
492 }
493#endif
494
495 kprintf("-- Control frame information "
496 "-----------------------------------------------\n");
497 while ((void *)cfp < (void *)(ec->vm_stack + ec->vm_stack_size)) {
498 control_frame_dump(ec, cfp, errout);
499 cfp++;
500 }
501 kprintf("\n");
502 return true;
503
504 error:
505 return false;
506}
507
508bool
509rb_vmdebug_stack_dump_raw_current(void)
510{
511 const rb_execution_context_t *ec = GET_EC();
512 return rb_vmdebug_stack_dump_raw(ec, ec->cfp, stderr);
513}
514
515bool
516rb_vmdebug_env_dump_raw(const rb_env_t *env, const VALUE *ep, FILE *errout)
517{
518 unsigned int i;
519 kprintf("-- env --------------------\n");
520
521 while (env) {
522 kprintf("--\n");
523 for (i = 0; i < env->env_size; i++) {
524 kprintf("%04d: %08"PRIxVALUE" (%p)", i, env->env[i], (void *)&env->env[i]);
525 if (&env->env[i] == ep) kprintf(" <- ep");
526 kprintf("\n");
527 }
528
529 env = rb_vm_env_prev_env(env);
530 }
531 kprintf("---------------------------\n");
532 return true;
533
534 error:
535 return false;
536}
537
538bool
539rb_vmdebug_proc_dump_raw(rb_proc_t *proc, FILE *errout)
540{
541 const rb_env_t *env;
542 char *selfstr;
543 VALUE val = rb_inspect(vm_block_self(&proc->block));
544 selfstr = StringValueCStr(val);
545
546 kprintf("-- proc -------------------\n");
547 kprintf("self: %s\n", selfstr);
548 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&proc->block));
549 rb_vmdebug_env_dump_raw(env, vm_block_ep(&proc->block), errout);
550 return true;
551
552 error:
553 return false;
554}
555
556bool
557rb_vmdebug_stack_dump_th(VALUE thval, FILE *errout)
558{
559 rb_thread_t *target_th = rb_thread_ptr(thval);
560 return rb_vmdebug_stack_dump_raw(target_th->ec, target_th->ec->cfp, errout);
561}
562
563#if VMDEBUG > 2
564
565/* copy from vm_insnhelper.c */
566static const VALUE *
567vm_base_ptr(const rb_control_frame_t *cfp)
568{
569 const rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
570 const VALUE *bp = prev_cfp->sp + ISEQ_BODY(cfp->iseq)->local_table_size + VM_ENV_DATA_SIZE;
571
572 if (ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_METHOD || VM_FRAME_BMETHOD_P(cfp)) {
573 bp += 1;
574 }
575 return bp;
576}
577
578static void
579vm_stack_dump_each(const rb_execution_context_t *ec, const rb_control_frame_t *cfp, FILE *errout)
580{
581 int i, argc = 0, local_table_size = 0;
582 VALUE rstr;
583 VALUE *sp = cfp->sp;
584 const VALUE *ep = cfp->ep;
585
586 if (VM_FRAME_RUBYFRAME_P(cfp)) {
587 const rb_iseq_t *iseq = cfp->iseq;
588 argc = ISEQ_BODY(iseq)->param.lead_num;
589 local_table_size = ISEQ_BODY(iseq)->local_table_size;
590 }
591
592 /* stack trace header */
593
594 if (VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_METHOD||
595 VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_TOP ||
596 VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_BLOCK ||
597 VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_CLASS ||
598 VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_CFUNC ||
599 VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_IFUNC ||
600 VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_EVAL ||
601 VM_FRAME_TYPE(cfp) == VM_FRAME_MAGIC_RESCUE)
602 {
603 const VALUE *ptr = ep - local_table_size;
604
605 control_frame_dump(ec, cfp, errout);
606
607 for (i = 0; i < argc; i++) {
608 rstr = rb_inspect(*ptr);
609 kprintf(" arg %2d: %8s (%p)\n", i, StringValueCStr(rstr),
610 (void *)ptr++);
611 }
612 for (; i < local_table_size - 1; i++) {
613 rstr = rb_inspect(*ptr);
614 kprintf(" local %2d: %8s (%p)\n", i, StringValueCStr(rstr),
615 (void *)ptr++);
616 }
617
618 ptr = vm_base_ptr(cfp);
619 for (; ptr < sp; ptr++, i++) {
620 switch (TYPE(*ptr)) {
621 case T_UNDEF:
622 rstr = rb_str_new2("undef");
623 break;
624 case T_IMEMO:
625 rstr = rb_str_new2("imemo"); /* TODO: can put mode detail information */
626 break;
627 default:
628 rstr = rb_inspect(*ptr);
629 break;
630 }
631 kprintf(" stack %2d: %8s (%"PRIdPTRDIFF")\n", i, StringValueCStr(rstr),
632 (ptr - ec->vm_stack));
633 }
634 }
635 else if (VM_FRAME_FINISHED_P(cfp)) {
636 if (ec->vm_stack + ec->vm_stack_size > (VALUE *)(cfp + 1)) {
637 vm_stack_dump_each(ec, cfp + 1, errout);
638 }
639 else {
640 /* SDR(); */
641 }
642 }
643 else {
644 rb_bug("unsupported frame type: %08lx", VM_FRAME_TYPE(cfp));
645 }
646}
647#endif
648
649bool
650rb_vmdebug_debug_print_register(const rb_execution_context_t *ec, FILE *errout)
651{
652 rb_control_frame_t *cfp = ec->cfp;
653 ptrdiff_t pc = -1;
654 ptrdiff_t ep = cfp->ep - ec->vm_stack;
655 ptrdiff_t cfpi;
656
657 if (VM_FRAME_RUBYFRAME_P(cfp)) {
658 pc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded;
659 }
660
661 if (ep < 0 || (size_t)ep > ec->vm_stack_size) {
662 ep = -1;
663 }
664
665 cfpi = ((rb_control_frame_t *)(ec->vm_stack + ec->vm_stack_size)) - cfp;
666 kprintf(" [PC] %04"PRIdPTRDIFF", [SP] %04"PRIdPTRDIFF", [EP] %04"PRIdPTRDIFF", [CFP] %04"PRIdPTRDIFF"\n",
667 pc, (cfp->sp - ec->vm_stack), ep, cfpi);
668 return true;
669
670 error:
671 return false;
672}
673
674bool
675rb_vmdebug_thread_dump_regs(VALUE thval, FILE *errout)
676{
677 return rb_vmdebug_debug_print_register(rb_thread_ptr(thval)->ec, errout);
678}
679
680bool
681rb_vmdebug_debug_print_pre(const rb_execution_context_t *ec, const rb_control_frame_t *cfp, const VALUE *_pc, FILE *errout)
682{
683 const rb_iseq_t *iseq = cfp->iseq;
684
685 if (iseq != 0) {
686 ptrdiff_t pc = _pc - ISEQ_BODY(iseq)->iseq_encoded;
687 int i;
688
689 for (i=0; i<(int)VM_CFP_CNT(ec, cfp); i++) {
690 kprintf(" ");
691 }
692 kprintf("| ");
693 if(0) kprintf("[%03ld] ", (long)(cfp->sp - ec->vm_stack));
694
695 /* printf("%3"PRIdPTRDIFF" ", VM_CFP_CNT(ec, cfp)); */
696 if (pc >= 0) {
697 const VALUE *iseq_original = rb_iseq_original_iseq((rb_iseq_t *)iseq);
698
699 rb_iseq_disasm_insn(0, iseq_original, (size_t)pc, iseq, 0);
700 }
701 }
702
703#if VMDEBUG > 3
704 kprintf(" (1)");
705 rb_vmdebug_debug_print_register(errout, ec);
706#endif
707 return true;
708
709 error:
710 return false;
711}
712
713bool
714rb_vmdebug_debug_print_post(const rb_execution_context_t *ec, const rb_control_frame_t *cfp, FILE *errout)
715{
716#if VMDEBUG > 9
717 if (!rb_vmdebug_stack_dump_raw(ec, cfp, errout)) goto errout;
718#endif
719
720#if VMDEBUG > 3
721 kprintf(" (2)");
722 rb_vmdebug_debug_print_register(errout, ec);
723#endif
724 /* stack_dump_raw(ec, cfp); */
725
726#if VMDEBUG > 2
727 /* stack_dump_thobj(ec); */
728 vm_stack_dump_each(ec, ec->cfp, errout);
729
730 kprintf
731 ("--------------------------------------------------------------\n");
732#endif
733 return true;
734
735#if VMDEBUG > 2
736 error:
737 return false;
738#endif
739}
740
741 VALUE
742rb_vmdebug_thread_dump_state(FILE *errout, VALUE self)
743{
744 rb_thread_t *th = rb_thread_ptr(self);
745 rb_control_frame_t *cfp = th->ec->cfp;
746
747 kprintf("Thread state dump:\n");
748 kprintf("pc : %p, sp : %p\n", (void *)cfp->pc, (void *)cfp->sp);
749 kprintf("cfp: %p, ep : %p\n", (void *)cfp, (void *)cfp->ep);
750
751 error:
752 return Qnil;
753}
754
755#if defined __APPLE__
756# include <AvailabilityMacros.h>
757# if defined(MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
758# define MCTX_SS_REG(reg) __ss.__##reg
759# else
760# define MCTX_SS_REG(reg) ss.reg
761# endif
762#endif
763
764#if defined(HAVE_BACKTRACE)
765# define USE_BACKTRACE 1
766# ifdef HAVE_LIBUNWIND
767# undef backtrace
768# define backtrace unw_backtrace
769# elif defined(__APPLE__) && defined(HAVE_LIBUNWIND_H) \
770 && defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
771# define UNW_LOCAL_ONLY
772# include <libunwind.h>
773# include <sys/mman.h>
774# undef backtrace
775
776# if defined(__arm64__) || defined(__POWERPC__)
777static bool
778is_coroutine_start(unw_word_t ip)
779{
780#if defined(USE_MN_THREADS) && USE_MN_THREADS
781 struct coroutine_context;
782 extern void ruby_coroutine_start(struct coroutine_context *, struct coroutine_context *);
783 return ((void *)(ip) == (void *)ruby_coroutine_start);
784#else
785 return false;
786#endif
787}
788# endif
789
790int
791backtrace(void **trace, int size)
792{
793 unw_cursor_t cursor; unw_context_t uc;
794 unw_word_t ip;
795 int n = 0;
796
797 unw_getcontext(&uc);
798 unw_init_local(&cursor, &uc);
799# if defined(__x86_64__)
800 while (unw_step(&cursor) > 0) {
801 unw_get_reg(&cursor, UNW_REG_IP, &ip);
802 trace[n++] = (void *)ip;
803 {
804 char buf[256];
805 unw_get_proc_name(&cursor, buf, 256, &ip);
806 if (strncmp("_sigtramp", buf, sizeof("_sigtramp")) == 0) {
807 goto darwin_sigtramp;
808 }
809 }
810 }
811 return n;
812darwin_sigtramp:
813 /* darwin's bundled libunwind doesn't support signal trampoline */
814 {
815 ucontext_t *uctx;
816 char vec[1];
817 int r;
818 /* get previous frame information from %rbx at _sigtramp and set values to cursor
819 * https://www.opensource.apple.com/source/Libc/Libc-825.25/i386/sys/_sigtramp.s
820 * https://www.opensource.apple.com/source/libunwind/libunwind-35.1/src/unw_getcontext.s
821 */
822 unw_get_reg(&cursor, UNW_X86_64_RBX, &ip);
823 uctx = (ucontext_t *)ip;
824 unw_set_reg(&cursor, UNW_X86_64_RAX, uctx->uc_mcontext->MCTX_SS_REG(rax));
825 unw_set_reg(&cursor, UNW_X86_64_RBX, uctx->uc_mcontext->MCTX_SS_REG(rbx));
826 unw_set_reg(&cursor, UNW_X86_64_RCX, uctx->uc_mcontext->MCTX_SS_REG(rcx));
827 unw_set_reg(&cursor, UNW_X86_64_RDX, uctx->uc_mcontext->MCTX_SS_REG(rdx));
828 unw_set_reg(&cursor, UNW_X86_64_RDI, uctx->uc_mcontext->MCTX_SS_REG(rdi));
829 unw_set_reg(&cursor, UNW_X86_64_RSI, uctx->uc_mcontext->MCTX_SS_REG(rsi));
830 unw_set_reg(&cursor, UNW_X86_64_RBP, uctx->uc_mcontext->MCTX_SS_REG(rbp));
831 unw_set_reg(&cursor, UNW_X86_64_RSP, 8+(uctx->uc_mcontext->MCTX_SS_REG(rsp)));
832 unw_set_reg(&cursor, UNW_X86_64_R8, uctx->uc_mcontext->MCTX_SS_REG(r8));
833 unw_set_reg(&cursor, UNW_X86_64_R9, uctx->uc_mcontext->MCTX_SS_REG(r9));
834 unw_set_reg(&cursor, UNW_X86_64_R10, uctx->uc_mcontext->MCTX_SS_REG(r10));
835 unw_set_reg(&cursor, UNW_X86_64_R11, uctx->uc_mcontext->MCTX_SS_REG(r11));
836 unw_set_reg(&cursor, UNW_X86_64_R12, uctx->uc_mcontext->MCTX_SS_REG(r12));
837 unw_set_reg(&cursor, UNW_X86_64_R13, uctx->uc_mcontext->MCTX_SS_REG(r13));
838 unw_set_reg(&cursor, UNW_X86_64_R14, uctx->uc_mcontext->MCTX_SS_REG(r14));
839 unw_set_reg(&cursor, UNW_X86_64_R15, uctx->uc_mcontext->MCTX_SS_REG(r15));
840 ip = uctx->uc_mcontext->MCTX_SS_REG(rip);
841
842 /* There are 4 cases for SEGV:
843 * (1) called invalid address
844 * (2) read or write invalid address
845 * (3) received signal
846 *
847 * Detail:
848 * (1) called invalid address
849 * In this case, saved ip is invalid address.
850 * It needs to just save the address for the information,
851 * skip the frame, and restore the frame calling the
852 * invalid address from %rsp.
853 * The problem is how to check whether the ip is valid or not.
854 * This code uses mincore(2) and assume the address's page is
855 * incore/referenced or not reflects the problem.
856 * Note that High Sierra's mincore(2) may return -128.
857 * (2) read or write invalid address
858 * saved ip is valid. just restart backtracing.
859 * (3) received signal in user space
860 * Same as (2).
861 * (4) received signal in kernel
862 * In this case saved ip points just after syscall, but registers are
863 * already overwritten by kernel. To fix register consistency,
864 * skip libc's kernel wrapper.
865 * To detect this case, just previous two bytes of ip is "\x0f\x05",
866 * syscall instruction of x86_64.
867 */
868 r = mincore((const void *)ip, 1, vec);
869 if (r || vec[0] <= 0 || memcmp((const char *)ip-2, "\x0f\x05", 2) == 0) {
870 /* if segv is caused by invalid call or signal received in syscall */
871 /* the frame is invalid; skip */
872 trace[n++] = (void *)ip;
873 ip = *(unw_word_t*)uctx->uc_mcontext->MCTX_SS_REG(rsp);
874 }
875
876 trace[n++] = (void *)ip;
877 unw_set_reg(&cursor, UNW_REG_IP, ip);
878 }
879 while (unw_step(&cursor) > 0) {
880 unw_get_reg(&cursor, UNW_REG_IP, &ip);
881 trace[n++] = (void *)ip;
882 }
883 return n;
884
885# elif defined(__arm64__) || defined(__POWERPC__)
886 /* Since Darwin arm64's _sigtramp is implemented as normal function,
887 * unwind can unwind frames without special code.
888 * https://github.com/apple/darwin-libplatform/blob/215b09856ab5765b7462a91be7076183076600df/src/setjmp/generic/sigtramp.c
889 */
890 while (unw_step(&cursor) > 0) {
891 unw_get_reg(&cursor, UNW_REG_IP, &ip);
892# if defined(__arm64__)
893 // Strip Arm64's pointer authentication.
894 // https://developer.apple.com/documentation/security/preparing_your_app_to_work_with_pointer_authentication
895 // I wish I could use "ptrauth_strip()" but I get an error:
896 // "this target does not support pointer authentication"
897 trace[n++] = (void *)(ip & 0x7fffffffffffull);
898# else
899 trace[n++] = (void *)ip;
900# endif
901 // Apple's libunwind can't handle our coroutine switching code
902 if (is_coroutine_start(ip)) break;
903 }
904 return n;
905# else
906# error unsupported architecture
907# endif
908}
909# elif defined(BROKEN_BACKTRACE)
910# undef USE_BACKTRACE
911# define USE_BACKTRACE 0
912# endif
913#else
914# define USE_BACKTRACE 0
915#endif
916
917#if USE_BACKTRACE
918# include <execinfo.h>
919#elif defined(_WIN32)
920# include <imagehlp.h>
921# ifndef SYMOPT_DEBUG
922# define SYMOPT_DEBUG 0x80000000
923# endif
924# ifndef MAX_SYM_NAME
925# define MAX_SYM_NAME 2000
926typedef struct {
927 DWORD64 Offset;
928 WORD Segment;
929 ADDRESS_MODE Mode;
930} ADDRESS64;
931typedef struct {
932 DWORD64 Thread;
933 DWORD ThCallbackStack;
934 DWORD ThCallbackBStore;
935 DWORD NextCallback;
936 DWORD FramePointer;
937 DWORD64 KiCallUserMode;
938 DWORD64 KeUserCallbackDispatcher;
939 DWORD64 SystemRangeStart;
940 DWORD64 KiUserExceptionDispatcher;
941 DWORD64 StackBase;
942 DWORD64 StackLimit;
943 DWORD64 Reserved[5];
944} KDHELP64;
945typedef struct {
946 ADDRESS64 AddrPC;
947 ADDRESS64 AddrReturn;
948 ADDRESS64 AddrFrame;
949 ADDRESS64 AddrStack;
950 ADDRESS64 AddrBStore;
951 void *FuncTableEntry;
952 DWORD64 Params[4];
953 BOOL Far;
954 BOOL Virtual;
955 DWORD64 Reserved[3];
956 KDHELP64 KdHelp;
957} STACKFRAME64;
958typedef struct {
959 ULONG SizeOfStruct;
960 ULONG TypeIndex;
961 ULONG64 Reserved[2];
962 ULONG Index;
963 ULONG Size;
964 ULONG64 ModBase;
965 ULONG Flags;
966 ULONG64 Value;
967 ULONG64 Address;
968 ULONG Register;
969 ULONG Scope;
970 ULONG Tag;
971 ULONG NameLen;
972 ULONG MaxNameLen;
973 char Name[1];
974} SYMBOL_INFO;
975typedef struct {
976 DWORD SizeOfStruct;
977 void *Key;
978 DWORD LineNumber;
979 char *FileName;
980 DWORD64 Address;
981} IMAGEHLP_LINE64;
982typedef void *PREAD_PROCESS_MEMORY_ROUTINE64;
983typedef void *PFUNCTION_TABLE_ACCESS_ROUTINE64;
984typedef void *PGET_MODULE_BASE_ROUTINE64;
985typedef void *PTRANSLATE_ADDRESS_ROUTINE64;
986# endif
987
988struct dump_thead_arg {
989 DWORD tid;
990 FILE *errout;
991};
992
993static void
994dump_thread(void *arg)
995{
996 HANDLE dbghelp;
997 BOOL (WINAPI *pSymInitialize)(HANDLE, const char *, BOOL);
998 BOOL (WINAPI *pSymCleanup)(HANDLE);
999 BOOL (WINAPI *pStackWalk64)(DWORD, HANDLE, HANDLE, STACKFRAME64 *, void *, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64);
1000 DWORD64 (WINAPI *pSymGetModuleBase64)(HANDLE, DWORD64);
1001 BOOL (WINAPI *pSymFromAddr)(HANDLE, DWORD64, DWORD64 *, SYMBOL_INFO *);
1002 BOOL (WINAPI *pSymGetLineFromAddr64)(HANDLE, DWORD64, DWORD *, IMAGEHLP_LINE64 *);
1003 HANDLE (WINAPI *pOpenThread)(DWORD, BOOL, DWORD);
1004 DWORD tid = ((struct dump_thead_arg *)arg)->tid;
1005 FILE *errout = ((struct dump_thead_arg *)arg)->errout;
1006 HANDLE ph;
1007 HANDLE th;
1008
1009 dbghelp = LoadLibrary("dbghelp.dll");
1010 if (!dbghelp) return;
1011 pSymInitialize = (BOOL (WINAPI *)(HANDLE, const char *, BOOL))GetProcAddress(dbghelp, "SymInitialize");
1012 pSymCleanup = (BOOL (WINAPI *)(HANDLE))GetProcAddress(dbghelp, "SymCleanup");
1013 pStackWalk64 = (BOOL (WINAPI *)(DWORD, HANDLE, HANDLE, STACKFRAME64 *, void *, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64))GetProcAddress(dbghelp, "StackWalk64");
1014 pSymGetModuleBase64 = (DWORD64 (WINAPI *)(HANDLE, DWORD64))GetProcAddress(dbghelp, "SymGetModuleBase64");
1015 pSymFromAddr = (BOOL (WINAPI *)(HANDLE, DWORD64, DWORD64 *, SYMBOL_INFO *))GetProcAddress(dbghelp, "SymFromAddr");
1016 pSymGetLineFromAddr64 = (BOOL (WINAPI *)(HANDLE, DWORD64, DWORD *, IMAGEHLP_LINE64 *))GetProcAddress(dbghelp, "SymGetLineFromAddr64");
1017 pOpenThread = (HANDLE (WINAPI *)(DWORD, BOOL, DWORD))GetProcAddress(GetModuleHandle("kernel32.dll"), "OpenThread");
1018 if (pSymInitialize && pSymCleanup && pStackWalk64 && pSymGetModuleBase64 &&
1019 pSymFromAddr && pSymGetLineFromAddr64 && pOpenThread) {
1020 SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_DEBUG | SYMOPT_LOAD_LINES);
1021 ph = GetCurrentProcess();
1022 pSymInitialize(ph, NULL, TRUE);
1023 th = pOpenThread(THREAD_SUSPEND_RESUME|THREAD_GET_CONTEXT, FALSE, tid);
1024 if (th) {
1025 if (SuspendThread(th) != (DWORD)-1) {
1026 CONTEXT context;
1027 memset(&context, 0, sizeof(context));
1028 context.ContextFlags = CONTEXT_FULL;
1029 if (GetThreadContext(th, &context)) {
1030 char libpath[MAX_PATH];
1031 char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1032 SYMBOL_INFO *info = (SYMBOL_INFO *)buf;
1033 DWORD mac;
1034 STACKFRAME64 frame;
1035 memset(&frame, 0, sizeof(frame));
1036#if defined(_M_AMD64) || defined(__x86_64__)
1037 mac = IMAGE_FILE_MACHINE_AMD64;
1038 frame.AddrPC.Mode = AddrModeFlat;
1039 frame.AddrPC.Offset = context.Rip;
1040 frame.AddrFrame.Mode = AddrModeFlat;
1041 frame.AddrFrame.Offset = context.Rbp;
1042 frame.AddrStack.Mode = AddrModeFlat;
1043 frame.AddrStack.Offset = context.Rsp;
1044#elif defined(_M_ARM64) || defined(__aarch64__)
1045 mac = IMAGE_FILE_MACHINE_ARM64;
1046 frame.AddrPC.Mode = AddrModeFlat;
1047 frame.AddrPC.Offset = context.Pc;
1048 frame.AddrFrame.Mode = AddrModeFlat;
1049 frame.AddrFrame.Offset = context.Fp;
1050 frame.AddrStack.Mode = AddrModeFlat;
1051 frame.AddrStack.Offset = context.Sp;
1052#else /* i386 */
1053 mac = IMAGE_FILE_MACHINE_I386;
1054 frame.AddrPC.Mode = AddrModeFlat;
1055 frame.AddrPC.Offset = context.Eip;
1056 frame.AddrFrame.Mode = AddrModeFlat;
1057 frame.AddrFrame.Offset = context.Ebp;
1058 frame.AddrStack.Mode = AddrModeFlat;
1059 frame.AddrStack.Offset = context.Esp;
1060#endif
1061
1062 while (pStackWalk64(mac, ph, th, &frame, &context, NULL,
1063 NULL, NULL, NULL)) {
1064 DWORD64 addr = frame.AddrPC.Offset;
1065 IMAGEHLP_LINE64 line;
1066 DWORD64 displacement;
1067 DWORD tmp;
1068
1069 if (addr == frame.AddrReturn.Offset || addr == 0 ||
1070 frame.AddrReturn.Offset == 0)
1071 break;
1072
1073 memset(buf, 0, sizeof(buf));
1074 info->SizeOfStruct = sizeof(SYMBOL_INFO);
1075 info->MaxNameLen = MAX_SYM_NAME;
1076 if (pSymFromAddr(ph, addr, &displacement, info)) {
1077 if (GetModuleFileName((HANDLE)(uintptr_t)pSymGetModuleBase64(ph, addr), libpath, sizeof(libpath)))
1078 kprintf("%s", libpath);
1079 kprintf("(%s+0x%"PRI_64_PREFIX"x)",
1080 info->Name, displacement);
1081 }
1082 kprintf(" [0x%p]", (void *)(VALUE)addr);
1083 memset(&line, 0, sizeof(line));
1084 line.SizeOfStruct = sizeof(line);
1085 if (pSymGetLineFromAddr64(ph, addr, &tmp, &line))
1086 kprintf(" %s:%lu", line.FileName, line.LineNumber);
1087 kprintf("\n");
1088 }
1089 }
1090
1091 error:
1092 ResumeThread(th);
1093 }
1094 CloseHandle(th);
1095 }
1096 pSymCleanup(ph);
1097 }
1098 FreeLibrary(dbghelp);
1099}
1100#endif
1101
1102void
1103rb_print_backtrace(FILE *errout)
1104{
1105#if USE_BACKTRACE
1106#define MAX_NATIVE_TRACE 1024
1107 static void *trace[MAX_NATIVE_TRACE];
1108 int n = (int)backtrace(trace, MAX_NATIVE_TRACE);
1109#if (defined(USE_ELF) || defined(HAVE_MACH_O_LOADER_H)) && defined(HAVE_DLADDR) && !defined(__sparc)
1110 rb_dump_backtrace_with_lines(n, trace, errout);
1111#else
1112 char **syms = backtrace_symbols(trace, n);
1113 if (syms) {
1114 int i;
1115 for (i=0; i<n; i++) {
1116 kprintf("%s\n", syms[i]);
1117 }
1118 free(syms);
1119 }
1120 error:
1121 /* ignore errors at writing */;
1122#endif
1123#elif defined(_WIN32)
1124 struct dump_thead_arg arg = {
1125 .tid = GetCurrentThreadId(),
1126 .errout = errout,
1127 };
1128 HANDLE th = (HANDLE)_beginthread(dump_thread, 0, &arg);
1129 if (th != (HANDLE)-1)
1130 WaitForSingleObject(th, INFINITE);
1131#endif
1132}
1133
1134#ifdef HAVE_LIBPROCSTAT
1135struct procstat;
1136struct kinfo_proc;
1137static void procstat_vm(struct procstat *, struct kinfo_proc *, FILE *);
1138#include "missing/procstat_vm.c"
1139#endif
1140
1141#if defined __linux__
1142# if defined(__x86_64__) || defined(__i386__)
1143# define dump_machine_register(reg) (col_count = print_machine_register(errout, mctx->gregs[REG_##reg], #reg, col_count, 80))
1144# elif defined(__aarch64__) || defined(__arm__) || defined(__riscv) || defined(__loongarch64)
1145# define dump_machine_register(reg, regstr) (col_count = print_machine_register(errout, reg, regstr, col_count, 80))
1146# endif
1147#elif defined __APPLE__
1148# if defined(__aarch64__)
1149# define dump_machine_register(reg, regstr) (col_count = print_machine_register(errout, mctx->MCTX_SS_REG(reg), regstr, col_count, 80))
1150# else
1151# define dump_machine_register(reg) (col_count = print_machine_register(errout, mctx->MCTX_SS_REG(reg), #reg, col_count, 80))
1152# endif
1153#endif
1154
1155#ifdef dump_machine_register
1156static int
1157print_machine_register(FILE *errout, size_t reg, const char *reg_name, int col_count, int max_col)
1158{
1159 int ret;
1160 char buf[64];
1161 static const int size_width = sizeof(size_t) * CHAR_BIT / 4;
1162
1163 ret = snprintf(buf, sizeof(buf), " %3.3s: 0x%.*" PRIxSIZE, reg_name, size_width, reg);
1164 if (col_count + ret > max_col) {
1165 kputs("\n");
1166 col_count = 0;
1167 }
1168 col_count += ret;
1169 kputs(buf);
1170 return col_count;
1171
1172 error:
1173 return -1;
1174}
1175
1176static bool
1177rb_dump_machine_register(FILE *errout, const ucontext_t *ctx)
1178{
1179 int col_count = 0;
1180 if (!ctx) return true;
1181
1182 kprintf("-- Machine register context "
1183 "------------------------------------------------\n");
1184
1185# if defined __linux__
1186 {
1187 const mcontext_t *const mctx = &ctx->uc_mcontext;
1188# if defined __x86_64__
1189 dump_machine_register(RIP);
1190 dump_machine_register(RBP);
1191 dump_machine_register(RSP);
1192 dump_machine_register(RAX);
1193 dump_machine_register(RBX);
1194 dump_machine_register(RCX);
1195 dump_machine_register(RDX);
1196 dump_machine_register(RDI);
1197 dump_machine_register(RSI);
1198 dump_machine_register(R8);
1199 dump_machine_register(R9);
1200 dump_machine_register(R10);
1201 dump_machine_register(R11);
1202 dump_machine_register(R12);
1203 dump_machine_register(R13);
1204 dump_machine_register(R14);
1205 dump_machine_register(R15);
1206 dump_machine_register(EFL);
1207# elif defined __i386__
1208 dump_machine_register(GS);
1209 dump_machine_register(FS);
1210 dump_machine_register(ES);
1211 dump_machine_register(DS);
1212 dump_machine_register(EDI);
1213 dump_machine_register(ESI);
1214 dump_machine_register(EBP);
1215 dump_machine_register(ESP);
1216 dump_machine_register(EBX);
1217 dump_machine_register(EDX);
1218 dump_machine_register(ECX);
1219 dump_machine_register(EAX);
1220 dump_machine_register(TRAPNO);
1221 dump_machine_register(ERR);
1222 dump_machine_register(EIP);
1223 dump_machine_register(CS);
1224 dump_machine_register(EFL);
1225 dump_machine_register(UESP);
1226 dump_machine_register(SS);
1227# elif defined __aarch64__
1228 dump_machine_register(mctx->regs[0], "x0");
1229 dump_machine_register(mctx->regs[1], "x1");
1230 dump_machine_register(mctx->regs[2], "x2");
1231 dump_machine_register(mctx->regs[3], "x3");
1232 dump_machine_register(mctx->regs[4], "x4");
1233 dump_machine_register(mctx->regs[5], "x5");
1234 dump_machine_register(mctx->regs[6], "x6");
1235 dump_machine_register(mctx->regs[7], "x7");
1236 dump_machine_register(mctx->regs[18], "x18");
1237 dump_machine_register(mctx->regs[19], "x19");
1238 dump_machine_register(mctx->regs[20], "x20");
1239 dump_machine_register(mctx->regs[21], "x21");
1240 dump_machine_register(mctx->regs[22], "x22");
1241 dump_machine_register(mctx->regs[23], "x23");
1242 dump_machine_register(mctx->regs[24], "x24");
1243 dump_machine_register(mctx->regs[25], "x25");
1244 dump_machine_register(mctx->regs[26], "x26");
1245 dump_machine_register(mctx->regs[27], "x27");
1246 dump_machine_register(mctx->regs[28], "x28");
1247 dump_machine_register(mctx->regs[29], "x29");
1248 dump_machine_register(mctx->sp, "sp");
1249 dump_machine_register(mctx->fault_address, "fault_address");
1250# elif defined __arm__
1251 dump_machine_register(mctx->arm_r0, "r0");
1252 dump_machine_register(mctx->arm_r1, "r1");
1253 dump_machine_register(mctx->arm_r2, "r2");
1254 dump_machine_register(mctx->arm_r3, "r3");
1255 dump_machine_register(mctx->arm_r4, "r4");
1256 dump_machine_register(mctx->arm_r5, "r5");
1257 dump_machine_register(mctx->arm_r6, "r6");
1258 dump_machine_register(mctx->arm_r7, "r7");
1259 dump_machine_register(mctx->arm_r8, "r8");
1260 dump_machine_register(mctx->arm_r9, "r9");
1261 dump_machine_register(mctx->arm_r10, "r10");
1262 dump_machine_register(mctx->arm_sp, "sp");
1263 dump_machine_register(mctx->fault_address, "fault_address");
1264# elif defined __riscv
1265 dump_machine_register(mctx->__gregs[REG_SP], "sp");
1266 dump_machine_register(mctx->__gregs[REG_S0], "s0");
1267 dump_machine_register(mctx->__gregs[REG_S1], "s1");
1268 dump_machine_register(mctx->__gregs[REG_A0], "a0");
1269 dump_machine_register(mctx->__gregs[REG_A0+1], "a1");
1270 dump_machine_register(mctx->__gregs[REG_A0+2], "a2");
1271 dump_machine_register(mctx->__gregs[REG_A0+3], "a3");
1272 dump_machine_register(mctx->__gregs[REG_A0+4], "a4");
1273 dump_machine_register(mctx->__gregs[REG_A0+5], "a5");
1274 dump_machine_register(mctx->__gregs[REG_A0+6], "a6");
1275 dump_machine_register(mctx->__gregs[REG_A0+7], "a7");
1276 dump_machine_register(mctx->__gregs[REG_S2], "s2");
1277 dump_machine_register(mctx->__gregs[REG_S2+1], "s3");
1278 dump_machine_register(mctx->__gregs[REG_S2+2], "s4");
1279 dump_machine_register(mctx->__gregs[REG_S2+3], "s5");
1280 dump_machine_register(mctx->__gregs[REG_S2+4], "s6");
1281 dump_machine_register(mctx->__gregs[REG_S2+5], "s7");
1282 dump_machine_register(mctx->__gregs[REG_S2+6], "s8");
1283 dump_machine_register(mctx->__gregs[REG_S2+7], "s9");
1284 dump_machine_register(mctx->__gregs[REG_S2+8], "s10");
1285 dump_machine_register(mctx->__gregs[REG_S2+9], "s11");
1286# elif defined __loongarch64
1287 dump_machine_register(mctx->__gregs[LARCH_REG_SP], "sp");
1288 dump_machine_register(mctx->__gregs[LARCH_REG_A0], "a0");
1289 dump_machine_register(mctx->__gregs[LARCH_REG_A0+1], "a1");
1290 dump_machine_register(mctx->__gregs[LARCH_REG_A0+2], "a2");
1291 dump_machine_register(mctx->__gregs[LARCH_REG_A0+3], "a3");
1292 dump_machine_register(mctx->__gregs[LARCH_REG_A0+4], "a4");
1293 dump_machine_register(mctx->__gregs[LARCH_REG_A0+5], "a5");
1294 dump_machine_register(mctx->__gregs[LARCH_REG_A0+6], "a6");
1295 dump_machine_register(mctx->__gregs[LARCH_REG_A0+7], "a7");
1296 dump_machine_register(mctx->__gregs[LARCH_REG_A0+8], "fp");
1297 dump_machine_register(mctx->__gregs[LARCH_REG_S0], "s0");
1298 dump_machine_register(mctx->__gregs[LARCH_REG_S1], "s1");
1299 dump_machine_register(mctx->__gregs[LARCH_REG_S2], "s2");
1300 dump_machine_register(mctx->__gregs[LARCH_REG_S0+3], "s3");
1301 dump_machine_register(mctx->__gregs[LARCH_REG_S0+4], "s4");
1302 dump_machine_register(mctx->__gregs[LARCH_REG_S0+5], "s5");
1303 dump_machine_register(mctx->__gregs[LARCH_REG_S0+6], "s6");
1304 dump_machine_register(mctx->__gregs[LARCH_REG_S0+7], "s7");
1305 dump_machine_register(mctx->__gregs[LARCH_REG_S0+8], "s8");
1306# endif
1307 }
1308# elif defined __APPLE__
1309 {
1310 const mcontext_t mctx = ctx->uc_mcontext;
1311# if defined __x86_64__
1312 dump_machine_register(rax);
1313 dump_machine_register(rbx);
1314 dump_machine_register(rcx);
1315 dump_machine_register(rdx);
1316 dump_machine_register(rdi);
1317 dump_machine_register(rsi);
1318 dump_machine_register(rbp);
1319 dump_machine_register(rsp);
1320 dump_machine_register(r8);
1321 dump_machine_register(r9);
1322 dump_machine_register(r10);
1323 dump_machine_register(r11);
1324 dump_machine_register(r12);
1325 dump_machine_register(r13);
1326 dump_machine_register(r14);
1327 dump_machine_register(r15);
1328 dump_machine_register(rip);
1329 dump_machine_register(rflags);
1330# elif defined __i386__
1331 dump_machine_register(eax);
1332 dump_machine_register(ebx);
1333 dump_machine_register(ecx);
1334 dump_machine_register(edx);
1335 dump_machine_register(edi);
1336 dump_machine_register(esi);
1337 dump_machine_register(ebp);
1338 dump_machine_register(esp);
1339 dump_machine_register(ss);
1340 dump_machine_register(eflags);
1341 dump_machine_register(eip);
1342 dump_machine_register(cs);
1343 dump_machine_register(ds);
1344 dump_machine_register(es);
1345 dump_machine_register(fs);
1346 dump_machine_register(gs);
1347# elif defined __aarch64__
1348 dump_machine_register(x[0], "x0");
1349 dump_machine_register(x[1], "x1");
1350 dump_machine_register(x[2], "x2");
1351 dump_machine_register(x[3], "x3");
1352 dump_machine_register(x[4], "x4");
1353 dump_machine_register(x[5], "x5");
1354 dump_machine_register(x[6], "x6");
1355 dump_machine_register(x[7], "x7");
1356 dump_machine_register(x[18], "x18");
1357 dump_machine_register(x[19], "x19");
1358 dump_machine_register(x[20], "x20");
1359 dump_machine_register(x[21], "x21");
1360 dump_machine_register(x[22], "x22");
1361 dump_machine_register(x[23], "x23");
1362 dump_machine_register(x[24], "x24");
1363 dump_machine_register(x[25], "x25");
1364 dump_machine_register(x[26], "x26");
1365 dump_machine_register(x[27], "x27");
1366 dump_machine_register(x[28], "x28");
1367 dump_machine_register(lr, "lr");
1368 dump_machine_register(fp, "fp");
1369 dump_machine_register(sp, "sp");
1370# endif
1371 }
1372# endif
1373 kprintf("\n\n");
1374 return true;
1375
1376 error:
1377 return false;
1378}
1379#else
1380# define rb_dump_machine_register(errout, ctx) ((void)0)
1381#endif /* dump_machine_register */
1382
1383bool
1384rb_vm_bugreport(const void *ctx, FILE *errout)
1385{
1386 const char *box_env = getenv("RUBY_BUGREPORT_BOX_ENV");
1387 const char *cmd = getenv("RUBY_ON_BUG");
1388 if (cmd) {
1389 char buf[0x100];
1390 snprintf(buf, sizeof(buf), "%s %"PRI_PIDT_PREFIX"d", cmd, getpid());
1391 int r = system(buf);
1392 if (r == -1) {
1393 snprintf(buf, sizeof(buf), "Launching RUBY_ON_BUG command failed.");
1394 }
1395 }
1396
1397 // Thread unsafe best effort attempt to stop printing the bug report in an
1398 // infinite loop. Can happen with corrupt Ruby stack.
1399 {
1400 static bool crashing = false;
1401 if (crashing) {
1402 kprintf("Crashed while printing bug report\n");
1403 return true;
1404 }
1405 crashing = true;
1406 }
1407
1408#ifdef __linux__
1409# define PROC_MAPS_NAME "/proc/self/maps"
1410#endif
1411#ifdef PROC_MAPS_NAME
1412 enum {other_runtime_info = 1};
1413#else
1414 enum {other_runtime_info = 0};
1415#endif
1416 const rb_vm_t *const vm = GET_VM();
1417 const rb_box_t *current_box = rb_current_box_in_crash_report();
1418 const rb_execution_context_t *ec = rb_current_execution_context(false);
1419 VALUE loaded_features;
1420
1421 if (current_box) {
1422 loaded_features = current_box->loaded_features;
1423 }
1424 else {
1425 loaded_features = rb_root_box()->loaded_features;
1426 }
1427
1428 if (vm && ec) {
1429 rb_vmdebug_stack_dump_raw(ec, ec->cfp, errout);
1430 if (box_env) {
1431 rb_vmdebug_box_env_dump_raw(ec, ec->cfp, errout);
1432 }
1433 rb_backtrace_print_as_bugreport(errout);
1434 kputs("\n");
1435 // If we get here, hopefully things are intact enough that
1436 // we can read these two numbers. It is an estimate because
1437 // we are reading without synchronization.
1438 kprintf("-- Threading information "
1439 "---------------------------------------------------\n");
1440 kprintf("Total ractor count: %u\n", vm->ractor.cnt);
1441 kprintf("Ruby thread count for this ractor: %u\n", rb_ec_ractor_ptr(ec)->threads.cnt);
1442 if (ec->thread_ptr->scheduler != Qnil) {
1443 kprintf("Note that the Fiber scheduler is enabled\n");
1444 }
1445 kputs("\n");
1446 }
1447
1448 rb_dump_machine_register(errout, ctx);
1449
1450#if USE_BACKTRACE || defined(_WIN32)
1451 kprintf("-- C level backtrace information "
1452 "-------------------------------------------\n");
1453 rb_print_backtrace(errout);
1454
1455
1456 kprintf("\n");
1457#endif /* USE_BACKTRACE */
1458
1459 if (other_runtime_info || vm) {
1460 kprintf("-- Other runtime information "
1461 "-----------------------------------------------\n\n");
1462 }
1463 if (vm && !rb_during_gc()) {
1464 int i;
1465 VALUE name;
1466 long len;
1467 const int max_name_length = 1024;
1468# define LIMITED_NAME_LENGTH(s) \
1469 (((len = RSTRING_LEN(s)) > max_name_length) ? max_name_length : (int)len)
1470
1471 name = vm->progname;
1472 if (name) {
1473 kprintf("* Loaded script: %.*s\n",
1474 LIMITED_NAME_LENGTH(name), RSTRING_PTR(name));
1475 kprintf("\n");
1476 }
1477 if (rb_box_available()) {
1478 kprintf("* Ruby Box: enabled\n");
1479 if (current_box) {
1480 kprintf("* Current box id: %ld, type: %s\n",
1481 current_box->box_id,
1482 BOX_USER_P(current_box) ? (BOX_MAIN_P(current_box) ? "main" : "user") : "root");
1483 }
1484 else {
1485 kprintf("* Current box: NULL (crashed)\n");
1486 }
1487 }
1488 else {
1489 kprintf("* Ruby Box: disabled\n");
1490 }
1491 if (loaded_features) {
1492 kprintf("* Loaded features:\n\n");
1493 for (i=0; i<RARRAY_LEN(loaded_features); i++) {
1494 name = RARRAY_AREF(loaded_features, i);
1495 if (RB_TYPE_P(name, T_STRING)) {
1496 kprintf(" %4d %.*s\n", i,
1497 LIMITED_NAME_LENGTH(name), RSTRING_PTR(name));
1498 }
1499 else if (RB_TYPE_P(name, T_CLASS) || RB_TYPE_P(name, T_MODULE)) {
1500 const char *const type = RB_TYPE_P(name, T_CLASS) ?
1501 "class" : "module";
1502 name = rb_search_class_path(rb_class_real(name));
1503 if (!RB_TYPE_P(name, T_STRING)) {
1504 kprintf(" %4d %s:<unnamed>\n", i, type);
1505 continue;
1506 }
1507 kprintf(" %4d %s:%.*s\n", i, type,
1508 LIMITED_NAME_LENGTH(name), RSTRING_PTR(name));
1509 }
1510 else {
1511 VALUE klass = rb_search_class_path(rb_obj_class(name));
1512 if (!RB_TYPE_P(klass, T_STRING)) {
1513 kprintf(" %4d #<%p:%p>\n", i,
1514 (void *)CLASS_OF(name), (void *)name);
1515 continue;
1516 }
1517 kprintf(" %4d #<%.*s:%p>\n", i,
1518 LIMITED_NAME_LENGTH(klass), RSTRING_PTR(klass),
1519 (void *)name);
1520 }
1521 }
1522 }
1523 kprintf("\n");
1524 }
1525
1526 {
1527#ifndef RUBY_ASAN_ENABLED
1528# ifdef PROC_MAPS_NAME
1529 {
1530 FILE *fp = fopen(PROC_MAPS_NAME, "r");
1531 if (fp) {
1532 kprintf("* Process memory map:\n\n");
1533
1534 while (!feof(fp)) {
1535 char buff[0x100];
1536 size_t rn = fread(buff, 1, 0x100, fp);
1537 if (fwrite(buff, 1, rn, errout) != rn)
1538 break;
1539 }
1540
1541 fclose(fp);
1542 kprintf("\n\n");
1543 }
1544 }
1545# endif /* __linux__ */
1546# ifdef HAVE_LIBPROCSTAT
1547# define MIB_KERN_PROC_PID_LEN 4
1548 int mib[MIB_KERN_PROC_PID_LEN];
1549 struct kinfo_proc kp;
1550 size_t len = sizeof(struct kinfo_proc);
1551 mib[0] = CTL_KERN;
1552 mib[1] = KERN_PROC;
1553 mib[2] = KERN_PROC_PID;
1554 mib[3] = getpid();
1555 if (sysctl(mib, MIB_KERN_PROC_PID_LEN, &kp, &len, NULL, 0) == -1) {
1556 kprintf("sysctl: %s\n", strerror(errno));
1557 }
1558 else {
1559 struct procstat *prstat = procstat_open_sysctl();
1560 kprintf("* Process memory map:\n\n");
1561 procstat_vm(prstat, &kp, errout);
1562 procstat_close(prstat);
1563 kprintf("\n");
1564 }
1565# endif /* __FreeBSD__ */
1566# ifdef __APPLE__
1567 vm_address_t addr = 0;
1568 vm_size_t size = 0;
1569 struct vm_region_submap_info map;
1570 mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT;
1571 natural_t depth = 0;
1572
1573 kprintf("* Process memory map:\n\n");
1574 while (1) {
1575 if (vm_region_recurse(mach_task_self(), &addr, &size, &depth,
1576 (vm_region_recurse_info_t)&map, &count) != KERN_SUCCESS) {
1577 break;
1578 }
1579
1580 if (map.is_submap) {
1581 // We only look at main addresses
1582 depth++;
1583 }
1584 else {
1585 kprintf("%lx-%lx %s%s%s", addr, (addr+size),
1586 ((map.protection & VM_PROT_READ) != 0 ? "r" : "-"),
1587 ((map.protection & VM_PROT_WRITE) != 0 ? "w" : "-"),
1588 ((map.protection & VM_PROT_EXECUTE) != 0 ? "x" : "-"));
1589# ifdef HAVE_LIBPROC_H
1590 char buff[PATH_MAX];
1591 if (proc_regionfilename(getpid(), addr, buff, sizeof(buff)) > 0) {
1592 kprintf(" %s", buff);
1593 }
1594# endif
1595 kprintf("\n");
1596 }
1597
1598 addr += size;
1599 size = 0;
1600 }
1601# endif
1602#endif
1603 }
1604 return true;
1605
1606 error:
1607 return false;
1608}
1609
1610bool
1611rb_vmdebug_stack_dump_all_threads(void)
1612{
1613 rb_thread_t *th = NULL;
1614 rb_ractor_t *r = GET_RACTOR();
1615 FILE *errout = stderr;
1616
1617 // TODO: now it only shows current ractor
1618 ccan_list_for_each(&r->threads.set, th, lt_node) {
1619#ifdef NON_SCALAR_THREAD_ID
1620 kprintf("th: %p, native_id: N/A\n", th);
1621#else
1622 kprintf("th: %p, native_id: %p\n", (void *)th, (void *)(uintptr_t)th->nt->thread_id);
1623#endif
1624 if (!rb_vmdebug_stack_dump_raw(th->ec, th->ec->cfp, errout)) goto error;
1625 }
1626 return true;
1627
1628 error:
1629 return false;
1630}
rb_str_new2
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
TYPE
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
T_STRING
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
T_IMEMO
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition value_type.h:67
CLASS_OF
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
T_MODULE
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
T_UNDEF
#define T_UNDEF
Old name of RUBY_T_UNDEF.
Definition value_type.h:82
Qnil
#define Qnil
Old name of RUBY_Qnil.
Definition special_consts.h:60
Qfalse
#define Qfalse
Old name of RUBY_Qfalse.
Definition special_consts.h:59
T_CLASS
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
SYMBOL_P
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
rb_obj_class
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
rb_inspect
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:686
rb_class_real
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition object.c:255
rb_during_gc
int rb_during_gc(void)
Queries if the GC is busy.
Definition gc.c:4276
rb_sym2str
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:993
len
int len
Length of the buffer.
Definition io.h:8
ruby::backward::cxxanyargs::type
VALUE type(ANYARGS)
ANYARGS-ed function type.
Definition cxxanyargs.hpp:56
PRI_PIDT_PREFIX
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
Definition pid_t.h:38
RARRAY_LEN
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
RARRAY_AREF
#define RARRAY_AREF(a, i)
Definition rarray.h:403
StringValueCStr
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
errno
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
scheduler.h
Scheduler APIs.
coroutine_context
Definition Context.h:36
rb_env_t
Definition vm_core.h:1301
rb_proc_t
Definition vm_core.h:1288
vm_svar
SVAR (Special VARiable).
Definition imemo.h:50
VALUE
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
RB_TYPE_P
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