Ruby: vm_dump.c Source File

Ruby 4.0.5p0 (2026-05-20 revision 64336ffd0ee9e1f4c05891695a3d7b49cb709721)

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