Ruby 4.1.0dev (2026-09-26 revision 57213d44ce7b1a31fc9648e9cd5eb0c4507f4a49)
vm_dump.c (57213d44ce7b1a31fc9648e9cd5eb0c4507f4a49)
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 if (size <= 0) return 0;
803
804 unw_getcontext(&uc);
805 unw_init_local(&cursor, &uc);
806# if defined(__x86_64__)
807 while (n < size && unw_step(&cursor) > 0) {
808 unw_get_reg(&cursor, UNW_REG_IP, &ip);
809 trace[n++] = (void *)ip;
810 {
811 char buf[256];
812 unw_get_proc_name(&cursor, buf, 256, &ip);
813 if (strncmp("_sigtramp", buf, sizeof("_sigtramp")) == 0) {
814 goto darwin_sigtramp;
815 }
816 }
817 }
818 return n;
819darwin_sigtramp:
820 if (n == size) return n;
821 /* darwin's bundled libunwind doesn't support signal trampoline */
822 {
823 ucontext_t *uctx;
824 char vec[1];
825 int r;
826 /* get previous frame information from %rbx at _sigtramp and set values to cursor
827 * https://www.opensource.apple.com/source/Libc/Libc-825.25/i386/sys/_sigtramp.s
828 * https://www.opensource.apple.com/source/libunwind/libunwind-35.1/src/unw_getcontext.s
829 */
830 unw_get_reg(&cursor, UNW_X86_64_RBX, &ip);
831 uctx = (ucontext_t *)ip;
832 unw_set_reg(&cursor, UNW_X86_64_RAX, uctx->uc_mcontext->MCTX_SS_REG(rax));
833 unw_set_reg(&cursor, UNW_X86_64_RBX, uctx->uc_mcontext->MCTX_SS_REG(rbx));
834 unw_set_reg(&cursor, UNW_X86_64_RCX, uctx->uc_mcontext->MCTX_SS_REG(rcx));
835 unw_set_reg(&cursor, UNW_X86_64_RDX, uctx->uc_mcontext->MCTX_SS_REG(rdx));
836 unw_set_reg(&cursor, UNW_X86_64_RDI, uctx->uc_mcontext->MCTX_SS_REG(rdi));
837 unw_set_reg(&cursor, UNW_X86_64_RSI, uctx->uc_mcontext->MCTX_SS_REG(rsi));
838 unw_set_reg(&cursor, UNW_X86_64_RBP, uctx->uc_mcontext->MCTX_SS_REG(rbp));
839 unw_set_reg(&cursor, UNW_X86_64_RSP, 8+(uctx->uc_mcontext->MCTX_SS_REG(rsp)));
840 unw_set_reg(&cursor, UNW_X86_64_R8, uctx->uc_mcontext->MCTX_SS_REG(r8));
841 unw_set_reg(&cursor, UNW_X86_64_R9, uctx->uc_mcontext->MCTX_SS_REG(r9));
842 unw_set_reg(&cursor, UNW_X86_64_R10, uctx->uc_mcontext->MCTX_SS_REG(r10));
843 unw_set_reg(&cursor, UNW_X86_64_R11, uctx->uc_mcontext->MCTX_SS_REG(r11));
844 unw_set_reg(&cursor, UNW_X86_64_R12, uctx->uc_mcontext->MCTX_SS_REG(r12));
845 unw_set_reg(&cursor, UNW_X86_64_R13, uctx->uc_mcontext->MCTX_SS_REG(r13));
846 unw_set_reg(&cursor, UNW_X86_64_R14, uctx->uc_mcontext->MCTX_SS_REG(r14));
847 unw_set_reg(&cursor, UNW_X86_64_R15, uctx->uc_mcontext->MCTX_SS_REG(r15));
848 ip = uctx->uc_mcontext->MCTX_SS_REG(rip);
849
850 /* There are 4 cases for SEGV:
851 * (1) called invalid address
852 * (2) read or write invalid address
853 * (3) received signal
854 *
855 * Detail:
856 * (1) called invalid address
857 * In this case, saved ip is invalid address.
858 * It needs to just save the address for the information,
859 * skip the frame, and restore the frame calling the
860 * invalid address from %rsp.
861 * The problem is how to check whether the ip is valid or not.
862 * This code uses mincore(2) and assume the address's page is
863 * incore/referenced or not reflects the problem.
864 * Note that High Sierra's mincore(2) may return -128.
865 * (2) read or write invalid address
866 * saved ip is valid. just restart backtracing.
867 * (3) received signal in user space
868 * Same as (2).
869 * (4) received signal in kernel
870 * In this case saved ip points just after syscall, but registers are
871 * already overwritten by kernel. To fix register consistency,
872 * skip libc's kernel wrapper.
873 * To detect this case, just previous two bytes of ip is "\x0f\x05",
874 * syscall instruction of x86_64.
875 */
876 r = mincore((const void *)ip, 1, vec);
877 if (r || vec[0] <= 0 || memcmp((const char *)ip-2, "\x0f\x05", 2) == 0) {
878 /* if segv is caused by invalid call or signal received in syscall */
879 /* the frame is invalid; skip */
880 trace[n++] = (void *)ip;
881 if (n == size) return n;
882 ip = *(unw_word_t*)uctx->uc_mcontext->MCTX_SS_REG(rsp);
883 }
884
885 trace[n++] = (void *)ip;
886 unw_set_reg(&cursor, UNW_REG_IP, ip);
887 }
888 while (n < size && unw_step(&cursor) > 0) {
889 unw_get_reg(&cursor, UNW_REG_IP, &ip);
890 trace[n++] = (void *)ip;
891 }
892 return n;
893
894# elif defined(__arm64__) || defined(__POWERPC__)
895 /* Since Darwin arm64's _sigtramp is implemented as normal function,
896 * unwind can unwind frames without special code.
897 * https://github.com/apple/darwin-libplatform/blob/215b09856ab5765b7462a91be7076183076600df/src/setjmp/generic/sigtramp.c
898 */
899 while (n < size && unw_step(&cursor) > 0) {
900 unw_get_reg(&cursor, UNW_REG_IP, &ip);
901# if defined(__arm64__)
902 // Strip Arm64's pointer authentication.
903 // https://developer.apple.com/documentation/security/preparing_your_app_to_work_with_pointer_authentication
904 // I wish I could use "ptrauth_strip()" but I get an error:
905 // "this target does not support pointer authentication"
906 trace[n++] = (void *)(ip & 0x7fffffffffffull);
907# else
908 trace[n++] = (void *)ip;
909# endif
910 // Apple's libunwind can't handle our coroutine switching code
911 if (is_coroutine_start(ip)) break;
912 }
913 return n;
914# else
915# error unsupported architecture
916# endif
917}
918# elif defined(BROKEN_BACKTRACE)
919# undef USE_BACKTRACE
920# define USE_BACKTRACE 0
921# endif
922#else
923# define USE_BACKTRACE 0
924#endif
925
926#if USE_BACKTRACE
927# include <execinfo.h>
928#elif defined(_WIN32)
929# include <imagehlp.h>
930# ifndef SYMOPT_DEBUG
931# define SYMOPT_DEBUG 0x80000000
932# endif
933# ifndef MAX_SYM_NAME
934# define MAX_SYM_NAME 2000
935typedef struct {
936 DWORD64 Offset;
937 WORD Segment;
938 ADDRESS_MODE Mode;
939} ADDRESS64;
940typedef struct {
941 DWORD64 Thread;
942 DWORD ThCallbackStack;
943 DWORD ThCallbackBStore;
944 DWORD NextCallback;
945 DWORD FramePointer;
946 DWORD64 KiCallUserMode;
947 DWORD64 KeUserCallbackDispatcher;
948 DWORD64 SystemRangeStart;
949 DWORD64 KiUserExceptionDispatcher;
950 DWORD64 StackBase;
951 DWORD64 StackLimit;
952 DWORD64 Reserved[5];
953} KDHELP64;
954typedef struct {
955 ADDRESS64 AddrPC;
956 ADDRESS64 AddrReturn;
957 ADDRESS64 AddrFrame;
958 ADDRESS64 AddrStack;
959 ADDRESS64 AddrBStore;
960 void *FuncTableEntry;
961 DWORD64 Params[4];
962 BOOL Far;
963 BOOL Virtual;
964 DWORD64 Reserved[3];
965 KDHELP64 KdHelp;
966} STACKFRAME64;
967typedef struct {
968 ULONG SizeOfStruct;
969 ULONG TypeIndex;
970 ULONG64 Reserved[2];
971 ULONG Index;
972 ULONG Size;
973 ULONG64 ModBase;
974 ULONG Flags;
975 ULONG64 Value;
976 ULONG64 Address;
977 ULONG Register;
978 ULONG Scope;
979 ULONG Tag;
980 ULONG NameLen;
981 ULONG MaxNameLen;
982 char Name[1];
983} SYMBOL_INFO;
984typedef struct {
985 DWORD SizeOfStruct;
986 void *Key;
987 DWORD LineNumber;
988 char *FileName;
989 DWORD64 Address;
990} IMAGEHLP_LINE64;
991typedef void *PREAD_PROCESS_MEMORY_ROUTINE64;
992typedef void *PFUNCTION_TABLE_ACCESS_ROUTINE64;
993typedef void *PGET_MODULE_BASE_ROUTINE64;
994typedef void *PTRANSLATE_ADDRESS_ROUTINE64;
995# endif
996
997struct dump_thead_arg {
998 DWORD tid;
999 FILE *errout;
1000};
1001
1002static void
1003dump_thread(void *arg)
1004{
1005 HANDLE dbghelp;
1006 BOOL (WINAPI *pSymInitialize)(HANDLE, const char *, BOOL);
1007 BOOL (WINAPI *pSymCleanup)(HANDLE);
1008 BOOL (WINAPI *pStackWalk64)(DWORD, HANDLE, HANDLE, STACKFRAME64 *, void *, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64);
1009 DWORD64 (WINAPI *pSymGetModuleBase64)(HANDLE, DWORD64);
1010 BOOL (WINAPI *pSymFromAddr)(HANDLE, DWORD64, DWORD64 *, SYMBOL_INFO *);
1011 BOOL (WINAPI *pSymGetLineFromAddr64)(HANDLE, DWORD64, DWORD *, IMAGEHLP_LINE64 *);
1012 HANDLE (WINAPI *pOpenThread)(DWORD, BOOL, DWORD);
1013 DWORD tid = ((struct dump_thead_arg *)arg)->tid;
1014 FILE *errout = ((struct dump_thead_arg *)arg)->errout;
1015 HANDLE ph;
1016 HANDLE th;
1017
1018 dbghelp = LoadLibrary("dbghelp.dll");
1019 if (!dbghelp) return;
1020 pSymInitialize = (BOOL (WINAPI *)(HANDLE, const char *, BOOL))GetProcAddress(dbghelp, "SymInitialize");
1021 pSymCleanup = (BOOL (WINAPI *)(HANDLE))GetProcAddress(dbghelp, "SymCleanup");
1022 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");
1023 pSymGetModuleBase64 = (DWORD64 (WINAPI *)(HANDLE, DWORD64))GetProcAddress(dbghelp, "SymGetModuleBase64");
1024 pSymFromAddr = (BOOL (WINAPI *)(HANDLE, DWORD64, DWORD64 *, SYMBOL_INFO *))GetProcAddress(dbghelp, "SymFromAddr");
1025 pSymGetLineFromAddr64 = (BOOL (WINAPI *)(HANDLE, DWORD64, DWORD *, IMAGEHLP_LINE64 *))GetProcAddress(dbghelp, "SymGetLineFromAddr64");
1026 pOpenThread = (HANDLE (WINAPI *)(DWORD, BOOL, DWORD))GetProcAddress(GetModuleHandle("kernel32.dll"), "OpenThread");
1027 if (pSymInitialize && pSymCleanup && pStackWalk64 && pSymGetModuleBase64 &&
1028 pSymFromAddr && pSymGetLineFromAddr64 && pOpenThread) {
1029 SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_DEBUG | SYMOPT_LOAD_LINES);
1030 ph = GetCurrentProcess();
1031 pSymInitialize(ph, NULL, TRUE);
1032 th = pOpenThread(THREAD_SUSPEND_RESUME|THREAD_GET_CONTEXT, FALSE, tid);
1033 if (th) {
1034 if (SuspendThread(th) != (DWORD)-1) {
1035 CONTEXT context;
1036 memset(&context, 0, sizeof(context));
1037 context.ContextFlags = CONTEXT_FULL;
1038 if (GetThreadContext(th, &context)) {
1039 char libpath[MAX_PATH];
1040 char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1041 SYMBOL_INFO *info = (SYMBOL_INFO *)buf;
1042 DWORD mac;
1043 STACKFRAME64 frame;
1044 memset(&frame, 0, sizeof(frame));
1045#if defined(_M_AMD64) || defined(__x86_64__)
1046 mac = IMAGE_FILE_MACHINE_AMD64;
1047 frame.AddrPC.Mode = AddrModeFlat;
1048 frame.AddrPC.Offset = context.Rip;
1049 frame.AddrFrame.Mode = AddrModeFlat;
1050 frame.AddrFrame.Offset = context.Rbp;
1051 frame.AddrStack.Mode = AddrModeFlat;
1052 frame.AddrStack.Offset = context.Rsp;
1053#elif defined(_M_ARM64) || defined(__aarch64__)
1054 mac = IMAGE_FILE_MACHINE_ARM64;
1055 frame.AddrPC.Mode = AddrModeFlat;
1056 frame.AddrPC.Offset = context.Pc;
1057 frame.AddrFrame.Mode = AddrModeFlat;
1058 frame.AddrFrame.Offset = context.Fp;
1059 frame.AddrStack.Mode = AddrModeFlat;
1060 frame.AddrStack.Offset = context.Sp;
1061#else /* i386 */
1062 mac = IMAGE_FILE_MACHINE_I386;
1063 frame.AddrPC.Mode = AddrModeFlat;
1064 frame.AddrPC.Offset = context.Eip;
1065 frame.AddrFrame.Mode = AddrModeFlat;
1066 frame.AddrFrame.Offset = context.Ebp;
1067 frame.AddrStack.Mode = AddrModeFlat;
1068 frame.AddrStack.Offset = context.Esp;
1069#endif
1070
1071 while (pStackWalk64(mac, ph, th, &frame, &context, NULL,
1072 NULL, NULL, NULL)) {
1073 DWORD64 addr = frame.AddrPC.Offset;
1074 IMAGEHLP_LINE64 line;
1075 DWORD64 displacement;
1076 DWORD tmp;
1077
1078 if (addr == frame.AddrReturn.Offset || addr == 0 ||
1079 frame.AddrReturn.Offset == 0)
1080 break;
1081
1082 memset(buf, 0, sizeof(buf));
1083 info->SizeOfStruct = sizeof(SYMBOL_INFO);
1084 info->MaxNameLen = MAX_SYM_NAME;
1085 if (pSymFromAddr(ph, addr, &displacement, info)) {
1086 if (GetModuleFileName((HANDLE)(uintptr_t)pSymGetModuleBase64(ph, addr), libpath, sizeof(libpath)))
1087 kprintf("%s", libpath);
1088 kprintf("(%s+0x%"PRI_64_PREFIX"x)",
1089 info->Name, displacement);
1090 }
1091 kprintf(" [0x%p]", (void *)(VALUE)addr);
1092 memset(&line, 0, sizeof(line));
1093 line.SizeOfStruct = sizeof(line);
1094 if (pSymGetLineFromAddr64(ph, addr, &tmp, &line))
1095 kprintf(" %s:%lu", line.FileName, line.LineNumber);
1096 kprintf("\n");
1097 }
1098 }
1099
1100 error:
1101 ResumeThread(th);
1102 }
1103 CloseHandle(th);
1104 }
1105 pSymCleanup(ph);
1106 }
1107 FreeLibrary(dbghelp);
1108}
1109#endif
1110
1111void
1112rb_print_backtrace(FILE *errout)
1113{
1114#if USE_BACKTRACE
1115#define MAX_NATIVE_TRACE 1024
1116 static void *trace[MAX_NATIVE_TRACE];
1117 int n = (int)backtrace(trace, MAX_NATIVE_TRACE);
1118#if (defined(USE_ELF) || defined(HAVE_MACH_O_LOADER_H)) && defined(HAVE_DLADDR) && !defined(__sparc)
1119 rb_dump_backtrace_with_lines(n, trace, errout);
1120#else
1121 char **syms = backtrace_symbols(trace, n);
1122 if (syms) {
1123 int i;
1124 for (i=0; i<n; i++) {
1125 kprintf("%s\n", syms[i]);
1126 }
1127 free(syms);
1128 }
1129 error:
1130 /* ignore errors at writing */;
1131#endif
1132#elif defined(_WIN32)
1133 struct dump_thead_arg arg = {
1134 .tid = GetCurrentThreadId(),
1135 .errout = errout,
1136 };
1137 HANDLE th = (HANDLE)_beginthread(dump_thread, 0, &arg);
1138 if (th != (HANDLE)-1)
1139 WaitForSingleObject(th, INFINITE);
1140#endif
1141}
1142
1143#ifdef HAVE_LIBPROCSTAT
1144struct procstat;
1145struct kinfo_proc;
1146static void procstat_vm(struct procstat *, struct kinfo_proc *, FILE *);
1147#include "missing/procstat_vm.c"
1148#endif
1149
1150#if defined __linux__
1151# if defined(__x86_64__) || defined(__i386__)
1152# define dump_machine_register(reg) (col_count = print_machine_register(errout, mctx->gregs[REG_##reg], #reg, col_count, 80))
1153# elif defined(__aarch64__) || defined(__arm__) || defined(__riscv) || defined(__loongarch64)
1154# define dump_machine_register(reg, regstr) (col_count = print_machine_register(errout, reg, regstr, col_count, 80))
1155# endif
1156#elif defined __APPLE__
1157# if defined(__aarch64__)
1158# define dump_machine_register(reg, regstr) (col_count = print_machine_register(errout, mctx->MCTX_SS_REG(reg), regstr, col_count, 80))
1159# else
1160# define dump_machine_register(reg) (col_count = print_machine_register(errout, mctx->MCTX_SS_REG(reg), #reg, col_count, 80))
1161# endif
1162#endif
1163
1164#ifdef dump_machine_register
1165static int
1166print_machine_register(FILE *errout, size_t reg, const char *reg_name, int col_count, int max_col)
1167{
1168 int ret;
1169 char buf[64];
1170 static const int size_width = sizeof(size_t) * CHAR_BIT / 4;
1171
1172 ret = snprintf(buf, sizeof(buf), " %3.3s: 0x%.*" PRIxSIZE, reg_name, size_width, reg);
1173 if (col_count + ret > max_col) {
1174 kputs("\n");
1175 col_count = 0;
1176 }
1177 col_count += ret;
1178 kputs(buf);
1179 return col_count;
1180
1181 error:
1182 return -1;
1183}
1184
1185static bool
1186rb_dump_machine_register(FILE *errout, const ucontext_t *ctx)
1187{
1188 int col_count = 0;
1189 if (!ctx) return true;
1190
1191 kprintf("-- Machine register context "
1192 "------------------------------------------------\n");
1193
1194# if defined __linux__
1195 {
1196 const mcontext_t *const mctx = &ctx->uc_mcontext;
1197# if defined __x86_64__
1198 dump_machine_register(RIP);
1199 dump_machine_register(RBP);
1200 dump_machine_register(RSP);
1201 dump_machine_register(RAX);
1202 dump_machine_register(RBX);
1203 dump_machine_register(RCX);
1204 dump_machine_register(RDX);
1205 dump_machine_register(RDI);
1206 dump_machine_register(RSI);
1207 dump_machine_register(R8);
1208 dump_machine_register(R9);
1209 dump_machine_register(R10);
1210 dump_machine_register(R11);
1211 dump_machine_register(R12);
1212 dump_machine_register(R13);
1213 dump_machine_register(R14);
1214 dump_machine_register(R15);
1215 dump_machine_register(EFL);
1216# elif defined __i386__
1217 dump_machine_register(GS);
1218 dump_machine_register(FS);
1219 dump_machine_register(ES);
1220 dump_machine_register(DS);
1221 dump_machine_register(EDI);
1222 dump_machine_register(ESI);
1223 dump_machine_register(EBP);
1224 dump_machine_register(ESP);
1225 dump_machine_register(EBX);
1226 dump_machine_register(EDX);
1227 dump_machine_register(ECX);
1228 dump_machine_register(EAX);
1229 dump_machine_register(TRAPNO);
1230 dump_machine_register(ERR);
1231 dump_machine_register(EIP);
1232 dump_machine_register(CS);
1233 dump_machine_register(EFL);
1234 dump_machine_register(UESP);
1235 dump_machine_register(SS);
1236# elif defined __aarch64__
1237 dump_machine_register(mctx->regs[0], "x0");
1238 dump_machine_register(mctx->regs[1], "x1");
1239 dump_machine_register(mctx->regs[2], "x2");
1240 dump_machine_register(mctx->regs[3], "x3");
1241 dump_machine_register(mctx->regs[4], "x4");
1242 dump_machine_register(mctx->regs[5], "x5");
1243 dump_machine_register(mctx->regs[6], "x6");
1244 dump_machine_register(mctx->regs[7], "x7");
1245 dump_machine_register(mctx->regs[18], "x18");
1246 dump_machine_register(mctx->regs[19], "x19");
1247 dump_machine_register(mctx->regs[20], "x20");
1248 dump_machine_register(mctx->regs[21], "x21");
1249 dump_machine_register(mctx->regs[22], "x22");
1250 dump_machine_register(mctx->regs[23], "x23");
1251 dump_machine_register(mctx->regs[24], "x24");
1252 dump_machine_register(mctx->regs[25], "x25");
1253 dump_machine_register(mctx->regs[26], "x26");
1254 dump_machine_register(mctx->regs[27], "x27");
1255 dump_machine_register(mctx->regs[28], "x28");
1256 dump_machine_register(mctx->regs[29], "x29");
1257 dump_machine_register(mctx->sp, "sp");
1258 dump_machine_register(mctx->fault_address, "fault_address");
1259# elif defined __arm__
1260 dump_machine_register(mctx->arm_r0, "r0");
1261 dump_machine_register(mctx->arm_r1, "r1");
1262 dump_machine_register(mctx->arm_r2, "r2");
1263 dump_machine_register(mctx->arm_r3, "r3");
1264 dump_machine_register(mctx->arm_r4, "r4");
1265 dump_machine_register(mctx->arm_r5, "r5");
1266 dump_machine_register(mctx->arm_r6, "r6");
1267 dump_machine_register(mctx->arm_r7, "r7");
1268 dump_machine_register(mctx->arm_r8, "r8");
1269 dump_machine_register(mctx->arm_r9, "r9");
1270 dump_machine_register(mctx->arm_r10, "r10");
1271 dump_machine_register(mctx->arm_sp, "sp");
1272 dump_machine_register(mctx->fault_address, "fault_address");
1273# elif defined __riscv
1274 dump_machine_register(mctx->__gregs[REG_SP], "sp");
1275 dump_machine_register(mctx->__gregs[REG_S0], "s0");
1276 dump_machine_register(mctx->__gregs[REG_S1], "s1");
1277 dump_machine_register(mctx->__gregs[REG_A0], "a0");
1278 dump_machine_register(mctx->__gregs[REG_A0+1], "a1");
1279 dump_machine_register(mctx->__gregs[REG_A0+2], "a2");
1280 dump_machine_register(mctx->__gregs[REG_A0+3], "a3");
1281 dump_machine_register(mctx->__gregs[REG_A0+4], "a4");
1282 dump_machine_register(mctx->__gregs[REG_A0+5], "a5");
1283 dump_machine_register(mctx->__gregs[REG_A0+6], "a6");
1284 dump_machine_register(mctx->__gregs[REG_A0+7], "a7");
1285 dump_machine_register(mctx->__gregs[REG_S2], "s2");
1286 dump_machine_register(mctx->__gregs[REG_S2+1], "s3");
1287 dump_machine_register(mctx->__gregs[REG_S2+2], "s4");
1288 dump_machine_register(mctx->__gregs[REG_S2+3], "s5");
1289 dump_machine_register(mctx->__gregs[REG_S2+4], "s6");
1290 dump_machine_register(mctx->__gregs[REG_S2+5], "s7");
1291 dump_machine_register(mctx->__gregs[REG_S2+6], "s8");
1292 dump_machine_register(mctx->__gregs[REG_S2+7], "s9");
1293 dump_machine_register(mctx->__gregs[REG_S2+8], "s10");
1294 dump_machine_register(mctx->__gregs[REG_S2+9], "s11");
1295# elif defined __loongarch64
1296 dump_machine_register(mctx->__gregs[LARCH_REG_SP], "sp");
1297 dump_machine_register(mctx->__gregs[LARCH_REG_A0], "a0");
1298 dump_machine_register(mctx->__gregs[LARCH_REG_A0+1], "a1");
1299 dump_machine_register(mctx->__gregs[LARCH_REG_A0+2], "a2");
1300 dump_machine_register(mctx->__gregs[LARCH_REG_A0+3], "a3");
1301 dump_machine_register(mctx->__gregs[LARCH_REG_A0+4], "a4");
1302 dump_machine_register(mctx->__gregs[LARCH_REG_A0+5], "a5");
1303 dump_machine_register(mctx->__gregs[LARCH_REG_A0+6], "a6");
1304 dump_machine_register(mctx->__gregs[LARCH_REG_A0+7], "a7");
1305 dump_machine_register(mctx->__gregs[LARCH_REG_A0+8], "fp");
1306 dump_machine_register(mctx->__gregs[LARCH_REG_S0], "s0");
1307 dump_machine_register(mctx->__gregs[LARCH_REG_S1], "s1");
1308 dump_machine_register(mctx->__gregs[LARCH_REG_S2], "s2");
1309 dump_machine_register(mctx->__gregs[LARCH_REG_S0+3], "s3");
1310 dump_machine_register(mctx->__gregs[LARCH_REG_S0+4], "s4");
1311 dump_machine_register(mctx->__gregs[LARCH_REG_S0+5], "s5");
1312 dump_machine_register(mctx->__gregs[LARCH_REG_S0+6], "s6");
1313 dump_machine_register(mctx->__gregs[LARCH_REG_S0+7], "s7");
1314 dump_machine_register(mctx->__gregs[LARCH_REG_S0+8], "s8");
1315# endif
1316 }
1317# elif defined __APPLE__
1318 {
1319 const mcontext_t mctx = ctx->uc_mcontext;
1320# if defined __x86_64__
1321 dump_machine_register(rax);
1322 dump_machine_register(rbx);
1323 dump_machine_register(rcx);
1324 dump_machine_register(rdx);
1325 dump_machine_register(rdi);
1326 dump_machine_register(rsi);
1327 dump_machine_register(rbp);
1328 dump_machine_register(rsp);
1329 dump_machine_register(r8);
1330 dump_machine_register(r9);
1331 dump_machine_register(r10);
1332 dump_machine_register(r11);
1333 dump_machine_register(r12);
1334 dump_machine_register(r13);
1335 dump_machine_register(r14);
1336 dump_machine_register(r15);
1337 dump_machine_register(rip);
1338 dump_machine_register(rflags);
1339# elif defined __i386__
1340 dump_machine_register(eax);
1341 dump_machine_register(ebx);
1342 dump_machine_register(ecx);
1343 dump_machine_register(edx);
1344 dump_machine_register(edi);
1345 dump_machine_register(esi);
1346 dump_machine_register(ebp);
1347 dump_machine_register(esp);
1348 dump_machine_register(ss);
1349 dump_machine_register(eflags);
1350 dump_machine_register(eip);
1351 dump_machine_register(cs);
1352 dump_machine_register(ds);
1353 dump_machine_register(es);
1354 dump_machine_register(fs);
1355 dump_machine_register(gs);
1356# elif defined __aarch64__
1357 dump_machine_register(x[0], "x0");
1358 dump_machine_register(x[1], "x1");
1359 dump_machine_register(x[2], "x2");
1360 dump_machine_register(x[3], "x3");
1361 dump_machine_register(x[4], "x4");
1362 dump_machine_register(x[5], "x5");
1363 dump_machine_register(x[6], "x6");
1364 dump_machine_register(x[7], "x7");
1365 dump_machine_register(x[18], "x18");
1366 dump_machine_register(x[19], "x19");
1367 dump_machine_register(x[20], "x20");
1368 dump_machine_register(x[21], "x21");
1369 dump_machine_register(x[22], "x22");
1370 dump_machine_register(x[23], "x23");
1371 dump_machine_register(x[24], "x24");
1372 dump_machine_register(x[25], "x25");
1373 dump_machine_register(x[26], "x26");
1374 dump_machine_register(x[27], "x27");
1375 dump_machine_register(x[28], "x28");
1376 dump_machine_register(lr, "lr");
1377 dump_machine_register(fp, "fp");
1378 dump_machine_register(sp, "sp");
1379# endif
1380 }
1381# endif
1382 kprintf("\n\n");
1383 return true;
1384
1385 error:
1386 return false;
1387}
1388#else
1389# define rb_dump_machine_register(errout, ctx) ((void)0)
1390#endif /* dump_machine_register */
1391
1392bool
1393rb_vm_bugreport(const void *ctx, FILE *errout)
1394{
1395 const char *box_env = getenv("RUBY_BUGREPORT_BOX_ENV");
1396 const char *cmd = getenv("RUBY_ON_BUG");
1397 if (cmd) {
1398 char buf[0x100];
1399 snprintf(buf, sizeof(buf), "%s %"PRI_PIDT_PREFIX"d", cmd, getpid());
1400 int r = system(buf);
1401 if (r == -1) {
1402 snprintf(buf, sizeof(buf), "Launching RUBY_ON_BUG command failed.");
1403 }
1404 }
1405
1406 // Thread unsafe best effort attempt to stop printing the bug report in an
1407 // infinite loop. Can happen with corrupt Ruby stack.
1408 {
1409 static bool crashing = false;
1410 if (crashing) {
1411 kprintf("Crashed while printing bug report\n");
1412 return true;
1413 }
1414 crashing = true;
1415 }
1416
1417#ifdef __linux__
1418# define PROC_MAPS_NAME "/proc/self/maps"
1419#endif
1420#ifdef PROC_MAPS_NAME
1421 enum {other_runtime_info = 1};
1422#else
1423 enum {other_runtime_info = 0};
1424#endif
1425 const rb_vm_t *const vm = GET_VM();
1426 const rb_execution_context_t *ec = rb_current_execution_context(false);
1427 rb_box_t *current_box = NULL;
1428 VALUE loaded_features = 0;
1429 if (ec) {
1430 current_box = (rb_box_t*)rb_current_box_in_crash_report();
1431 }
1432 else {
1433 current_box = (rb_box_t*)rb_main_box();
1434 if (!current_box) current_box = (rb_box_t*)rb_root_box();
1435 }
1436
1437 if (current_box) {
1438 loaded_features = current_box->loaded_features;
1439 }
1440
1441 if (vm && ec) {
1442 rb_vmdebug_stack_dump_raw(ec, ec->cfp, errout);
1443 if (box_env) {
1444 rb_vmdebug_box_env_dump_raw(ec, ec->cfp, errout);
1445 }
1446 rb_backtrace_print_as_bugreport(errout);
1447 kputs("\n");
1448 // If we get here, hopefully things are intact enough that
1449 // we can read these two numbers. It is an estimate because
1450 // we are reading without synchronization.
1451 kprintf("-- Threading information "
1452 "---------------------------------------------------\n");
1453 kprintf("Total ractor count: %u\n", vm->ractor.cnt);
1454 const rb_ractor_t *cr = rb_ec_ractor_ptr(ec);
1455 if (cr) {
1456 kprintf("Ruby thread count for this ractor: %u\n", cr->threads.cnt);
1457 }
1458 if (ec->thread_ptr && ec->thread_ptr->scheduler != Qnil) {
1459 kprintf("Note that the Fiber scheduler is enabled\n");
1460 }
1461 kputs("\n");
1462 }
1463 else {
1464 /* No Ruby level information is available: there is no current execution
1465 * context, or the VM is not ready. State it explicitly instead of
1466 * silently jumping to the machine register context. */
1467 kprintf("-- Control frame information "
1468 "-----------------------------------------------\n");
1469 if (!vm) {
1470 kprintf(" The VM is not available.\n");
1471 }
1472 else {
1473 kprintf(" No Ruby execution context on the current thread.\n");
1474 }
1475 kputs("\n");
1476 }
1477
1478 rb_dump_machine_register(errout, ctx);
1479
1480#if USE_BACKTRACE || defined(_WIN32)
1481 kprintf("-- C level backtrace information "
1482 "-------------------------------------------\n");
1483 rb_print_backtrace(errout);
1484
1485
1486 kprintf("\n");
1487#endif /* USE_BACKTRACE */
1488
1489 if (other_runtime_info || vm) {
1490 kprintf("-- Other runtime information "
1491 "-----------------------------------------------\n\n");
1492 }
1493 if (vm && !rb_during_gc()) {
1494 int i;
1495 VALUE name;
1496 long len;
1497 const int max_name_length = 1024;
1498# define LIMITED_NAME_LENGTH(s) \
1499 (((len = RSTRING_LEN(s)) > max_name_length) ? max_name_length : (int)len)
1500
1501 name = vm->progname;
1502 if (name) {
1503 kprintf("* Loaded script: %.*s\n",
1504 LIMITED_NAME_LENGTH(name), RSTRING_PTR(name));
1505 kprintf("\n");
1506 }
1507 if (rb_box_available()) {
1508 kprintf("* Ruby Box: enabled\n");
1509 if (current_box) {
1510 kprintf("* Current box id: %ld, type: %s\n",
1511 current_box->box_id,
1512 BOX_USER_P(current_box) ? (BOX_MAIN_P(current_box) ? "main" : "user") : "root");
1513 }
1514 else {
1515 kprintf("* Current box: NULL (crashed)\n");
1516 }
1517 }
1518 else {
1519 kprintf("* Ruby Box: disabled\n");
1520 }
1521 if (loaded_features) {
1522 kprintf("* Loaded features:\n\n");
1523 for (i=0; i<RARRAY_LEN(loaded_features); i++) {
1524 name = RARRAY_AREF(loaded_features, i);
1525 if (RB_TYPE_P(name, T_STRING)) {
1526 kprintf(" %4d %.*s\n", i,
1527 LIMITED_NAME_LENGTH(name), RSTRING_PTR(name));
1528 }
1529 else if (RB_TYPE_P(name, T_CLASS) || RB_TYPE_P(name, T_MODULE)) {
1530 const char *const type = RB_TYPE_P(name, T_CLASS) ?
1531 "class" : "module";
1532 name = rb_search_class_path(rb_class_real(name));
1533 if (!RB_TYPE_P(name, T_STRING)) {
1534 kprintf(" %4d %s:<unnamed>\n", i, type);
1535 continue;
1536 }
1537 kprintf(" %4d %s:%.*s\n", i, type,
1538 LIMITED_NAME_LENGTH(name), RSTRING_PTR(name));
1539 }
1540 else {
1541 VALUE klass = rb_search_class_path(rb_obj_class(name));
1542 if (!RB_TYPE_P(klass, T_STRING)) {
1543 kprintf(" %4d #<%p:%p>\n", i,
1544 (void *)CLASS_OF(name), (void *)name);
1545 continue;
1546 }
1547 kprintf(" %4d #<%.*s:%p>\n", i,
1548 LIMITED_NAME_LENGTH(klass), RSTRING_PTR(klass),
1549 (void *)name);
1550 }
1551 }
1552 }
1553 kprintf("\n");
1554 }
1555
1556 {
1557#if !defined(RUBY_ASAN_ENABLED) && !USE_MODULAR_GC
1558# ifdef PROC_MAPS_NAME
1559 {
1560 FILE *fp = fopen(PROC_MAPS_NAME, "r");
1561 if (fp) {
1562 kprintf("* Process memory map:\n\n");
1563
1564 while (!feof(fp)) {
1565 char buff[0x100];
1566 size_t rn = fread(buff, 1, 0x100, fp);
1567 if (fwrite(buff, 1, rn, errout) != rn)
1568 break;
1569 }
1570
1571 fclose(fp);
1572 kprintf("\n\n");
1573 }
1574 }
1575# endif /* __linux__ */
1576# ifdef HAVE_LIBPROCSTAT
1577# define MIB_KERN_PROC_PID_LEN 4
1578 int mib[MIB_KERN_PROC_PID_LEN];
1579 struct kinfo_proc kp;
1580 size_t len = sizeof(struct kinfo_proc);
1581 mib[0] = CTL_KERN;
1582 mib[1] = KERN_PROC;
1583 mib[2] = KERN_PROC_PID;
1584 mib[3] = getpid();
1585 if (sysctl(mib, MIB_KERN_PROC_PID_LEN, &kp, &len, NULL, 0) == -1) {
1586 kprintf("sysctl: %s\n", strerror(errno));
1587 }
1588 else {
1589 struct procstat *prstat = procstat_open_sysctl();
1590 kprintf("* Process memory map:\n\n");
1591 procstat_vm(prstat, &kp, errout);
1592 procstat_close(prstat);
1593 kprintf("\n");
1594 }
1595# endif /* __FreeBSD__ */
1596# ifdef __APPLE__
1597 vm_address_t addr = 0;
1598 vm_size_t size = 0;
1599 struct vm_region_submap_info map;
1600 mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT;
1601 natural_t depth = 0;
1602
1603 kprintf("* Process memory map:\n\n");
1604 while (1) {
1605 if (vm_region_recurse(mach_task_self(), &addr, &size, &depth,
1606 (vm_region_recurse_info_t)&map, &count) != KERN_SUCCESS) {
1607 break;
1608 }
1609
1610 if (map.is_submap) {
1611 // We only look at main addresses
1612 depth++;
1613 }
1614 else {
1615 kprintf("%lx-%lx %s%s%s", addr, (addr+size),
1616 ((map.protection & VM_PROT_READ) != 0 ? "r" : "-"),
1617 ((map.protection & VM_PROT_WRITE) != 0 ? "w" : "-"),
1618 ((map.protection & VM_PROT_EXECUTE) != 0 ? "x" : "-"));
1619# ifdef HAVE_LIBPROC_H
1620 char buff[PATH_MAX];
1621 if (proc_regionfilename(getpid(), addr, buff, sizeof(buff)) > 0) {
1622 kprintf(" %s", buff);
1623 }
1624# endif
1625 kprintf("\n");
1626 }
1627
1628 addr += size;
1629 size = 0;
1630 }
1631# endif
1632#endif
1633 }
1634 return true;
1635
1636 error:
1637 return false;
1638}
1639
1640bool
1641rb_vmdebug_stack_dump_all_threads(void)
1642{
1643 rb_thread_t *th = NULL;
1644 rb_ractor_t *r = GET_RACTOR();
1645 FILE *errout = stderr;
1646
1647 // TODO: now it only shows current ractor
1648 ccan_list_for_each(&r->threads.set, th, lt_node) {
1649#ifdef NON_SCALAR_THREAD_ID
1650 kprintf("th: %p, native_id: N/A\n", th);
1651#else
1652 kprintf("th: %p, native_id: %p\n", (void *)th, (void *)(uintptr_t)th->nt->thread_id);
1653#endif
1654 if (!rb_vmdebug_stack_dump_raw(th->ec, th->ec->cfp, errout)) goto error;
1655 }
1656 return true;
1657
1658 error:
1659 return false;
1660}
#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
Scheduler APIs.
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
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