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