Ruby 4.1.0dev (2026-12-01 revision afadaed84ccb23517ffb57fd15f116f2e4a85917)
vm_backtrace.c (afadaed84ccb23517ffb57fd15f116f2e4a85917)
1/**********************************************************************
2
3 vm_backtrace.c -
4
5 $Author: ko1 $
6 created at: Sun Jun 03 00:14:20 2012
7
8 Copyright (C) 1993-2012 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "eval_intern.h"
13#include "internal.h"
14#include "internal/class.h"
15#include "internal/error.h"
16#include "internal/object.h"
17#include "internal/proc.h"
18#include "internal/ruby_parser.h"
19#include "internal/vm.h"
20#include "iseq.h"
21#include "prism_compile.h"
22#include "ruby/debug.h"
23#include "ruby/encoding.h"
25#include "vm_core.h"
26#include "zjit.h"
27
28static VALUE rb_cBacktrace;
29static VALUE rb_cBacktraceLocation;
30
31static VALUE
32id2str(ID id)
33{
34 VALUE str = rb_id2str(id);
35 if (!str) return Qnil;
36 return str;
37}
38#define rb_id2str(id) id2str(id)
39
40inline static int
41calc_pos(const rb_iseq_t *iseq, const VALUE *pc, int *lineno, int *node_id)
42{
43 VM_ASSERT(iseq);
44
45 if (pc == NULL) {
46 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_TOP) {
47 VM_ASSERT(! ISEQ_BODY(iseq)->local_table);
48 VM_ASSERT(! ISEQ_BODY(iseq)->local_table_size);
49 return 0;
50 }
51 if (lineno) *lineno = ISEQ_BODY(iseq)->location.first_lineno;
52 if (node_id) *node_id = ISEQ_BODY(iseq)->location.node_id;
53 return 1;
54 }
55 else {
56 VM_ASSERT(ISEQ_BODY(iseq));
57 VM_ASSERT(ISEQ_BODY(iseq)->iseq_encoded);
58 VM_ASSERT(ISEQ_BODY(iseq)->iseq_size);
59
60 ptrdiff_t n = pc - ISEQ_BODY(iseq)->iseq_encoded;
61 VM_ASSERT(n >= 0);
62#if SIZEOF_PTRDIFF_T > SIZEOF_INT
63 VM_ASSERT(n <= (ptrdiff_t)UINT_MAX);
64#endif
65 VM_ASSERT((unsigned int)n <= ISEQ_BODY(iseq)->iseq_size);
66 ASSUME(n >= 0);
67 size_t pos = n; /* no overflow */
68 if (LIKELY(pos)) {
69 /* use pos-1 because PC points next instruction at the beginning of instruction */
70 pos--;
71 }
72#if VMDEBUG && defined(HAVE_BUILTIN___BUILTIN_TRAP)
73 else {
74 /* SDR() is not possible; that causes infinite loop. */
75 rb_print_backtrace(stderr);
76 __builtin_trap();
77 }
78#endif
79 if (lineno) *lineno = rb_iseq_line_no(iseq, pos);
80 if (node_id) *node_id = rb_iseq_node_id(iseq, pos);
81 return 1;
82 }
83}
84
85inline static int
86calc_lineno(const rb_iseq_t *iseq, const VALUE *pc)
87{
88 int lineno;
89 if (calc_pos(iseq, pc, &lineno, NULL)) return lineno;
90 return 0;
91}
92
93inline static int
94calc_node_id(const rb_iseq_t *iseq, const VALUE *pc)
95{
96 int node_id;
97 if (calc_pos(iseq, pc, NULL, &node_id)) return node_id;
98 return -1;
99}
100
101int
102rb_vm_get_sourceline(const rb_control_frame_t *cfp)
103{
104 if (VM_FRAME_RUBYFRAME_P(cfp) && CFP_ISEQ(cfp)) {
105 const rb_iseq_t *iseq = CFP_ISEQ(cfp);
106 int line = calc_lineno(iseq, CFP_PC(cfp));
107 if (line != 0) {
108 return line;
109 }
110 else {
111 return ISEQ_BODY(iseq)->location.first_lineno;
112 }
113 }
114 else {
115 return 0;
116 }
117}
118
120 const rb_callable_method_entry_t *cme;
121 const rb_iseq_t *iseq;
122 const VALUE *pc;
123} rb_backtrace_location_t;
124
126 rb_backtrace_location_t *loc;
127 VALUE btobj;
128};
129
130static void
131location_mark(void *ptr)
132{
133 struct valued_frame_info *vfi = (struct valued_frame_info *)ptr;
134 rb_gc_mark_movable(vfi->btobj);
135}
136
137static void
138location_ref_update(void *ptr)
139{
140 struct valued_frame_info *vfi = ptr;
141 rb_gc_update_moved(&vfi->btobj);
142}
143
144static void
145location_mark_entry(rb_backtrace_location_t *fi)
146{
147 rb_gc_mark((VALUE)fi->cme);
148 if (fi->iseq) rb_gc_mark_movable((VALUE)fi->iseq);
149}
150
151static const rb_data_type_t location_data_type = {
152 "frame_info",
153 {
154 location_mark,
156 NULL, // No external memory to report,
157 location_ref_update,
158 },
159 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
160};
161
162int
163rb_frame_info_p(VALUE obj)
164{
165 return rb_typeddata_is_kind_of(obj, &location_data_type);
166}
167
168static inline rb_backtrace_location_t *
169location_ptr(VALUE locobj)
170{
171 struct valued_frame_info *vloc;
172 TypedData_Get_Struct(locobj, struct valued_frame_info, &location_data_type, vloc);
173 return vloc->loc;
174}
175
176static int
177location_lineno(rb_backtrace_location_t *loc)
178{
179 if (loc->iseq) {
180 return calc_lineno(loc->iseq, loc->pc);
181 }
182 return 0;
183}
184
185/*
186 * Returns the line number of this frame.
187 *
188 * For example, using +caller_locations.rb+ from Thread::Backtrace::Location
189 *
190 * loc = c(0..1).first
191 * loc.lineno #=> 2
192 */
193static VALUE
194location_lineno_m(VALUE self)
195{
196 return INT2FIX(location_lineno(location_ptr(self)));
197}
198
199VALUE rb_mod_name0(VALUE klass, bool *permanent);
200
201VALUE
202rb_gen_method_name(VALUE owner, VALUE name)
203{
204 bool permanent;
205 if (RB_TYPE_P(owner, T_CLASS) || RB_TYPE_P(owner, T_MODULE)) {
206 if (RCLASS_SINGLETON_P(owner)) {
207 VALUE v = RCLASS_ATTACHED_OBJECT(owner);
208 if (RB_TYPE_P(v, T_CLASS) || RB_TYPE_P(v, T_MODULE)) {
209 v = rb_mod_name0(v, &permanent);
210 if (permanent && !NIL_P(v)) {
211 return rb_sprintf("%"PRIsVALUE".%"PRIsVALUE, v, name);
212 }
213 }
214 }
215 else {
216 owner = rb_mod_name0(owner, &permanent);
217 if (permanent && !NIL_P(owner)) {
218 return rb_sprintf("%"PRIsVALUE"#%"PRIsVALUE, owner, name);
219 }
220 }
221 }
222 return name;
223}
224
225static VALUE
226calculate_iseq_label(VALUE owner, const rb_iseq_t *iseq)
227{
228retry:
229 switch (ISEQ_BODY(iseq)->type) {
230 case ISEQ_TYPE_TOP:
231 case ISEQ_TYPE_CLASS:
232 case ISEQ_TYPE_MAIN:
233 return ISEQ_BODY(iseq)->location.label;
234 case ISEQ_TYPE_METHOD:
235 return rb_gen_method_name(owner, ISEQ_BODY(iseq)->location.label);
236 case ISEQ_TYPE_BLOCK:
237 case ISEQ_TYPE_PLAIN: {
238 int level = 0;
239 const rb_iseq_t *orig_iseq = iseq;
240 if (ISEQ_BODY(orig_iseq)->parent_iseq != 0) {
241 while (ISEQ_BODY(orig_iseq)->local_iseq != iseq) {
242 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_BLOCK) {
243 level++;
244 }
245 iseq = ISEQ_BODY(iseq)->parent_iseq;
246 }
247 }
248 if (level <= 1) {
249 return rb_sprintf("block in %"PRIsVALUE, calculate_iseq_label(owner, iseq));
250 }
251 else {
252 return rb_sprintf("block (%d levels) in %"PRIsVALUE, level, calculate_iseq_label(owner, iseq));
253 }
254 }
255 case ISEQ_TYPE_RESCUE:
256 case ISEQ_TYPE_ENSURE:
257 case ISEQ_TYPE_EVAL:
258 iseq = ISEQ_BODY(iseq)->parent_iseq;
259 goto retry;
260 default:
261 rb_bug("calculate_iseq_label: unreachable");
262 }
263}
264
265static bool
266is_internal_location(const rb_iseq_t *iseq)
267{
268 static const char prefix[] = "<internal:";
269 const size_t prefix_len = sizeof(prefix) - 1;
270 VALUE file = rb_iseq_path(iseq);
271 return strncmp(prefix, RSTRING_PTR(file), prefix_len) == 0;
272}
273
274// Return true if a given location is a C method or supposed to behave like one.
275static inline bool
276location_cfunc_p(rb_backtrace_location_t *loc)
277{
278 if (!loc->cme) return false;
279
280 switch (loc->cme->def->type) {
281 case VM_METHOD_TYPE_CFUNC:
282 return true;
283 case VM_METHOD_TYPE_ISEQ:
284 return is_internal_location(loc->cme->def->body.iseq.iseqptr);
285 default:
286 return false;
287 }
288}
289
290/* Return the module where the running method body was actually defined.
291 *
292 * For an alias or a method installed via define_method(UnboundMethod), the CME's
293 * owner points at the site where the alias/copy was installed, not where the body
294 * was originally defined. Combined with the method name (taken from the original
295 * definition) that yields a "Class#method" pair which never existed -- e.g. an
296 * alias in a subclass reported as Child#original instead of Parent#original, or
297 * define_method(Original.instance_method(:m)) reported as A#m instead of
298 * Original#m ([Bug #22197]).
299 *
300 * The definition module is recorded once on the (reference-counted, shared)
301 * method definition when the body is first created, so every alias/define_method
302 * copy keeps pointing at the original module.
303 *
304 * The exception is module_function, which installs the instance method's *shared*
305 * def onto the module's singleton class as well: that copy must be labeled as a
306 * class method of the module (M.f), i.e. by its owner. Such a copy is exactly the
307 * one whose owner is the singleton class of the definition module. */
308static VALUE
309location_original_module(const rb_callable_method_entry_t *cme)
310{
311 if (!cme || !cme->def) return Qnil;
312 VALUE owner = cme->owner;
313 VALUE defined_in = cme->def->original_module;
314 if (!defined_in) return owner;
315 if (defined_in != owner &&
316 RB_TYPE_P(owner, T_CLASS) && RCLASS_SINGLETON_P(owner) &&
317 RCLASS_ATTACHED_OBJECT(owner) == defined_in) {
318 return owner;
319 }
320 return defined_in;
321}
322
323static VALUE
324location_label(rb_backtrace_location_t *loc)
325{
326 if (location_cfunc_p(loc)) {
327 return rb_gen_method_name(location_original_module(loc->cme), rb_id2str(loc->cme->def->original_id));
328 }
329 else {
330 return calculate_iseq_label(location_original_module(loc->cme), loc->iseq);
331 }
332}
333/*
334 * Returns the label of this frame.
335 *
336 * Usually consists of method, class, module, etc names with decoration.
337 *
338 * Consider the following example:
339 *
340 * def foo
341 * puts caller_locations(0).first.label
342 *
343 * 1.times do
344 * puts caller_locations(0).first.label
345 *
346 * 1.times do
347 * puts caller_locations(0).first.label
348 * end
349 * end
350 * end
351 *
352 * The result of calling +foo+ is this:
353 *
354 * foo
355 * block in foo
356 * block (2 levels) in foo
357 *
358 */
359static VALUE
360location_label_m(VALUE self)
361{
362 return location_label(location_ptr(self));
363}
364
365static VALUE
366location_base_label(rb_backtrace_location_t *loc)
367{
368 if (location_cfunc_p(loc)) {
369 return rb_id2str(loc->cme->def->original_id);
370 }
371
372 return rb_iseq_base_label(loc->iseq);
373}
374
375/*
376 * Returns the base label of this frame, which is usually equal to the label,
377 * without decoration.
378 *
379 * Consider the following example:
380 *
381 * def foo
382 * puts caller_locations(0).first.base_label
383 *
384 * 1.times do
385 * puts caller_locations(0).first.base_label
386 *
387 * 1.times do
388 * puts caller_locations(0).first.base_label
389 * end
390 * end
391 * end
392 *
393 * The result of calling +foo+ is this:
394 *
395 * foo
396 * foo
397 * foo
398 */
399static VALUE
400location_base_label_m(VALUE self)
401{
402 return location_base_label(location_ptr(self));
403}
404
405static const rb_iseq_t *
406location_iseq(rb_backtrace_location_t *loc)
407{
408 return loc->iseq;
409}
410
411/*
412 * Returns the file name of this frame. This will generally be an absolute
413 * path, unless the frame is in the main script, in which case it will be the
414 * script location passed on the command line.
415 *
416 * For example, using +caller_locations.rb+ from Thread::Backtrace::Location
417 *
418 * loc = c(0..1).first
419 * loc.path #=> caller_locations.rb
420 */
421static VALUE
422location_path_m(VALUE self)
423{
424 const rb_iseq_t *iseq = location_iseq(location_ptr(self));
425 return iseq ? rb_iseq_path(iseq) : Qnil;
426}
427
428static int
429location_node_id(rb_backtrace_location_t *loc)
430{
431 if (loc->iseq) {
432 return calc_node_id(loc->iseq, loc->pc);
433 }
434 return -1;
435}
436
437extern VALUE rb_e_script;
438
439static bool
440location_source_end_marker_p(const uint8_t *line, size_t length)
441{
442 return (length == 7 && memcmp(line, "__END__", 7) == 0) ||
443 (length == 8 && memcmp(line, "__END__\n", 8) == 0) ||
444 (length == 9 && memcmp(line, "__END__\r\n", 9) == 0);
445}
446
447static bool
448location_source_hash_matches(VALUE source, uint64_t source_hash)
449{
450 StringValue(source);
451 const uint8_t *bytes = (const uint8_t *)RSTRING_PTR(source);
452 size_t length = (size_t)RSTRING_LEN(source);
453 size_t line_start = 0;
454 rb_source_hash_state_t state;
455 rb_source_hash_init(&state);
456
457 for (size_t index = 0; index < length; index++) {
458 if (bytes[index] != '\n') continue;
459
460 size_t line_length = index + 1 - line_start;
461 rb_source_hash_update(&state, bytes + line_start, line_length);
462 if (location_source_end_marker_p(bytes + line_start, line_length) &&
463 rb_source_hash_finalize(&state) == source_hash) {
464 return true;
465 }
466 line_start = index + 1;
467 }
468
469 if (line_start < length) {
470 size_t line_length = length - line_start;
471 rb_source_hash_update(&state, bytes + line_start, line_length);
472 if (location_source_end_marker_p(bytes + line_start, line_length) &&
473 rb_source_hash_finalize(&state) == source_hash) {
474 return true;
475 }
476 }
477
478 return rb_source_hash_finalize(&state) == source_hash;
479}
480
481static VALUE
482location_source_read(VALUE io)
483{
484 VALUE source = rb_str_buf_new(0);
485 VALUE line;
486
487 while (!NIL_P(line = rb_io_gets(io))) {
488 rb_str_buf_append(source, line);
489 }
490 return source;
491}
492
493static VALUE
494location_source_read_file(VALUE path)
495{
496 VALUE file = rb_file_open_str(path, "rb");
497 return rb_ensure(location_source_read, file, rb_io_close, file);
498}
499
500static bool
501location_code_location_equal(const rb_code_location_t *left, const rb_code_location_t *right)
502{
503 return left->beg_pos.lineno == right->beg_pos.lineno &&
504 left->beg_pos.column == right->beg_pos.column &&
505 left->end_pos.lineno == right->end_pos.lineno &&
506 left->end_pos.column == right->end_pos.column;
507}
508
509static bool
510iseq_from_e_script_p(const rb_iseq_t *iseq, VALUE path, uint64_t source_hash)
511{
512 if (!RB_TYPE_P(path, T_STRING) ||
513 RSTRING_LEN(path) != 2 ||
514 memcmp(RSTRING_PTR(path), "-e", 2) != 0 ||
515 !RTEST(rb_e_script)) {
516 return false;
517 }
518 bool matches = ISEQ_BODY(iseq)->prism ?
519 pm_source_hash_matches(rb_e_script, path, source_hash) :
520 location_source_hash_matches(rb_e_script, source_hash);
521 if (!matches) return false;
522
523 const rb_iseq_t *source_iseq = iseq;
524 for (; source_iseq; source_iseq = ISEQ_BODY(source_iseq)->parent_iseq) {
525 if (ISEQ_BODY(source_iseq)->type == ISEQ_TYPE_EVAL) return false;
526 if (ISEQ_BODY(source_iseq)->type == ISEQ_TYPE_MAIN) return true;
527 }
528
529 int node_id = ISEQ_BODY(iseq)->location.node_id;
530 if (node_id == -1) return false;
531
532 rb_code_location_t source_location;
533 bool found;
534 if (ISEQ_BODY(iseq)->prism) {
535 found = pm_node_source_location(rb_e_script, path, 1, node_id, source_hash, &source_location);
536 }
537 else {
538 found = rb_ast_node_source_location(
539 rb_e_script,
540 path,
541 1,
542 node_id,
543 ISEQ_BODY(iseq)->type == ISEQ_TYPE_BLOCK,
544 node_id,
545 &source_location
546 );
547 }
548
549 return found && location_code_location_equal(
550 &source_location, &ISEQ_BODY(iseq)->location.code_location);
551}
552
553static int
554location_source_first_lineno(const rb_iseq_t *iseq, VALUE script_lines)
555{
556 const rb_iseq_t *source_iseq = iseq;
557
558 while (ISEQ_BODY(source_iseq)->parent_iseq) {
559 const rb_iseq_t *parent = ISEQ_BODY(source_iseq)->parent_iseq;
560 if (ISEQ_SCRIPT_LINES(parent) != script_lines) break;
561 source_iseq = parent;
562 }
563
564 return ISEQ_BODY(source_iseq)->location.first_lineno;
565}
566
567/*
568 * call-seq:
569 * location.source_range -> Ruby::SourceRange
570 *
571 * Returns the Ruby::SourceRange for the Ruby expression associated with this
572 * backtrace location.
573 *
574 * On CRuby, this method re-reads and re-parses the source file to determine
575 * the range. File errors encountered while reading the source are propagated.
576 * RuntimeError is raised if required source location information is
577 * unavailable, or if the source has changed.
578 *
579 * RubyVM.keep_script_lines = true can be used to retain source files in
580 * memory and avoid re-reading them from the filesystem.
581 *
582 * Locations from eval'd code are only available with
583 * RubyVM.keep_script_lines = true.
584 */
585static VALUE
586location_source_range_m(VALUE self)
587{
588 rb_backtrace_location_t *backtrace_location = location_ptr(self);
589 const rb_iseq_t *iseq = location_iseq(backtrace_location);
590 if (!iseq) {
591 rb_raise(rb_eRuntimeError, "cannot get source range for location without Ruby bytecode");
592 }
593
594 rb_iseq_check(iseq);
595 int node_id = location_node_id(backtrace_location);
596 if (node_id == -1) {
597 rb_raise(rb_eRuntimeError, "cannot get source range for location without a node ID");
598 }
599 if (!ISEQ_BODY(iseq)->source_hash) {
600 rb_raise(rb_eRuntimeError, "cannot get source range because the source hash is unavailable");
601 }
602 uint64_t source_hash = ISEQ_BODY(iseq)->source_hash;
603
604 VALUE path = rb_iseq_path(iseq);
605 VALUE absolute_path = rb_iseq_realpath(iseq);
606 VALUE script_lines = ISEQ_SCRIPT_LINES(iseq);
607 VALUE source;
608 VALUE parser_path = path;
609 int first_lineno = 1;
610
611 if (!NIL_P(script_lines)) {
612 source = rb_ary_join(script_lines, Qnil);
613 first_lineno = location_source_first_lineno(iseq, script_lines);
614 }
615 else if (iseq_from_e_script_p(iseq, path, source_hash)) {
616 source = rb_e_script;
617 }
618 else if (!NIL_P(absolute_path)) {
619 source = location_source_read_file(absolute_path);
620 parser_path = absolute_path;
621 }
622 else {
623 rb_raise(rb_eArgError, "cannot get source range for location in eval");
624 }
625
626 if (NIL_P(parser_path)) {
627 parser_path = rb_str_new_cstr("(eval)");
628 }
629 // Prism hashes the source itself, so for prism-compiled code the source
630 // hash is checked by pm_node_source_location.
631 if (!ISEQ_BODY(iseq)->prism && !location_source_hash_matches(source, source_hash)) {
632 rb_raise(rb_eRuntimeError, "source has been modified");
633 }
634
635 rb_code_location_t code_location;
636 bool found;
637
638 if (ISEQ_BODY(iseq)->prism) {
639 found = pm_node_source_location(
640 source,
641 parser_path,
642 first_lineno,
643 node_id,
644 source_hash,
645 &code_location
646 );
647 }
648 else {
649 found = rb_ast_node_source_location(
650 source,
651 parser_path,
652 first_lineno,
653 node_id,
654 ISEQ_BODY(iseq)->type == ISEQ_TYPE_BLOCK,
655 ISEQ_BODY(iseq)->location.node_id,
656 &code_location
657 );
658 }
659
660 if (!found) {
661 rb_raise(rb_eRuntimeError, "cannot find node ID %d in parsed source", node_id);
662 }
663
664 return rb_source_range_new(path, absolute_path, &code_location);
665}
666
667int
668rb_get_node_id_from_frame_info(VALUE obj)
669{
670 rb_backtrace_location_t *loc = location_ptr(obj);
671 return location_node_id(loc);
672}
673
674const rb_iseq_t *
675rb_get_iseq_from_frame_info(VALUE obj)
676{
677 rb_backtrace_location_t *loc = location_ptr(obj);
678 const rb_iseq_t *iseq = location_iseq(loc);
679 return iseq;
680}
681
682static VALUE
683location_realpath(rb_backtrace_location_t *loc)
684{
685 if (loc->iseq) {
686 return rb_iseq_realpath(loc->iseq);
687 }
688 return Qnil;
689}
690
691/*
692 * Returns the full file path of this frame.
693 *
694 * Same as #path, except that it will return absolute path
695 * even if the frame is in the main script.
696 */
697static VALUE
698location_absolute_path_m(VALUE self)
699{
700 return location_realpath(location_ptr(self));
701}
702
703static VALUE
704location_format(VALUE file, int lineno, VALUE name)
705{
706 VALUE s = rb_enc_sprintf(rb_enc_compatible(file, name), "%"PRIsVALUE, file);
707 if (lineno != 0) {
708 rb_str_catf(s, ":%d", lineno);
709 }
710 rb_str_cat_cstr(s, ":in ");
711 if (NIL_P(name)) {
712 rb_str_cat_cstr(s, "unknown method");
713 }
714 else {
715 rb_str_catf(s, "'%"PRIsVALUE"'", name);
716 }
717 RB_GC_GUARD(name);
718 return s;
719}
720
721static VALUE
722location_to_str(rb_backtrace_location_t *loc)
723{
724 VALUE file, owner = Qnil, name;
725 int lineno;
726
727 if (location_cfunc_p(loc)) {
728 if (loc->iseq && loc->pc) {
729 file = rb_iseq_path(loc->iseq);
730 lineno = calc_lineno(loc->iseq, loc->pc);
731 }
732 else {
733 file = GET_VM()->progname;
734 lineno = 0;
735 }
736 name = rb_gen_method_name(location_original_module(loc->cme), rb_id2str(loc->cme->def->original_id));
737 }
738 else {
739 file = rb_iseq_path(loc->iseq);
740 lineno = calc_lineno(loc->iseq, loc->pc);
741 if (loc->cme) {
742 owner = location_original_module(loc->cme);
743 }
744 name = calculate_iseq_label(owner, loc->iseq);
745 }
746
747 return location_format(file, lineno, name);
748}
749
750/*
751 * Returns a Kernel#caller style string representing this frame.
752 */
753static VALUE
754location_to_str_m(VALUE self)
755{
756 return location_to_str(location_ptr(self));
757}
758
759/*
760 * Returns the same as calling +inspect+ on the string representation of
761 * #to_str
762 */
763static VALUE
764location_inspect_m(VALUE self)
765{
766 return rb_str_inspect(location_to_str(location_ptr(self)));
767}
768
769typedef struct rb_backtrace_struct {
770 int backtrace_size;
771 VALUE strary;
772 VALUE locary;
773 rb_backtrace_location_t backtrace[1];
774} rb_backtrace_t;
775
776static void
777backtrace_mark(void *ptr)
778{
779 rb_backtrace_t *bt = (rb_backtrace_t *)ptr;
780 size_t i, s = bt->backtrace_size;
781
782 for (i=0; i<s; i++) {
783 location_mark_entry(&bt->backtrace[i]);
784 }
785 rb_gc_mark_movable(bt->strary);
786 rb_gc_mark_movable(bt->locary);
787}
788
789static void
790location_update_entry(rb_backtrace_location_t *fi)
791{
792 rb_gc_update_moved_ptr(&fi->cme);
793 if (fi->iseq) {
794 rb_gc_update_moved_ptr(&fi->iseq);
795 }
796}
797
798static void
799backtrace_update(void *ptr)
800{
801 rb_backtrace_t *bt = (rb_backtrace_t *)ptr;
802 size_t i, s = bt->backtrace_size;
803
804 for (i=0; i<s; i++) {
805 location_update_entry(&bt->backtrace[i]);
806 }
807 rb_gc_update_moved(&bt->strary);
808 rb_gc_update_moved(&bt->locary);
809}
810
811static const rb_data_type_t backtrace_data_type = {
812 "backtrace",
813 {
814 backtrace_mark,
816 NULL, // No external memory to report,
817 backtrace_update,
818 },
819 /* Cannot set the RUBY_TYPED_EMBEDDABLE flag because the loc of frame_info
820 * points elements in the backtrace array. This can cause the loc to become
821 * incorrect if this backtrace object is moved by compaction. */
822 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED
823};
824
825int
826rb_backtrace_p(VALUE obj)
827{
828 return rb_typeddata_is_kind_of(obj, &backtrace_data_type);
829}
830
831static VALUE
832backtrace_alloc_capa(rb_len_t num_frames, rb_backtrace_t **backtrace)
833{
834 size_t memsize = offsetof(rb_backtrace_t, backtrace) + num_frames * sizeof(rb_backtrace_location_t);
835 VALUE btobj = rb_data_typed_object_zalloc(rb_cBacktrace, memsize, &backtrace_data_type);
836 TypedData_Get_Struct(btobj, rb_backtrace_t, &backtrace_data_type, *backtrace);
837 return btobj;
838}
839
840/* Duplicate the backtrace so an exception copy carries no raw pointer to the sender's.
841 * A frame only references shareable iseq / method-entry imemos, so duplicating is safe;
842 * the lazily built strings and location array are regenerated on the receiving side. */
843VALUE
844rb_backtrace_dup(VALUE btobj)
845{
846 rb_backtrace_t *src, *dst;
847 TypedData_Get_Struct(btobj, rb_backtrace_t, &backtrace_data_type, src);
848
849 VALUE dupobj = backtrace_alloc_capa(src->backtrace_size, &dst);
850 dst->backtrace_size = src->backtrace_size;
851 MEMCPY(dst->backtrace, src->backtrace, rb_backtrace_location_t, src->backtrace_size);
852 for (int i = 0; i < dst->backtrace_size; i++) {
853 const rb_backtrace_location_t *fi = &dst->backtrace[i];
854 if (fi->cme) RB_OBJ_WRITTEN(dupobj, Qundef, (VALUE)fi->cme);
855 if (fi->iseq) RB_OBJ_WRITTEN(dupobj, Qundef, (VALUE)fi->iseq);
856 }
857 return dupobj;
858}
859
860
861/* Copy a backtrace's frames into an off-heap blob for a Ractor copy courier. A frame
862 * only references shareable iseq / method-entry imemos, so the blob can carry them as
863 * they are. It has no compaction update hook, so rb_backtrace_blob_mark_ctx pins them
864 * (rb_gc_mark_ctx, not _movable) for as long as the message is in flight. */
865void *
866rb_backtrace_blob_dump(VALUE btobj, int *size_out)
867{
868 rb_backtrace_t *bt;
869 TypedData_Get_Struct(btobj, rb_backtrace_t, &backtrace_data_type, bt);
870
871 int size = bt->backtrace_size;
872 *size_out = size;
873 rb_backtrace_location_t *blob = ALLOC_N(rb_backtrace_location_t, size > 0 ? size : 1);
874 MEMCPY(blob, bt->backtrace, rb_backtrace_location_t, size);
875 return blob;
876}
877
878VALUE
879rb_backtrace_blob_load(const void *blob_, int size)
880{
881 const rb_backtrace_location_t *blob = blob_;
882 rb_backtrace_t *dst;
883 VALUE btobj = backtrace_alloc_capa(size, &dst);
884
885 dst->backtrace_size = size;
886 MEMCPY(dst->backtrace, blob, rb_backtrace_location_t, size);
887 for (int i = 0; i < size; i++) {
888 const rb_backtrace_location_t *fi = &dst->backtrace[i];
889 if (fi->cme) RB_OBJ_WRITTEN(btobj, Qundef, (VALUE)fi->cme);
890 if (fi->iseq) RB_OBJ_WRITTEN(btobj, Qundef, (VALUE)fi->iseq);
891 }
892 /* strary / locary stay unset: the receiver rebuilds them lazily. */
893 return btobj;
894}
895
896void
897rb_backtrace_blob_mark_ctx(const struct rb_gc_mark_ctx *ctx, const void *blob_, int size)
898{
899 const rb_backtrace_location_t *blob = blob_;
900 for (int i = 0; i < size; i++) {
901 if (blob[i].cme) rb_gc_mark_ctx(ctx, (VALUE)blob[i].cme);
902 if (blob[i].iseq) rb_gc_mark_ctx(ctx, (VALUE)blob[i].iseq);
903 }
904}
905
906static long
907backtrace_size(const rb_execution_context_t *ec)
908{
909 const rb_control_frame_t *last_cfp = ec->cfp;
910 const rb_control_frame_t *start_cfp = RUBY_VM_END_CONTROL_FRAME(ec);
911
912 if (start_cfp == NULL) {
913 return -1;
914 }
915
916 start_cfp =
917 RUBY_VM_NEXT_CONTROL_FRAME(
918 RUBY_VM_NEXT_CONTROL_FRAME(start_cfp)); /* skip top frames */
919
920 if (start_cfp < last_cfp) {
921 return 0;
922 }
923
924 return start_cfp - last_cfp + 1;
925}
926
927static bool
928is_rescue_or_ensure_frame(const rb_control_frame_t *cfp)
929{
930 enum rb_iseq_type type = ISEQ_BODY(CFP_ISEQ(cfp))->type;
931 return type == ISEQ_TYPE_RESCUE || type == ISEQ_TYPE_ENSURE;
932}
933
934static void
935bt_backpatch_loc(unsigned long backpatch_counter, rb_backtrace_location_t *loc, const rb_iseq_t *iseq, const VALUE *pc)
936{
937 for (; backpatch_counter > 0; backpatch_counter--, loc--) {
938 loc->iseq = iseq;
939 loc->pc = pc;
940 }
941}
942
943static VALUE location_create(rb_backtrace_location_t *srcloc, void *btobj);
944
945static void
946bt_yield_loc(rb_backtrace_location_t *loc, long num_frames, VALUE btobj)
947{
948 for (; num_frames > 0; num_frames--, loc++) {
949 rb_yield(location_create(loc, (void *)btobj));
950 }
951}
952
953static VALUE
954rb_ec_partial_backtrace_object(const rb_execution_context_t *ec, rb_len_t start_frame, rb_len_t num_frames, int* start_too_large, bool skip_internal, bool do_yield)
955{
956 const rb_control_frame_t *cfp = ec->cfp;
957 const rb_control_frame_t *end_cfp = RUBY_VM_END_CONTROL_FRAME(ec);
958 ptrdiff_t size;
959 rb_backtrace_t *bt = NULL;
960 VALUE btobj = Qnil;
961 rb_backtrace_location_t *loc = NULL;
962 unsigned long backpatch_counter = 0;
963 bool skip_next_frame = FALSE;
964
965 // In the case the thread vm_stack or cfp is not initialized, there is no backtrace.
966 if (end_cfp == NULL) {
967 num_frames = 0;
968 }
969 else {
970 end_cfp = RUBY_VM_NEXT_CONTROL_FRAME(end_cfp);
971
972 /*
973 * top frame (dummy) <- RUBY_VM_END_CONTROL_FRAME
974 * top frame (dummy) <- end_cfp
975 * top frame <- main script
976 * top frame
977 * ...
978 * 2nd frame <- lev:0
979 * current frame <- ec->cfp
980 */
981
982 size = end_cfp - cfp + 1;
983 if (size < 0) {
984 num_frames = 0;
985 }
986 else if (num_frames < 0 || num_frames > size) {
987 num_frames = size;
988 }
989 }
990
991 btobj = backtrace_alloc_capa(num_frames, &bt);
992
993 bt->backtrace_size = 0;
994 if (num_frames == 0) {
995 if (start_too_large) *start_too_large = 0;
996 return btobj;
997 }
998
999 for (; cfp != end_cfp && (bt->backtrace_size < num_frames); cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)) {
1000 if (CFP_ISEQ(cfp)) {
1001 if (CFP_PC(cfp)) {
1002 if (start_frame > 0) {
1003 start_frame--;
1004 }
1005 else {
1006 bool internal = is_internal_location(CFP_ISEQ(cfp));
1007 if (skip_internal && internal) continue;
1008 if (!skip_next_frame) {
1009 const rb_iseq_t *iseq = CFP_ISEQ(cfp);
1010 const VALUE *pc = CFP_PC(cfp);
1011 if (internal && backpatch_counter > 0) {
1012 // To keep only one internal frame, discard the previous backpatch frames
1013 bt->backtrace_size -= backpatch_counter;
1014 backpatch_counter = 0;
1015 }
1016 loc = &bt->backtrace[bt->backtrace_size++];
1017 RB_OBJ_WRITE(btobj, &loc->cme, rb_vm_frame_method_entry(cfp));
1018 // internal frames (`<internal:...>`) should behave like C methods
1019 if (internal) {
1020 // Typically, these iseq and pc are not needed because they will be backpatched later.
1021 // But when the call stack starts with an internal frame (i.e., prelude.rb),
1022 // they will be used to show the `<internal:...>` location.
1023 RB_OBJ_WRITE(btobj, &loc->iseq, iseq);
1024 loc->pc = pc;
1025 backpatch_counter++;
1026 }
1027 else {
1028 RB_OBJ_WRITE(btobj, &loc->iseq, iseq);
1029 if ((VM_FRAME_TYPE(cfp) & VM_FRAME_MAGIC_MASK) == VM_FRAME_MAGIC_DUMMY) {
1030 loc->pc = NULL; // means location.first_lineno
1031 }
1032 else {
1033 loc->pc = pc;
1034 }
1035 bt_backpatch_loc(backpatch_counter, loc-1, iseq, pc);
1036 if (do_yield) {
1037 bt_yield_loc(loc - backpatch_counter, backpatch_counter+1, btobj);
1038 }
1039 backpatch_counter = 0;
1040 }
1041 }
1042 skip_next_frame = is_rescue_or_ensure_frame(cfp);
1043 }
1044 }
1045 }
1046 else {
1047 VM_ASSERT(RUBYVM_CFUNC_FRAME_P(cfp));
1048 if (start_frame > 0) {
1049 start_frame--;
1050 }
1051 else {
1052 loc = &bt->backtrace[bt->backtrace_size++];
1053 RB_OBJ_WRITE(btobj, &loc->cme, rb_vm_frame_method_entry(cfp));
1054 loc->iseq = NULL;
1055 loc->pc = NULL;
1056 backpatch_counter++;
1057 }
1058 }
1059 }
1060
1061 // When a backtrace entry corresponds to a method defined in C (e.g. rb_define_method), the reported file:line
1062 // is the one of the caller Ruby frame, so if the last entry is a C frame we find the caller Ruby frame here.
1063 if (backpatch_counter > 0) {
1064 for (; cfp != end_cfp; cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)) {
1065 if (CFP_ISEQ(cfp) && CFP_PC(cfp) && !(skip_internal && is_internal_location(CFP_ISEQ(cfp)))) {
1066 VM_ASSERT(!skip_next_frame); // ISEQ_TYPE_RESCUE/ISEQ_TYPE_ENSURE should have a caller Ruby ISEQ, not a cfunc
1067 bt_backpatch_loc(backpatch_counter, loc, CFP_ISEQ(cfp), CFP_PC(cfp));
1068 RB_OBJ_WRITTEN(btobj, Qundef, CFP_ISEQ(cfp));
1069 if (do_yield) {
1070 bt_yield_loc(loc - backpatch_counter + 1, backpatch_counter, btobj);
1071 }
1072 break;
1073 }
1074 }
1075 }
1076
1077 if (start_too_large) *start_too_large = (start_frame > 0 ? -1 : 0);
1078 return btobj;
1079}
1080
1081VALUE
1082rb_ec_backtrace_object(const rb_execution_context_t *ec)
1083{
1084 return rb_ec_partial_backtrace_object(ec, RUBY_BACKTRACE_START, RUBY_ALL_BACKTRACE_LINES, NULL, FALSE, FALSE);
1085}
1086
1087static VALUE
1088backtrace_collect(rb_backtrace_t *bt, VALUE (*func)(rb_backtrace_location_t *, void *arg), void *arg)
1089{
1090 VALUE btary;
1091 int i;
1092
1093 btary = rb_ary_new2(bt->backtrace_size);
1094
1095 for (i=0; i<bt->backtrace_size; i++) {
1096 rb_backtrace_location_t *loc = &bt->backtrace[i];
1097 rb_ary_push(btary, func(loc, arg));
1098 }
1099
1100 return btary;
1101}
1102
1103static VALUE
1104location_to_str_dmyarg(rb_backtrace_location_t *loc, void *dmy)
1105{
1106 return location_to_str(loc);
1107}
1108
1109static VALUE
1110backtrace_to_str_ary(VALUE self)
1111{
1112 VALUE r;
1113 rb_backtrace_t *bt;
1114 TypedData_Get_Struct(self, rb_backtrace_t, &backtrace_data_type, bt);
1115 r = backtrace_collect(bt, location_to_str_dmyarg, 0);
1116 RB_GC_GUARD(self);
1117 return r;
1118}
1119
1120VALUE
1121rb_backtrace_to_str_ary(VALUE self)
1122{
1123 rb_backtrace_t *bt;
1124 TypedData_Get_Struct(self, rb_backtrace_t, &backtrace_data_type, bt);
1125
1126 if (!bt->strary) {
1127 RB_OBJ_WRITE(self, &bt->strary, backtrace_to_str_ary(self));
1128 }
1129 return bt->strary;
1130}
1131
1132static VALUE
1133location_create(rb_backtrace_location_t *srcloc, void *btobj)
1134{
1135 VALUE obj;
1136 struct valued_frame_info *vloc;
1137 obj = TypedData_Make_Struct(rb_cBacktraceLocation, struct valued_frame_info, &location_data_type, vloc);
1138
1139 vloc->loc = srcloc;
1140 RB_OBJ_WRITE(obj, &vloc->btobj, (VALUE)btobj);
1141
1142 return obj;
1143}
1144
1145static VALUE
1146backtrace_to_location_ary(VALUE self)
1147{
1148 VALUE r;
1149 rb_backtrace_t *bt;
1150 TypedData_Get_Struct(self, rb_backtrace_t, &backtrace_data_type, bt);
1151 r = backtrace_collect(bt, location_create, (void *)self);
1152 RB_GC_GUARD(self);
1153 return r;
1154}
1155
1156VALUE
1157rb_backtrace_to_location_ary(VALUE self)
1158{
1159 rb_backtrace_t *bt;
1160 TypedData_Get_Struct(self, rb_backtrace_t, &backtrace_data_type, bt);
1161
1162 if (!bt->locary) {
1163 RB_OBJ_WRITE(self, &bt->locary, backtrace_to_location_ary(self));
1164 }
1165 return bt->locary;
1166}
1167
1168VALUE
1169rb_location_ary_to_backtrace(VALUE ary)
1170{
1171 if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) == 0 || !rb_frame_info_p(RARRAY_AREF(ary, 0))) {
1172 return Qfalse;
1173 }
1174
1175 rb_backtrace_t *new_backtrace;
1176 rb_len_t num_frames = RARRAY_LEN(ary);
1177 VALUE btobj = backtrace_alloc_capa(num_frames, &new_backtrace);
1178
1179 for (rb_len_t index = 0; index < RARRAY_LEN(ary); index++) {
1180 VALUE locobj = RARRAY_AREF(ary, index);
1181
1182 if (!rb_frame_info_p(locobj)) {
1183 return Qfalse;
1184 }
1185
1186 struct valued_frame_info *src_vloc;
1187 TypedData_Get_Struct(locobj, struct valued_frame_info, &location_data_type, src_vloc);
1188
1189 rb_backtrace_location_t *dst_location = &new_backtrace->backtrace[index];
1190 RB_OBJ_WRITE(btobj, &dst_location->cme, src_vloc->loc->cme);
1191 RB_OBJ_WRITE(btobj, &dst_location->iseq, src_vloc->loc->iseq);
1192 dst_location->pc = src_vloc->loc->pc;
1193
1194 new_backtrace->backtrace_size++;
1195
1196 RB_GC_GUARD(locobj);
1197 }
1198
1199 return btobj;
1200}
1201
1202static VALUE
1203backtrace_dump_data(VALUE self)
1204{
1205 VALUE str = rb_backtrace_to_str_ary(self);
1206 return str;
1207}
1208
1209static VALUE
1210backtrace_load_data(VALUE self, VALUE str)
1211{
1212 rb_backtrace_t *bt;
1213 TypedData_Get_Struct(self, rb_backtrace_t, &backtrace_data_type, bt);
1214 RB_OBJ_WRITE(self, &bt->strary, str);
1215 return self;
1216}
1217
1218/*
1219 * call-seq: Thread::Backtrace::limit -> integer
1220 *
1221 * Returns maximum backtrace length set by <tt>--backtrace-limit</tt>
1222 * command-line option. The default is <tt>-1</tt> which means unlimited
1223 * backtraces. If the value is zero or positive, the error backtraces,
1224 * produced by Exception#full_message, are abbreviated and the extra lines
1225 * are replaced by <tt>... 3 levels... </tt>
1226 *
1227 * $ ruby -r net/http -e "p Thread::Backtrace.limit; Net::HTTP.get(URI('http://wrong.address'))"
1228 * - 1
1229 * .../lib/ruby/3.1.0/socket.rb:227:in `getaddrinfo': Failed to open TCP connection to wrong.address:80 (getaddrinfo: Name or service not known) (SocketError)
1230 * from .../lib/ruby/3.1.0/socket.rb:227:in `foreach'
1231 * from .../lib/ruby/3.1.0/socket.rb:632:in `tcp'
1232 * from .../lib/ruby/3.1.0/net/http.rb:998:in `connect'
1233 * from .../lib/ruby/3.1.0/net/http.rb:976:in `do_start'
1234 * from .../lib/ruby/3.1.0/net/http.rb:965:in `start'
1235 * from .../lib/ruby/3.1.0/net/http.rb:627:in `start'
1236 * from .../lib/ruby/3.1.0/net/http.rb:503:in `get_response'
1237 * from .../lib/ruby/3.1.0/net/http.rb:474:in `get'
1238 * .../lib/ruby/3.1.0/socket.rb:227:in `getaddrinfo': getaddrinfo: Name or service not known (SocketError)
1239 * from .../lib/ruby/3.1.0/socket.rb:227:in `foreach'
1240 * from .../lib/ruby/3.1.0/socket.rb:632:in `tcp'
1241 * from .../lib/ruby/3.1.0/net/http.rb:998:in `connect'
1242 * from .../lib/ruby/3.1.0/net/http.rb:976:in `do_start'
1243 * from .../lib/ruby/3.1.0/net/http.rb:965:in `start'
1244 * from .../lib/ruby/3.1.0/net/http.rb:627:in `start'
1245 * from .../lib/ruby/3.1.0/net/http.rb:503:in `get_response'
1246 * from .../lib/ruby/3.1.0/net/http.rb:474:in `get'
1247 * from -e:1:in `<main>'
1248 *
1249 * $ ruby --backtrace-limit 2 -r net/http -e "p Thread::Backtrace.limit; Net::HTTP.get(URI('http://wrong.address'))"
1250 * 2
1251 * .../lib/ruby/3.1.0/socket.rb:227:in `getaddrinfo': Failed to open TCP connection to wrong.address:80 (getaddrinfo: Name or service not known) (SocketError)
1252 * from .../lib/ruby/3.1.0/socket.rb:227:in `foreach'
1253 * from .../lib/ruby/3.1.0/socket.rb:632:in `tcp'
1254 * ... 7 levels...
1255 * .../lib/ruby/3.1.0/socket.rb:227:in `getaddrinfo': getaddrinfo: Name or service not known (SocketError)
1256 * from .../lib/ruby/3.1.0/socket.rb:227:in `foreach'
1257 * from .../lib/ruby/3.1.0/socket.rb:632:in `tcp'
1258 * ... 7 levels...
1259 *
1260 * $ ruby --backtrace-limit 0 -r net/http -e "p Thread::Backtrace.limit; Net::HTTP.get(URI('http://wrong.address'))"
1261 * 0
1262 * .../lib/ruby/3.1.0/socket.rb:227:in `getaddrinfo': Failed to open TCP connection to wrong.address:80 (getaddrinfo: Name or service not known) (SocketError)
1263 * ... 9 levels...
1264 * .../lib/ruby/3.1.0/socket.rb:227:in `getaddrinfo': getaddrinfo: Name or service not known (SocketError)
1265 * ... 9 levels...
1266 *
1267 */
1268static VALUE
1269backtrace_limit(VALUE self)
1270{
1271 return LONG2NUM(rb_backtrace_length_limit);
1272}
1273
1274/* :nodoc: */
1275static VALUE
1276backtrace_clone(VALUE self)
1277{
1278 rb_backtrace_t *bt;
1279 TypedData_Get_Struct(self, rb_backtrace_t, &backtrace_data_type, bt);
1280
1281 rb_backtrace_t *other_bt;
1282 VALUE clone = backtrace_alloc_capa(bt->backtrace_size, &other_bt);
1283
1284 rb_obj_clone_setup(self, clone, Qfalse);
1285
1286 return clone;
1287}
1288
1289/* :nodoc: */
1290static VALUE
1291backtrace_dup(VALUE self)
1292{
1294
1296}
1297
1298/* :nodoc: */
1299static VALUE
1300backtrace_initialize_copy(VALUE self, VALUE original)
1301{
1302 rb_backtrace_t *bt;
1303 TypedData_Get_Struct(self, rb_backtrace_t, &backtrace_data_type, bt);
1304
1305 rb_backtrace_t *original_bt;
1306 TypedData_Get_Struct(original, rb_backtrace_t, &backtrace_data_type, original_bt);
1307
1308 bt->backtrace_size = original_bt->backtrace_size;
1309 MEMCPY(bt->backtrace, original_bt->backtrace, rb_backtrace_location_t, original_bt->backtrace_size);
1310 rb_gc_writebarrier_remember(self);
1311
1312 return Qnil;
1313}
1314
1315VALUE
1316rb_ec_backtrace_str_ary(const rb_execution_context_t *ec, long lev, long n)
1317{
1318 return rb_backtrace_to_str_ary(rb_ec_partial_backtrace_object(ec, lev, n, NULL, FALSE, FALSE));
1319}
1320
1321VALUE
1322rb_ec_backtrace_location_ary(const rb_execution_context_t *ec, long lev, long n, bool skip_internal)
1323{
1324 return rb_backtrace_to_location_ary(rb_ec_partial_backtrace_object(ec, lev, n, NULL, skip_internal, FALSE));
1325}
1326
1327/* make old style backtrace directly */
1328
1329static void
1330backtrace_each(const rb_execution_context_t *ec,
1331 void (*init)(void *arg, size_t size),
1332 void (*iter_iseq)(void *arg, const rb_control_frame_t *cfp),
1333 void (*iter_cfunc)(void *arg, const rb_control_frame_t *cfp, ID mid),
1334 void *arg)
1335{
1336 const rb_control_frame_t *last_cfp = ec->cfp;
1337 const rb_control_frame_t *start_cfp = RUBY_VM_END_CONTROL_FRAME(ec);
1338 const rb_control_frame_t *cfp;
1339 ptrdiff_t size, i;
1340
1341 // In the case the thread vm_stack or cfp is not initialized, there is no backtrace.
1342 if (start_cfp == NULL) {
1343 init(arg, 0);
1344 return;
1345 }
1346
1347 /* <- start_cfp (end control frame)
1348 * top frame (dummy)
1349 * top frame (dummy)
1350 * top frame <- start_cfp
1351 * top frame
1352 * ...
1353 * 2nd frame <- lev:0
1354 * current frame <- ec->cfp
1355 */
1356
1357 start_cfp =
1358 RUBY_VM_NEXT_CONTROL_FRAME(
1359 RUBY_VM_NEXT_CONTROL_FRAME(start_cfp)); /* skip top frames */
1360
1361 if (start_cfp < last_cfp) {
1362 size = 0;
1363 }
1364 else {
1365 size = start_cfp - last_cfp + 1;
1366 }
1367
1368 init(arg, size);
1369
1370 /* SDR(); */
1371 for (i=0, cfp = start_cfp; i<size; i++, cfp = RUBY_VM_NEXT_CONTROL_FRAME(cfp)) {
1372 /* fprintf(stderr, "cfp: %d\n", (rb_control_frame_t *)(ec->vm_stack + ec->vm_stack_size) - cfp); */
1373 if (CFP_ISEQ(cfp)) {
1374 if (CFP_PC(cfp)) {
1375 iter_iseq(arg, cfp);
1376 }
1377 }
1378 else {
1379 VM_ASSERT(RUBYVM_CFUNC_FRAME_P(cfp));
1380 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1381 ID mid = me->def->original_id;
1382
1383 iter_cfunc(arg, cfp, mid);
1384 }
1385 }
1386}
1387
1389 VALUE filename;
1390 int lineno;
1391 void (*func)(void *data, VALUE file, int lineno, VALUE name);
1392 void *data; /* result */
1393};
1394
1395static void
1396oldbt_init(void *ptr, size_t dmy)
1397{
1398 struct oldbt_arg *arg = (struct oldbt_arg *)ptr;
1399 arg->filename = GET_VM()->progname;
1400 arg->lineno = 0;
1401}
1402
1403static void
1404oldbt_iter_iseq(void *ptr, const rb_control_frame_t *cfp)
1405{
1406 const rb_iseq_t *iseq = CFP_ISEQ(cfp);
1407 const VALUE *pc = CFP_PC(cfp);
1408 struct oldbt_arg *arg = (struct oldbt_arg *)ptr;
1409 VALUE file = arg->filename = rb_iseq_path(iseq);
1410 VALUE name = ISEQ_BODY(iseq)->location.label;
1411 int lineno = arg->lineno = calc_lineno(iseq, pc);
1412
1413 (arg->func)(arg->data, file, lineno, name);
1414}
1415
1416static void
1417oldbt_iter_cfunc(void *ptr, const rb_control_frame_t *cfp, ID mid)
1418{
1419 struct oldbt_arg *arg = (struct oldbt_arg *)ptr;
1420 VALUE file = arg->filename;
1421 VALUE name = rb_id2str(mid);
1422 int lineno = arg->lineno;
1423
1424 (arg->func)(arg->data, file, lineno, name);
1425}
1426
1427static void
1428oldbt_print(void *data, VALUE file, int lineno, VALUE name)
1429{
1430 FILE *fp = (FILE *)data;
1431
1432 if (NIL_P(name)) {
1433 fprintf(fp, "\tfrom %.*s:%d:in unknown method\n",
1434 RSTRING_LENINT(file), RSTRING_PTR(file), lineno);
1435 }
1436 else {
1437 fprintf(fp, "\tfrom %.*s:%d:in '%.*s'\n",
1438 RSTRING_LENINT(file), RSTRING_PTR(file), lineno,
1439 RSTRING_LENINT(name), RSTRING_PTR(name));
1440 }
1441}
1442
1443static void
1444vm_backtrace_print(FILE *fp)
1445{
1446 struct oldbt_arg arg;
1447
1448 arg.func = oldbt_print;
1449 arg.data = (void *)fp;
1450 backtrace_each(GET_EC(),
1451 oldbt_init,
1452 oldbt_iter_iseq,
1453 oldbt_iter_cfunc,
1454 &arg);
1455}
1456
1458 FILE *fp;
1459 int count;
1460};
1461
1462static void
1463oldbt_bugreport(void *arg, VALUE file, int line, VALUE method)
1464{
1465 struct oldbt_bugreport_arg *p = arg;
1466 FILE *fp = p->fp;
1467 const char *filename = NIL_P(file) ? "ruby" : RSTRING_PTR(file);
1468 int filename_len = NIL_P(file) ? 4 : RSTRING_LENINT(file);
1469 if (!p->count) {
1470 fprintf(fp, "-- Ruby level backtrace information "
1471 "----------------------------------------\n");
1472 p->count = 1;
1473 }
1474 if (NIL_P(method)) {
1475 fprintf(fp, "%.*s:%d:in unknown method\n",
1476 filename_len, filename, line);
1477 }
1478 else {
1479 fprintf(fp, "%.*s:%d:in '%.*s'\n",
1480 filename_len, filename, line,
1481 RSTRING_LENINT(method), RSTRING_PTR(method));
1482 }
1483}
1484
1485void
1486rb_backtrace_print_as_bugreport(FILE *fp)
1487{
1488 struct oldbt_arg arg;
1489 struct oldbt_bugreport_arg barg = {fp, 0};
1490
1491 arg.func = oldbt_bugreport;
1492 arg.data = &barg;
1493
1494 backtrace_each(GET_EC(),
1495 oldbt_init,
1496 oldbt_iter_iseq,
1497 oldbt_iter_cfunc,
1498 &arg);
1499}
1500
1501void
1503{
1504 vm_backtrace_print(stderr);
1505}
1506
1508 VALUE (*iter)(VALUE recv, VALUE str);
1509 VALUE output;
1510};
1511
1512static void
1513oldbt_print_to(void *data, VALUE file, int lineno, VALUE name)
1514{
1515 const struct print_to_arg *arg = data;
1516 VALUE str = rb_sprintf("\tfrom %"PRIsVALUE":%d:in ", file, lineno);
1517
1518 if (NIL_P(name)) {
1519 rb_str_cat2(str, "unknown method\n");
1520 }
1521 else {
1522 rb_str_catf(str, " '%"PRIsVALUE"'\n", name);
1523 }
1524 (*arg->iter)(arg->output, str);
1525}
1526
1527void
1528rb_backtrace_each(VALUE (*iter)(VALUE recv, VALUE str), VALUE output)
1529{
1530 struct oldbt_arg arg;
1531 struct print_to_arg parg;
1532
1533 parg.iter = iter;
1534 parg.output = output;
1535 arg.func = oldbt_print_to;
1536 arg.data = &parg;
1537 backtrace_each(GET_EC(),
1538 oldbt_init,
1539 oldbt_iter_iseq,
1540 oldbt_iter_cfunc,
1541 &arg);
1542}
1543
1544VALUE
1546{
1547 return rb_ec_backtrace_str_ary(GET_EC(), RUBY_BACKTRACE_START, RUBY_ALL_BACKTRACE_LINES);
1548}
1549
1550static rb_len_t
1551ec_backtrace_range(const rb_execution_context_t *ec, int argc, const VALUE *argv, int lev_default, int lev_plus, rb_len_t *len_ptr)
1552{
1553 VALUE level, vn, opts;
1554 rb_len_t lev, n;
1555
1556 rb_scan_args(argc, argv, "02:", &level, &vn, &opts);
1557
1558 if (!NIL_P(opts)) {
1559 rb_get_kwargs(opts, (ID []){0}, 0, 0, NULL);
1560 }
1561 if (argc == 2 && NIL_P(vn)) argc--;
1562
1563 switch (argc) {
1564 case 0:
1565 lev = lev_default + lev_plus;
1566 n = RUBY_ALL_BACKTRACE_LINES;
1567 break;
1568 case 1:
1569 {
1570 rb_len_t beg, len, bt_size = backtrace_size(ec);
1571 switch (rb_range_beg_len(level, &beg, &len, bt_size - lev_plus, 0)) {
1572 case Qfalse:
1573 lev = NUM2LEN(level);
1574 if (lev < 0) {
1575 rb_raise(rb_eArgError, "negative level (%"PRIdLEN")", lev);
1576 }
1577 lev += lev_plus;
1578 n = RUBY_ALL_BACKTRACE_LINES;
1579 break;
1580 case Qnil:
1581 return -1;
1582 default:
1583 lev = beg + lev_plus;
1584 n = len;
1585 break;
1586 }
1587 break;
1588 }
1589 case 2:
1590 lev = NUM2LEN(level);
1591 n = NUM2LEN(vn);
1592 if (lev < 0) {
1593 rb_raise(rb_eArgError, "negative level (%"PRIdLEN")", lev);
1594 }
1595 if (n < 0) {
1596 rb_raise(rb_eArgError, "negative size (%"PRIdLEN")", n);
1597 }
1598 lev += lev_plus;
1599 break;
1600 default:
1601 lev = n = 0; /* to avoid warning */
1602 break;
1603 }
1604
1605 *len_ptr = n;
1606 return lev;
1607}
1608
1609static VALUE
1610ec_backtrace_to_ary(const rb_execution_context_t *ec, int argc, const VALUE *argv, int lev_default, int lev_plus, int to_str)
1611{
1612 rb_len_t lev, n;
1613 VALUE btval, r;
1614 int too_large;
1615
1616 lev = ec_backtrace_range(ec, argc, argv, lev_default, lev_plus, &n);
1617 if (lev < 0) return Qnil;
1618
1619 if (n == 0) {
1620 return rb_ary_new();
1621 }
1622
1623 btval = rb_ec_partial_backtrace_object(ec, lev, n, &too_large, FALSE, FALSE);
1624
1625 if (too_large) {
1626 return Qnil;
1627 }
1628
1629 if (to_str) {
1630 r = backtrace_to_str_ary(btval);
1631 }
1632 else {
1633 r = backtrace_to_location_ary(btval);
1634 }
1635 RB_GC_GUARD(btval);
1636 return r;
1637}
1638
1639static VALUE
1640thread_backtrace_to_ary(int argc, const VALUE *argv, VALUE thval, int to_str)
1641{
1642 rb_thread_t *target_th = rb_thread_ptr(thval);
1643
1644 if (target_th->to_kill || target_th->status == THREAD_KILLED)
1645 return Qnil;
1646
1647 return ec_backtrace_to_ary(target_th->ec, argc, argv, 0, 0, to_str);
1648}
1649
1650VALUE
1651rb_vm_thread_backtrace(int argc, const VALUE *argv, VALUE thval)
1652{
1653 return thread_backtrace_to_ary(argc, argv, thval, 1);
1654}
1655
1656VALUE
1657rb_vm_thread_backtrace_locations(int argc, const VALUE *argv, VALUE thval)
1658{
1659 return thread_backtrace_to_ary(argc, argv, thval, 0);
1660}
1661
1662VALUE
1663rb_vm_backtrace(int argc, const VALUE * argv, struct rb_execution_context_struct * ec)
1664{
1665 return ec_backtrace_to_ary(ec, argc, argv, 0, 0, 1);
1666}
1667
1668VALUE
1669rb_vm_backtrace_locations(int argc, const VALUE * argv, struct rb_execution_context_struct * ec)
1670{
1671 return ec_backtrace_to_ary(ec, argc, argv, 0, 0, 0);
1672}
1673
1674/*
1675 * call-seq:
1676 * caller(start=1, length=nil) -> array or nil
1677 * caller(range) -> array or nil
1678 *
1679 * Returns the current execution stack---an array containing strings in
1680 * the form <code>file:line</code> or <code>file:line: in
1681 * `method'</code>.
1682 *
1683 * The optional _start_ parameter determines the number of initial stack
1684 * entries to omit from the top of the stack.
1685 *
1686 * A second optional +length+ parameter can be used to limit how many entries
1687 * are returned from the stack.
1688 *
1689 * Returns +nil+ if _start_ is greater than the size of
1690 * current execution stack.
1691 *
1692 * Optionally you can pass a range, which will return an array containing the
1693 * entries within the specified range.
1694 *
1695 * def a(skip)
1696 * caller(skip)
1697 * end
1698 * def b(skip)
1699 * a(skip)
1700 * end
1701 * def c(skip)
1702 * b(skip)
1703 * end
1704 * c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10:in `<main>'"]
1705 * c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11:in `<main>'"]
1706 * c(2) #=> ["prog:8:in `c'", "prog:12:in `<main>'"]
1707 * c(3) #=> ["prog:13:in `<main>'"]
1708 * c(4) #=> []
1709 * c(5) #=> nil
1710 */
1711
1712static VALUE
1713rb_f_caller(int argc, VALUE *argv, VALUE _)
1714{
1715 return ec_backtrace_to_ary(GET_EC(), argc, argv, 1, 1, 1);
1716}
1717
1718/*
1719 * call-seq:
1720 * caller_locations(start=1, length=nil) -> array or nil
1721 * caller_locations(range) -> array or nil
1722 *
1723 * Returns the current execution stack---an array containing
1724 * backtrace location objects.
1725 *
1726 * See Thread::Backtrace::Location for more information.
1727 *
1728 * The optional _start_ parameter determines the number of initial stack
1729 * entries to omit from the top of the stack.
1730 *
1731 * A second optional +length+ parameter can be used to limit how many entries
1732 * are returned from the stack.
1733 *
1734 * Returns +nil+ if _start_ is greater than the size of
1735 * current execution stack.
1736 *
1737 * Optionally you can pass a range, which will return an array containing the
1738 * entries within the specified range.
1739 */
1740static VALUE
1741rb_f_caller_locations(int argc, VALUE *argv, VALUE _)
1742{
1743 return ec_backtrace_to_ary(GET_EC(), argc, argv, 1, 1, 0);
1744}
1745
1746/*
1747 * call-seq:
1748 * Thread.each_caller_location(...) { |loc| ... } -> nil
1749 *
1750 * Yields each frame of the current execution stack as a
1751 * backtrace location object.
1752 */
1753static VALUE
1754each_caller_location(int argc, VALUE *argv, VALUE _)
1755{
1756 rb_execution_context_t *ec = GET_EC();
1757 rb_len_t n, lev = ec_backtrace_range(ec, argc, argv, 1, 1, &n);
1758 if (lev >= 0 && n != 0) {
1759 rb_ec_partial_backtrace_object(ec, lev, n, NULL, FALSE, TRUE);
1760 }
1761 return Qnil;
1762}
1763
1764static VALUE
1765backtrace_no_allocator(VALUE klass)
1766{
1768
1770}
1771
1772/* called from Init_vm() in vm.c */
1773void
1774Init_vm_backtrace(void)
1775{
1776 /*
1777 * An internal representation of the backtrace. The user will never interact with
1778 * objects of this class directly, but class methods can be used to get backtrace
1779 * settings of the current session.
1780 */
1781 rb_cBacktrace = rb_define_class_under(rb_cThread, "Backtrace", rb_cObject);
1782
1783 // Can't undefine the allocator, as it's needed as a key by Marshal
1784 rb_define_alloc_func(rb_cBacktrace, backtrace_no_allocator);
1785 rb_marshal_define_compat(rb_cBacktrace, rb_cArray, backtrace_dump_data, backtrace_load_data);
1786
1787 rb_undef_method(CLASS_OF(rb_cBacktrace), "new");
1788 rb_define_singleton_method(rb_cBacktrace, "limit", backtrace_limit, 0);
1789
1790 rb_define_method(rb_cBacktrace, "clone", backtrace_clone, 0);
1791 rb_define_method(rb_cBacktrace, "dup", backtrace_dup, 0);
1792 rb_define_method(rb_cBacktrace, "initialize_copy", backtrace_initialize_copy, 1);
1793
1794 /*
1795 * An object representation of a stack frame, initialized by
1796 * Kernel#caller_locations.
1797 *
1798 * For example:
1799 *
1800 * # caller_locations.rb
1801 * def a(skip)
1802 * caller_locations(skip)
1803 * end
1804 * def b(skip)
1805 * a(skip)
1806 * end
1807 * def c(skip)
1808 * b(skip)
1809 * end
1810 *
1811 * c(0..2).map do |call|
1812 * puts call.to_s
1813 * end
1814 *
1815 * Running <code>ruby caller_locations.rb</code> will produce:
1816 *
1817 * caller_locations.rb:2:in `a'
1818 * caller_locations.rb:5:in `b'
1819 * caller_locations.rb:8:in `c'
1820 *
1821 * Here's another example with a slightly different result:
1822 *
1823 * # foo.rb
1824 * class Foo
1825 * attr_accessor :locations
1826 * def initialize(skip)
1827 * @locations = caller_locations(skip)
1828 * end
1829 * end
1830 *
1831 * Foo.new(0..2).locations.map do |call|
1832 * puts call.to_s
1833 * end
1834 *
1835 * Now run <code>ruby foo.rb</code> and you should see:
1836 *
1837 * init.rb:4:in `initialize'
1838 * init.rb:8:in `new'
1839 * init.rb:8:in `<main>'
1840 */
1841 rb_cBacktraceLocation = rb_define_class_under(rb_cBacktrace, "Location", rb_cObject);
1842 rb_undef_alloc_func(rb_cBacktraceLocation);
1843 rb_undef_method(CLASS_OF(rb_cBacktraceLocation), "new");
1844 rb_define_method(rb_cBacktraceLocation, "lineno", location_lineno_m, 0);
1845 rb_define_method(rb_cBacktraceLocation, "label", location_label_m, 0);
1846 rb_define_method(rb_cBacktraceLocation, "base_label", location_base_label_m, 0);
1847 rb_define_method(rb_cBacktraceLocation, "path", location_path_m, 0);
1848 rb_define_method(rb_cBacktraceLocation, "absolute_path", location_absolute_path_m, 0);
1849 rb_define_method(rb_cBacktraceLocation, "source_range", location_source_range_m, 0);
1850 rb_define_method(rb_cBacktraceLocation, "to_s", location_to_str_m, 0);
1851 rb_define_method(rb_cBacktraceLocation, "inspect", location_inspect_m, 0);
1852
1853 rb_define_global_function("caller", rb_f_caller, -1);
1854 rb_define_global_function("caller_locations", rb_f_caller_locations, -1);
1855
1856 rb_define_singleton_method(rb_cThread, "each_caller_location", each_caller_location, -1);
1857}
1858
1859/* debugger API */
1860
1861RUBY_SYMBOL_EXPORT_BEGIN
1862
1863RUBY_SYMBOL_EXPORT_END
1864
1866 rb_execution_context_t *ec;
1867 rb_control_frame_t *cfp;
1868 VALUE contexts; /* [[klass, binding, iseq, cfp], ...] */
1869 VALUE raw_backtrace;
1870};
1871
1872enum {
1873 CALLER_BINDING_SELF,
1874 CALLER_BINDING_CLASS,
1875 CALLER_BINDING_BINDING,
1876 CALLER_BINDING_ISEQ,
1877 CALLER_BINDING_CFP,
1878 CALLER_BINDING_LOC,
1879 CALLER_BINDING_DEPTH,
1880};
1881
1883 VALUE ary;
1884 const rb_execution_context_t *ec;
1885 VALUE btobj;
1886 rb_backtrace_t *bt;
1887};
1888
1889static void
1890collect_caller_bindings_init(void *arg, size_t num_frames)
1891{
1893 data->btobj = backtrace_alloc_capa(num_frames, &data->bt);
1894}
1895
1896static VALUE
1897get_klass(const rb_control_frame_t *cfp)
1898{
1899 VALUE klass;
1900 if (rb_vm_control_frame_id_and_class(cfp, 0, 0, &klass)) {
1901 if (RB_TYPE_P(klass, T_ICLASS)) {
1902 return RBASIC(klass)->klass;
1903 }
1904 else {
1905 return klass;
1906 }
1907 }
1908 else {
1909 return Qnil;
1910 }
1911}
1912
1913static int
1914frame_depth(const rb_execution_context_t *ec, const rb_control_frame_t *cfp)
1915{
1916 VM_ASSERT(RUBY_VM_END_CONTROL_FRAME(ec) >= cfp);
1917 return (int)(RUBY_VM_END_CONTROL_FRAME(ec) - cfp);
1918}
1919
1920static void
1921collect_caller_bindings_iseq(void *arg, const rb_control_frame_t *cfp)
1922{
1924 VALUE frame = rb_ary_new2(6);
1925 const rb_iseq_t *iseq = CFP_ISEQ(cfp);
1926
1927 rb_ary_store(frame, CALLER_BINDING_SELF, cfp->self);
1928 rb_ary_store(frame, CALLER_BINDING_CLASS, get_klass(cfp));
1929 rb_ary_store(frame, CALLER_BINDING_BINDING, GC_GUARDED_PTR(cfp)); /* create later */
1930 rb_ary_store(frame, CALLER_BINDING_ISEQ, iseq ? (VALUE)iseq : Qnil);
1931 rb_ary_store(frame, CALLER_BINDING_CFP, GC_GUARDED_PTR(cfp));
1932
1933 rb_backtrace_location_t *loc = &data->bt->backtrace[data->bt->backtrace_size++];
1934 RB_OBJ_WRITE(data->btobj, &loc->cme, rb_vm_frame_method_entry(cfp));
1935 RB_OBJ_WRITE(data->btobj, &loc->iseq, iseq);
1936 loc->pc = CFP_PC(cfp);
1937 VALUE vloc = location_create(loc, (void *)data->btobj);
1938 rb_ary_store(frame, CALLER_BINDING_LOC, vloc);
1939
1940 rb_ary_store(frame, CALLER_BINDING_DEPTH, INT2FIX(frame_depth(data->ec, cfp)));
1941
1942 rb_ary_push(data->ary, frame);
1943}
1944
1945static void
1946collect_caller_bindings_cfunc(void *arg, const rb_control_frame_t *cfp, ID mid)
1947{
1949 VALUE frame = rb_ary_new2(6);
1950
1951 rb_ary_store(frame, CALLER_BINDING_SELF, cfp->self);
1952 rb_ary_store(frame, CALLER_BINDING_CLASS, get_klass(cfp));
1953 rb_ary_store(frame, CALLER_BINDING_BINDING, Qnil); /* not available */
1954 rb_ary_store(frame, CALLER_BINDING_ISEQ, Qnil); /* not available */
1955 rb_ary_store(frame, CALLER_BINDING_CFP, GC_GUARDED_PTR(cfp));
1956
1957 rb_backtrace_location_t *loc = &data->bt->backtrace[data->bt->backtrace_size++];
1958 RB_OBJ_WRITE(data->btobj, &loc->cme, rb_vm_frame_method_entry(cfp));
1959 loc->iseq = NULL;
1960 loc->pc = NULL;
1961 VALUE vloc = location_create(loc, (void *)data->btobj);
1962 rb_ary_store(frame, CALLER_BINDING_LOC, vloc);
1963
1964 rb_ary_store(frame, CALLER_BINDING_DEPTH, INT2FIX(frame_depth(data->ec, cfp)));
1965
1966 rb_ary_push(data->ary, frame);
1967}
1968
1969static VALUE
1970collect_caller_bindings(const rb_execution_context_t *ec)
1971{
1972 int i;
1973 VALUE result;
1974 struct collect_caller_bindings_data data = {
1975 rb_ary_new(), ec
1976 };
1977
1978 backtrace_each(ec,
1979 collect_caller_bindings_init,
1980 collect_caller_bindings_iseq,
1981 collect_caller_bindings_cfunc,
1982 &data);
1983
1984 result = rb_ary_reverse(data.ary);
1985
1986 /* bindings should be created from top of frame */
1987 for (i=0; i<RARRAY_LEN(result); i++) {
1988 VALUE entry = rb_ary_entry(result, i);
1989 VALUE cfp_val = rb_ary_entry(entry, CALLER_BINDING_BINDING);
1990
1991 if (!NIL_P(cfp_val)) {
1992 rb_control_frame_t *cfp = GC_GUARDED_PTR_REF(cfp_val);
1993 rb_ary_store(entry, CALLER_BINDING_BINDING, rb_vm_make_binding(ec, cfp));
1994 }
1995 }
1996
1997 return result;
1998}
1999
2000/*
2001 * Note that the passed `rb_debug_inspector_t' will be disabled
2002 * after `rb_debug_inspector_open'.
2003 */
2004
2005VALUE
2007{
2008 rb_debug_inspector_t dbg_context;
2009 rb_execution_context_t *ec = GET_EC();
2010 enum ruby_tag_type state;
2011 volatile VALUE MAYBE_UNUSED(result);
2012 int i;
2013
2014 /* escape all env to heap */
2015 rb_vm_stack_to_heap(ec);
2016
2017 dbg_context.ec = ec;
2018 dbg_context.cfp = dbg_context.ec->cfp;
2019 dbg_context.contexts = collect_caller_bindings(ec);
2020 dbg_context.raw_backtrace = rb_ary_new();
2021 for (i=0; i<RARRAY_LEN(dbg_context.contexts); i++) {
2022 VALUE frame = rb_ary_entry(dbg_context.contexts, i);
2023 rb_ary_push(dbg_context.raw_backtrace, rb_ary_entry(frame, CALLER_BINDING_LOC));
2024 }
2025
2026 EC_PUSH_TAG(ec);
2027 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2028 result = (*func)(&dbg_context, data);
2029 }
2030 EC_POP_TAG();
2031
2032 /* invalidate bindings? */
2033
2034 if (state) {
2035 EC_JUMP_TAG(ec, state);
2036 }
2037
2038 return result;
2039}
2040
2041static VALUE
2042frame_get(const rb_debug_inspector_t *dc, rb_len_t index)
2043{
2044 if (index < 0 || index >= RARRAY_LEN(dc->contexts)) {
2045 rb_raise(rb_eArgError, "no such frame");
2046 }
2047 return rb_ary_entry(dc->contexts, index);
2048}
2049
2050VALUE
2052{
2053 VALUE frame = frame_get(dc, index);
2054 return rb_ary_entry(frame, CALLER_BINDING_SELF);
2055}
2056
2057VALUE
2059{
2060 VALUE frame = frame_get(dc, index);
2061 return rb_ary_entry(frame, CALLER_BINDING_CLASS);
2062}
2063
2064VALUE
2066{
2067 VALUE frame = frame_get(dc, index);
2068 return rb_ary_entry(frame, CALLER_BINDING_BINDING);
2069}
2070
2071VALUE
2073{
2074 VALUE frame = frame_get(dc, index);
2075 VALUE iseq = rb_ary_entry(frame, CALLER_BINDING_ISEQ);
2076
2077 return RTEST(iseq) ? rb_iseqw_new((rb_iseq_t *)iseq) : Qnil;
2078}
2079
2080VALUE
2082{
2083 VALUE frame = frame_get(dc, index);
2084 return rb_ary_entry(frame, CALLER_BINDING_DEPTH);
2085}
2086
2087VALUE
2089{
2090 rb_execution_context_t *ec = GET_EC();
2091 return INT2FIX(frame_depth(ec, ec->cfp));
2092}
2093
2094VALUE
2096{
2097 return dc->raw_backtrace;
2098}
2099
2100static int
2101thread_profile_frames(rb_execution_context_t *ec, int start, int limit, VALUE *buff, int *lines)
2102{
2103 int i;
2104 const rb_control_frame_t *cfp = ec->cfp, *end_cfp = RUBY_VM_END_CONTROL_FRAME(ec);
2105 const rb_control_frame_t *top = cfp;
2106 const rb_callable_method_entry_t *cme;
2107
2108 // If this function is called inside a thread after thread creation, but
2109 // before the CFP has been created, just return 0. This can happen when
2110 // sampling via signals. Threads can be interrupted randomly by the
2111 // signal, including during the time after the thread has been created, but
2112 // before the CFP has been allocated
2113 if (!cfp) {
2114 return 0;
2115 }
2116
2117 // Skip dummy frame; see `rb_ec_partial_backtrace_object` for details
2118 end_cfp = RUBY_VM_NEXT_CONTROL_FRAME(end_cfp);
2119
2120 for (i=0; i<limit && cfp != end_cfp; cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)) {
2121 if (VM_FRAME_RUBYFRAME_P_UNCHECKED(cfp) && CFP_PC(cfp)) {
2122 if (start > 0) {
2123 start--;
2124 continue;
2125 }
2126
2127 /* record frame info */
2128 cme = rb_vm_frame_method_entry_unchecked(cfp);
2129 const rb_iseq_t *iseq = CFP_ISEQ(cfp);
2130 if (cme && cme->def->type == VM_METHOD_TYPE_ISEQ) {
2131 buff[i] = (VALUE)cme;
2132 }
2133 else {
2134 buff[i] = (VALUE)iseq;
2135 }
2136
2137 if (lines) {
2138 const VALUE *pc = CFP_PC(cfp);
2139 VALUE *iseq_encoded = ISEQ_BODY(iseq)->iseq_encoded;
2140 VALUE *pc_end = iseq_encoded + ISEQ_BODY(iseq)->iseq_size;
2141
2142 // The topmost frame may have an invalid PC because the JIT
2143 // may leave it uninitialized for speed. JIT code must update the PC
2144 // before entering a non-leaf method (so that `caller` will work),
2145 // so only the topmost frame could possibly have an out-of-date PC.
2146 // Avoid passing invalid PC to calc_lineno() to avoid crashing.
2147 if (cfp == top && (pc < iseq_encoded || pc > pc_end)) {
2148 lines[i] = 0;
2149 }
2150 else {
2151 lines[i] = calc_lineno(iseq, pc);
2152 }
2153 }
2154
2155 i++;
2156 }
2157 else {
2158 cme = rb_vm_frame_method_entry_unchecked(cfp);
2159 if (cme && cme->def->type == VM_METHOD_TYPE_CFUNC) {
2160 if (start > 0) {
2161 start--;
2162 continue;
2163 }
2164 buff[i] = (VALUE)cme;
2165 if (lines) lines[i] = 0;
2166 i++;
2167 }
2168 }
2169 }
2170
2171 return i;
2172}
2173
2174int
2175rb_profile_frames(int start, int limit, VALUE *buff, int *lines)
2176{
2177 rb_execution_context_t *ec = rb_current_execution_context(false);
2178
2179 // If there is no EC, we may be attempting to profile a non-Ruby thread or a
2180 // M:N shared native thread which has no active Ruby thread.
2181 if (!ec) {
2182 return 0;
2183 }
2184
2185 return thread_profile_frames(ec, start, limit, buff, lines);
2186}
2187
2188int
2189rb_profile_thread_frames(VALUE thread, int start, int limit, VALUE *buff, int *lines)
2190{
2191 rb_thread_t *th = rb_thread_ptr(thread);
2192 return thread_profile_frames(th->ec, start, limit, buff, lines);
2193}
2194
2195static const rb_iseq_t *
2196frame2iseq(VALUE frame)
2197{
2198 if (NIL_P(frame)) return NULL;
2199
2200 if (RB_TYPE_P(frame, T_IMEMO)) {
2201 switch (imemo_type(frame)) {
2202 case imemo_iseq:
2203 return (const rb_iseq_t *)frame;
2204 case imemo_ment:
2205 {
2206 const rb_callable_method_entry_t *cme = (rb_callable_method_entry_t *)frame;
2207 switch (cme->def->type) {
2208 case VM_METHOD_TYPE_ISEQ:
2209 return cme->def->body.iseq.iseqptr;
2210 default:
2211 return NULL;
2212 }
2213 }
2214 default:
2215 break;
2216 }
2217 }
2218 rb_bug("frame2iseq: unreachable");
2219}
2220
2221VALUE
2223{
2224 const rb_iseq_t *iseq = frame2iseq(frame);
2225 return iseq ? rb_iseq_path(iseq) : Qnil;
2226}
2227
2228static const rb_callable_method_entry_t *
2229cframe(VALUE frame)
2230{
2231 if (NIL_P(frame)) return NULL;
2232
2233 if (RB_TYPE_P(frame, T_IMEMO)) {
2234 switch (imemo_type(frame)) {
2235 case imemo_ment:
2236 {
2237 const rb_callable_method_entry_t *cme = (rb_callable_method_entry_t *)frame;
2238 switch (cme->def->type) {
2239 case VM_METHOD_TYPE_CFUNC:
2240 return cme;
2241 default:
2242 return NULL;
2243 }
2244 }
2245 default:
2246 return NULL;
2247 }
2248 }
2249
2250 return NULL;
2251}
2252
2253VALUE
2255{
2256 if (cframe(frame)) {
2257 static VALUE cfunc_str = Qfalse;
2258 if (!cfunc_str) {
2259 cfunc_str = rb_str_new_literal("<cfunc>");
2260 rb_vm_register_global_object(cfunc_str);
2261 }
2262 return cfunc_str;
2263 }
2264 const rb_iseq_t *iseq = frame2iseq(frame);
2265 return iseq ? rb_iseq_realpath(iseq) : Qnil;
2266}
2267
2268VALUE
2270{
2271 const rb_iseq_t *iseq = frame2iseq(frame);
2272 return iseq ? rb_iseq_label(iseq) : Qnil;
2273}
2274
2275VALUE
2277{
2278 const rb_iseq_t *iseq = frame2iseq(frame);
2279 return iseq ? rb_iseq_base_label(iseq) : Qnil;
2280}
2281
2282VALUE
2284{
2285 const rb_iseq_t *iseq = frame2iseq(frame);
2286 return iseq ? rb_iseq_first_lineno(iseq) : Qnil;
2287}
2288
2289static VALUE
2290frame2klass(VALUE frame)
2291{
2292 if (NIL_P(frame)) return Qnil;
2293
2294 if (RB_TYPE_P(frame, T_IMEMO)) {
2295 const rb_callable_method_entry_t *cme = (rb_callable_method_entry_t *)frame;
2296
2297 if (imemo_type(frame) == imemo_ment) {
2298 return cme->defined_class;
2299 }
2300 }
2301 return Qnil;
2302}
2303
2304VALUE
2306{
2307 VALUE klass = frame2klass(frame);
2308
2309 if (klass && !NIL_P(klass)) {
2310 if (RB_TYPE_P(klass, T_ICLASS)) {
2311 klass = RBASIC(klass)->klass;
2312 }
2313 else if (RCLASS_SINGLETON_P(klass)) {
2314 klass = RCLASS_ATTACHED_OBJECT(klass);
2315 if (!RB_TYPE_P(klass, T_CLASS) && !RB_TYPE_P(klass, T_MODULE))
2316 return rb_sprintf("#<%s:%p>", rb_class2name(rb_obj_class(klass)), (void*)klass);
2317 }
2318 return rb_class_path(klass);
2319 }
2320 else {
2321 return Qnil;
2322 }
2323}
2324
2325VALUE
2327{
2328 VALUE klass = frame2klass(frame);
2329
2330 return RBOOL(klass && !NIL_P(klass) && RCLASS_SINGLETON_P(klass));
2331}
2332
2333VALUE
2335{
2336 const rb_callable_method_entry_t *cme = cframe(frame);
2337 if (cme) {
2338 ID mid = cme->def->original_id;
2339 return id2str(mid);
2340 }
2341 const rb_iseq_t *iseq = frame2iseq(frame);
2342 return iseq ? rb_iseq_method_name(iseq) : Qnil;
2343}
2344
2345static VALUE
2346qualified_method_name(VALUE frame, VALUE method_name)
2347{
2348 if (method_name != Qnil) {
2349 VALUE classpath = rb_profile_frame_classpath(frame);
2350 VALUE singleton_p = rb_profile_frame_singleton_method_p(frame);
2351
2352 if (classpath != Qnil) {
2353 return rb_sprintf("%"PRIsVALUE"%s%"PRIsVALUE,
2354 classpath, singleton_p == Qtrue ? "." : "#", method_name);
2355 }
2356 else {
2357 return method_name;
2358 }
2359 }
2360 else {
2361 return Qnil;
2362 }
2363}
2364
2365VALUE
2367{
2368 VALUE method_name = rb_profile_frame_method_name(frame);
2369
2370 return qualified_method_name(frame, method_name);
2371}
2372
2373VALUE
2375{
2376 const rb_callable_method_entry_t *cme = cframe(frame);
2377 if (cme) {
2378 ID mid = cme->def->original_id;
2379 VALUE method_name = id2str(mid);
2380 return qualified_method_name(frame, method_name);
2381 }
2382
2383 VALUE label = rb_profile_frame_label(frame);
2384 VALUE base_label = rb_profile_frame_base_label(frame);
2385 VALUE qualified_method_name = rb_profile_frame_qualified_method_name(frame);
2386
2387 if (NIL_P(qualified_method_name) || base_label == qualified_method_name) {
2388 return label;
2389 }
2390 else {
2391 rb_len_t label_length = RSTRING_LEN(label);
2392 rb_len_t base_label_length = RSTRING_LEN(base_label);
2393 int prefix_len = rb_len2int(label_length - base_label_length);
2394
2395 return rb_sprintf("%.*s%"PRIsVALUE, prefix_len, RSTRING_PTR(label), qualified_method_name);
2396 }
2397}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
int rb_profile_frames(int start, int limit, VALUE *buff, int *lines)
Queries mysterious "frame"s of the given range.
VALUE rb_debug_inspector_frame_binding_get(const rb_debug_inspector_t *dc, rb_len_t index)
Queries the binding of the passed context's upper frame.
VALUE rb_profile_frame_full_label(VALUE frame)
Identical to rb_profile_frame_label(), except it returns a qualified result.
struct rb_debug_inspector_struct rb_debug_inspector_t
Opaque struct representing a debug inspector.
Definition debug.h:207
VALUE rb_debug_inspector_current_depth(void)
Return current frame depth.
VALUE rb_debug_inspector_frame_depth(const rb_debug_inspector_t *dc, rb_len_t index)
Queries the depth of the passed context's upper frame.
VALUE rb_profile_frame_method_name(VALUE frame)
Queries the name of the method of the passed frame.
VALUE rb_profile_frame_qualified_method_name(VALUE frame)
Identical to rb_profile_frame_method_name(), except it "qualifies" the return value with its defining...
VALUE rb_profile_frame_label(VALUE frame)
Queries human-readable "label" string.
VALUE rb_profile_frame_singleton_method_p(VALUE frame)
Queries if the method of the passed frame is a singleton class.
VALUE rb_debug_inspector_backtrace_locations(const rb_debug_inspector_t *dc)
Queries the backtrace object of the context.
VALUE rb_profile_frame_absolute_path(VALUE frame)
Identical to rb_profile_frame_path(), except it tries to expand the returning path.
VALUE rb_debug_inspector_open(rb_debug_inspector_func_t func, void *data)
Prepares, executes, then cleans up a debug session.
VALUE rb_debug_inspector_frame_class_get(const rb_debug_inspector_t *dc, rb_len_t index)
Queries the current class of the passed context's upper frame.
VALUE rb_debug_inspector_frame_iseq_get(const rb_debug_inspector_t *dc, rb_len_t index)
Queries the instruction sequence of the passed context's upper frame.
VALUE rb_profile_frame_classpath(VALUE frame)
Queries the class path of the method that the passed frame represents.
VALUE rb_profile_frame_path(VALUE frame)
Queries the path of the passed backtrace.
VALUE rb_profile_frame_first_lineno(VALUE frame)
Queries the first line of the method of the passed frame pointer.
VALUE rb_debug_inspector_frame_self_get(const rb_debug_inspector_t *dc, rb_len_t index)
Queries the current receiver of the passed context's upper frame.
int rb_profile_thread_frames(VALUE thread, int start, int limit, VALUE *buff, int *lines)
Queries mysterious "frame"s of the given range.
VALUE(* rb_debug_inspector_func_t)(const rb_debug_inspector_t *dc, void *data)
Type of the callback function passed to rb_debug_inspector_open().
Definition debug.h:218
VALUE rb_profile_frame_base_label(VALUE frame)
Identical to rb_profile_frame_label(), except it does not "qualify" the result.
VALUE rb_enc_sprintf(rb_encoding *enc, const char *fmt,...)
Identical to rb_sprintf(), except it additionally takes an encoding.
Definition sprintf.c:1254
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2907
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3394
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3183
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition value_type.h:67
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#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 ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define NUM2LEN
Old name of RB_NUM2LEN.
Definition len_t.h:34
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define rb_notimplement()
Definition flock.c:3
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
VALUE rb_cArray
Array class.
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_cThread
Thread class.
Definition vm.c:719
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
Encoding relates APIs.
VALUE rb_ary_reverse(VALUE ary)
Destructively reverses the passed array in-place.
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
Public APIs related to rb_cIO.
VALUE rb_io_gets(VALUE io)
Reads a "line" from the given IO.
Definition io.c:4562
VALUE rb_file_open_str(VALUE fname, const char *fmode)
Identical to rb_file_open(), except it takes the pathname as a Ruby's string instead of C's.
Definition io.c:7582
VALUE rb_io_close(VALUE io)
Closes the IO.
Definition io.c:6034
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition marshal.c:139
VALUE rb_range_beg_len(VALUE range, rb_len_t *begp, rb_len_t *lenp, rb_len_t len, int err)
Deconstructs a numerical range.
Definition range.c:1949
#define rb_str_new_literal(str)
Just another name of rb_str_new_lit.
Definition string.h:1775
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3959
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
Definition string.c:9427
VALUE rb_str_buf_new(rb_len_t capa)
Allocates a "string buffer".
Definition string.c:1788
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1681
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition variable.c:397
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1904
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_make_backtrace(void)
Creates the good old fashioned array-of-strings style backtrace info.
void rb_backtrace(void)
Prints the backtrace out to the standard error.
int len
Length of the buffer.
Definition io.h:8
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1396
#define rb_len2int
Just another name of rb_len2int_inline.
Definition len_t.h:37
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
VALUE type(ANYARGS)
ANYARGS-ed function type.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:398
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RUBY_DEFAULT_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:56
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
static int RSTRING_LENINT(VALUE str)
Identical to RSTRING_LEN(), except it differs for the return type.
Definition rstring.h:438
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:81
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
const char * rb_class2name(VALUE klass)
Queries the name of the passed class.
Definition variable.c:523
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition method.h:143
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.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