blib/lib/Devel/DebugHooks.pm untested

filter: Statementstmt 0.0% 0 / 611 Branchbran 0.0% 0 / 258 Conditioncond 0.0% 0 / 166 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 86 Podpod 0.0% 0 / 69 totaltotal 0.0% 0 / 1190 CC 136 SCAR 38.6
CC
136
Cov
0%
state
210.0
frames
182.0
scall
132.0
CRAP 47.3
1 package Devel::DebugHooks;
2  
3 BEGIN {
4 if( $DB::options{ w } ) { require 'warnings.pm'; 'warnings'->import(); }
5 if( $DB::options{ s } ) { require 'strict.pm'; 'strict'->import(); }
6 if( $options{ d } ) { require 'Data/Dump.pm'; 'Data::Dump'->import( 'pp'); }
7 }
8  
9  
10 our $VERSION = '0.04.01';
11  
12 =head1 NAME
13  
14 C<Devel::DebugHooks> - Hooks for perl debugger
15  
16 =head1 SYNOPSIS
17  
18 perl -d:DebugHooks::Terminal script.pl
19  
20 ## If you want to debug remotely you required additionally install IO::Async
21 # on remote
22 perl -d:DebugHooks::Server script.pl
23 # on local
24 ./dclient.pl 1.2.3.4 9000
25  
26 =cut
27  
28  
29 # We should init $DB::dbg as soon as possible, because if trace_subs/load are
30 # enabled at compile time (at the BEGIN block) the DB:: module will make call
31 # to $dbg->trace_subs/load. Also these subs should be declared before the
32 # 'use Devel::DebugHooks' in other case you will get:
33 # 'Call to undefined sub YourModule::trace_subs/load is made...'
34 # That is because perl internals make calls to DB::* as soon as the subs in it
35 # are compiled even whole file is not processed yet.
36 # Also do not forget to 'push @ISA, "YourModule"' if you set these DB:: options at
37 # compile time: trace_load, trace_subs,
38 BEGIN {
39 unless( defined $DB::dbg ) {
40 my $level = 0;
41 while( my $frame = caller($level++) ) {
42 $DB::dbg = $frame if $frame =~ /^Devel::/;
43 }
44  
45 $DB::dbg //= __PACKAGE__;
46  
47 # ISSUE: We can not make 'main' package as descendant of 'Devel::DebugHooks'
48 # because of broken info from 'caller', so I restrict pkg_names to 'Devel::'
49 # TODO: Ask #p5p about that 'caller' shows strange file:line for (eval)
50 # https://rt.perl.org/Public/Bug/Display.html?id=127083
51 }
52 }
53  
54  
55  
56 sub pop_frame {
57 #NOTICE: We will fall into infinite loop if something dies inside this sub
58 #because this sub is called when flow run out of scope.
59 #TODO: Put this code into eval block
60  
61 my $stack = DB::state( 'stack' );
62 my $last = pop @$stack;
63 DB::print_state( "POP FRAME <<<< ",
64 " -- $last->{ sub }\@". @$stack ."\n"
65 ." $last->{ file }:$last->{ line }\n\n"
66 ) if DB::state( 'ddd' );
67  
68 if( @{ DB::state( 'stack' ) } ) {
69 # Restore $DB::single for upper frame
70 DB::state( 'single', DB::state( 'single' ) );
71 } else {
72 # Something nasty happened at &push_frame, because of we are at
73 # &pop_frame already but not "push @{ state( 'stack' ) }" done yet
74 print $DB::OUT "Error happen while &pop_frame. Pay attention to this!\n";
75 $DB::single = 0;
76 }
77 }
78  
79  
80  
81 {
82 my $handler = DB::reg( 'pop_frame', 'DebugHooks' );
83 $$handler->{ context } = $DB::dbg;
84 $$handler->{ code } = \&pop_frame;
85 }
86  
87  
88  
89  
90 sub test {
91 1;
92 2;
93 }
94  
95  
96  
97 sub push_frame {
98 { # these lines exists for testing purpose
99 no warnings 'void';
100 test();
101 3;
102 }
103  
104 shift; #Turf event context
105 my $sub = shift;
106 DB::print_state( "PUSH FRAME $_[0] >>>> ", " -- $sub\n" ) if DB::state( 'ddd' );
107  
108 if( $_[0] ne 'G' ) {
109 # http://stackoverflow.com/questions/34595192/how-to-fix-the-dbgoto-frame
110 # WORKAROUND: for broken frame. Here we are trying to be closer to goto call
111 # Most actual info we get when we trace script step-by-step at this case
112 # those vars have sharp last opcode location.
113 if( !DB::state( 'eval' ) ) {
114 #TODO: If $DB::single == 1 we can skip this because cursor is updated at DB::DB
115 my( $p, $f, $l ) = caller 5;
116 DB::state( 'package', $p );
117 DB::state( 'file', $f );
118 DB::state( 'line', $l );
119 DB::print_state( "", sprintf "\n cursor(PF) => %s, %s, %s\n" ,$p ,$f, $l ) if DB::state( 'ddd' );
120 }
121  
122 my $stack = DB::state( 'stack' );
123 my $frame = {()
124 # Until we stop at a callee last known cursor position is the caller position
125 ,package => $stack->[-1]{ package }
126 ,file => $stack->[-1]{ file }
127 ,line => $stack->[-1]{ line }
128 ,single => $stack->[-1]{ single }
129 ,sub => $sub
130 ,goto_frames => []
131 ,type => $_[0]
132 };
133  
134  
135 DB::emit( 'frame', $frame );
136  
137 #TODO: Now we push always. Q: How to skip coresopnding &pop_frame?
138 # Think about this feature: if( $confirm ) {
139 push @{ $stack }, $frame;
140 }
141 else {
142 push @{ DB::state( 'goto_frames' ) },
143 [ DB::state( 'package' ), DB::state( 'file' ), DB::state( 'line' ), $sub, $_[0] ]
144 }
145  
146  
147 DB::emit( 'call', $sub );
148 1;
149 }
150  
151  
152  
153 {
154 my $handler = DB::reg( 'push_frame', 'DebugHooks' );
155 $$handler->{ context } = $DB::dbg;
156 $$handler->{ code } = \&push_frame;
157 }
158  
159  
160  
161 # NOTICE: We do not inherit DB:: interface, we use it
162 sub import {
163 if( $_[0] eq 'Devel::DebugHooks' ) {
164 shift;
165 for my $module ( @_ ) {
166 my( $package, $args ) = $module =~ m/^([^=]+)=?(.*)$/;
167 $DB::dbg = "Devel::DebugHooks::$package";
168 $package =~ s/::/\//;
169 require "Devel/DebugHooks/$package.pm";
170 $DB::dbg->import( split ':', $args );
171 }
172 }
173 else {
174 DB::import( @_ );
175 }
176 # shift->SUPER::import( @_ );
177 }
178  
179  
180  
181 package
182 x;
183  
184 sub x { # This is 'invader' :)
185 # When we returns from this sub the $DB::single is restored at 'DB::sub_returns'
186 DB::state( 'stack' )->[-1]{ single } = 1 if !@_ || $_[0];
187 # TODO: Allow to disable trap
188 }
189  
190 # NOTICE: x::x; does not work at the end of sub
191  
192 package
193 X;
194 sub X {
195 local $^D |= (1<<30);
196 DB::state( 'stack' )->[-1]{ single } = 1;
197 DB::state( 'single', 1 );
198 1;
199 }
200  
201  
202  
203 package DB::Error;
204 use overload bool => sub {1}, '""' => sub { shift->error }, fallback => 1;
205  
206 sub error {
207 return shift->{ error };
208 }
209  
210  
211 package DB;
212  
213 # In theory this may break user's code because this usage cause dependencies are loaded
214 # in different order under debugger
215 use Scope::Cleanup qw/ establish_cleanup /;
216 use Sub::Metadata qw/ mutate_sub_is_debuggable /;
217 use List::Util;
218  
219 BEGIN {
220 # https://metacpan.org/pod/release/PEVANS/Scalar-List-Utils-1.27/lib/List/Util.pm#SUGGESTED-ADDITIONS
221 # Perl <=5.18 have List::Utils 1.27 which have not next functions:
222 $List::Util::VERSION <= 1.27 && eval '
223 sub List::Util::any(&@) { my $sub = shift; $sub->() && return 1 for @_; 0 }
224 sub List::Util::all(&@) { my $sub = shift; $sub->() || return 0 for @_; 1 }
225 ';
226 }
227  
228  
229  
230 ## Utility subs
231 sub orig_frames {
232 BEGIN{ 'warnings'->unimport( 'uninitialized' ) if $DB::options{ w } }
233 my( $count, $warn ) = @_;
234 $count //= -1; # infinite
235  
236 my $lvl = 0;
237 # $x && $y = 3 in this case '=' op precedence should be higher then &&
238 while( $count-- && (my @frame = caller( $lvl++ )) ) {
239 $_ = "@frame[0..3,5]\n";
240 print $DB::OUT $_ unless $warn;
241 warn $_ if $warn;
242 }
243  
244 print $DB::OUT "\n" unless $warn;
245 }
246  
247  
248 # This sub is called twice: at compile time and before run time of 'main' package
249 sub applyOptions {
250 # Q: is warn expected when $DB::trace == undef?
251 $DB::trace = $DB::options{ trace_line } || 0
252 if defined $DB::options{ trace_line };
253  
254 $^P &= ~0x20 if $DB::options{ NonStop };
255 DB::state( 'single', 1 ) if $DB::options{ Stop };
256 }
257  
258  
259  
260 sub print_state {
261 my( $before, $after ) = @_;
262  
263 local $DB::state->[ -1 ]{ ddd };
264  
265 my( undef, $f, $l ) = caller;
266 print $DB::OUT
267 $before
268 ."DB::state: l:" .@$DB::state ." d:" .(DB::state('inDB')//0)
269 ." s:$DB::single t:$DB::trace"
270 ." $f:$l"
271 .($after // "\n")
272 ;
273 }
274  
275  
276  
277 sub log_access {
278 my( $debug, $context, $hash, $name, $value ) = @_;
279  
280 my $old_value = $hash->{ $name } // 'undef';
281 my $new_value = '';
282 if( @_ >= 5 ) {
283 $new_value = ' -> '. ($value//'undef');
284 defined $value
285 ? $hash->{ $name } = $value
286 : delete $hash->{ $name };
287 }
288  
289 if( $debug && ( @_ >= 5 || $debug >= 2 ) ) {
290 # We are not interested at address of value only its state
291 # Also this makes life happy when we compare diff for two debugger output
292 $old_value = ref $old_value ? ref $old_value : $old_value;
293 $new_value = ref $new_value ? ref $new_value : $new_value;
294 print $DB::OUT " ${context}::$name: $old_value$new_value\n";
295 }
296  
297  
298 return $hash->{ $name };
299 }
300  
301  
302  
303 sub int_vrbl {
304 my( $self, $name, $value, $preserve_frame ) = @_;
305  
306 #TODO: do not affect current debugger state if we are { inDB } mode
307 if( @_ >= 3 ) {
308 no strict "refs";
309 if( $self->{ debug } ) {
310 print $DB::OUT " ( DB::$name: ${ \"DB::$name\" } -> $value )";
311 $self->{ debug }++ if $preserve_frame;
312 }
313  
314 ${ "DB::$name" } = $value;
315 }
316  
317  
318 return frm_vrbl( $self, $name, (@_>=3 && !$preserve_frame ? $value : ()) );
319 }
320  
321  
322  
323 sub dbg_vrbl {
324 my $self = shift;
325  
326 my $dbg = $self->{ instance } // $DB::state->[-1];
327  
328 return log_access( $self->{ debug }, 'DBG', $dbg, @_ );
329 }
330  
331  
332  
333 sub frm_vrbl {
334 my $self = shift;
335  
336 my $frame;
337 {
338 local $self->{ debug };
339 $frame = dbg_vrbl( $self, 'stack' )->[ -1 ];
340 }
341  
342 return log_access( $self->{ debug }, 'FRM', $frame, @_ );
343 }
344  
345  
346  
347 mutate_sub_is_debuggable( \&state, 0 );
348 sub state {
349 return unless $DB::state && @$DB::state;
350  
351 my( $name, $value ) = @_;
352  
353 # Do not debug access into 'ddd' flag
354 my $debug = $name ne 'ddd' && $DB::state->[ -1 ]{ ddd } // 0;
355 # If we run debugger command do not trace access to debugger state
356 $debug -= 3 if $DB::state->[ -1 ]{ cmd } && $name ne 'cmd';
357 $debug = 0 if $debug < 0;
358  
359 # Show full stack only when verbose mode ON and only before changes
360 # or before implicit changes: when debugger command take whole 'stack'
361 # and manipulate data directly
362 if( $debug && (($debug >= 3 && @_ >= 2) || $name eq 'stack' ) ) {
363 print_state "\n ";
364  
365 for( @$DB::state ) {
366 print $DB::OUT " ***\n";
367 for my $option ( sort keys %$_ ) {
368 my $value = $_->{ $option };
369 $value = ref $value ? ref $value : $value;
370 print $DB::OUT ' ', $option, " = $value\n";
371 }
372 my $CNT = 5;
373 for( @{ $_->{ stack } } ) {
374 last if $CNT-- == 0;
375 print $DB::OUT " ";
376 for my $key ( sort keys %$_ ) {
377 my $value = $_->{ $key };
378 $value = ref $value ? ref $value : $value;
379 print $DB::OUT " $key => $value;";
380 }
381 print $DB::OUT "\n";
382 }
383 }
384  
385 print $DB::OUT ' ', '-'x20 ."\n";
386 }
387  
388 # Force access into last instance if we are in debugger
389 my $inDB = $DB::state->[ -1 ]{ inDB };
390 my $level = -1;
391 $level = -2 if @$DB::state >= 2 && !$inDB && $name ne 'inDB';
392 my $instance = $DB::state->[ $level ];
393  
394 if( $debug && ( @_ >= 2 || $debug >= 2 ) ) {
395 my($file, $line) = (caller 0)[1,2];
396 $file =~ s'.*?([^/]+)$'$1'e;
397 print $DB::OUT " " .-$level ." $file:$line: ";
398 }
399  
400 unless( $instance ) {
401 my($file, $line) = (caller 0)[1,2];
402 $file =~ s'.*?([^/]+)$'$1'e;
403 print $DB::OUT "!!!!!! No debugger at level: $level at $file:$line<<<<<<<<<\n";
404 return;
405 }
406  
407  
408  
409 if( $name eq 'instance' ) {
410 print $DB::OUT " INT::instance\n" if $debug && ( @_ >= 2 || $debug >= 2 );
411 return $instance;
412 }
413  
414 $name = '*' unless exists $DB::variables->{ $name };
415 return $DB::variables->{ $name }({()
416 ,debug => $debug
417 ,instance => $instance
418 }
419 ,@_
420 );
421 }
422  
423  
424  
425 sub _ddd {
426 return $DB::state->[ -1 ]{ ddd };
427 }
428  
429  
430  
431 sub new {
432 my $ddd = DB::state( 'ddd' );
433  
434 # NOTICE: After creating new debugger instance we are in debugger yet
435 # So we set { inDB } flag. It allows us safely initialize new debugger
436 # instance through &DB::state ( see &DB::state ). We do not do that directly
437 # to spy which state and how it is changed when { ddd } is turned on
438 my $dbg_instance = bless { inDB => 1, stack => [ {()
439 ,goto_frames => []
440 # ,type => 'D'
441 } ], @_ }, $DB::dbg;
442 push @$DB::state, $dbg_instance;
443  
444 # New debugger instance should have same { ddd } flag
445 # DB::state( 'ddd', $ddd ) if defined $ddd;
446  
447 if( @$DB::state > 1 ) {
448 my @events = grep{ /^on_/ } keys %{ $DB::state->[-2] };
449 @{ $DB::state->[-1] }{ @events } = @{ $DB::state->[-2] }{ @events };
450 }
451  
452 print $DB::OUT "\nIN DEBUGGER >>>>>>>>>>>>>>>>>>>>>>\n\n"
453 if DB::state( 'ddd' );
454  
455 my $self;
456 }
457  
458  
459  
460 sub DESTROY {
461 # Clear { dd } flag to prevent debugging for next command
462 DB::state( 'dd', undef );
463 DB::state( 'debug', undef );
464  
465 print $DB::OUT "\nOUT DEBUGGER <<<<<<<<<<<<<<<<<<<<<<\n\n"
466 if _ddd;
467 pop @$DB::state;
468 # NOTICE: previous frame is always have { inDB } flag on because there is
469 # no any way to run new debugger instance as from debugger
470 # (See &DB::scall and assert { inDB } check)
471 }
472  
473  
474  
475 # Used perl internal variables:
476 # ${ ::_<filename } # maintained at 'file' and 'sources'
477 # @{ ::_<filename } # maintained at 'source' and 'can_break'
478 # %{ ::_<filename } # maintained at 'traps'
479 # $DB::single
480 # $DB::signal
481 # $DB::trace
482 # $DB::sub # NOTICE: this maybe the reference to sub, not just the name of it
483 # %DB::sub # maintained at 'location' and 'subs'
484 # %DB::postponed
485 # @DB::args # maintained at 'frames'
486  
487 # Perl sets up $DB::single to 1 after the 'script.pl' is compiled, so we are able
488 # to debug it from first OP. We can disable this feature through NonStop option.
489  
490 our $dbg; # debugger object/class
491 # our $package; # current package
492 # our $file; # current file
493 # our $line; # current line number
494 # our @goto_frames; # save sequence of places where nested gotos are called
495 our $commands; # hash of commands to interact user with debugger
496 # our @stack; # array of hashes that keeps aliases of DB::'s ours for current frame
497 # This allows us to spy the DB::'s values for a given frame
498 # our $ddlvl; # Level of debugger debugging <= @$DB::state
499 # our $dbg_call; # keep silent at DB::sub/lsub while do external call from DB::*
500 # our $inDB; # Flag which shows we are currently in debugger
501 # our $inSUB; # Flag which shows we are currently in debugger
502 # TODO? does it better to implement TTY object?
503 our $IN;
504 our $OUT;
505 our %options;
506 our $interaction; # True if we interact with dbg client
507 our $variables; # Hash which defines behaviour for values available through &DB::state
508 # There three types of variables:
509 # Debugger internal variables -- global values from DB:: package
510 # Debugger instance variables -- values which exists in current debugger instance
511 # Frame variables -- values for each sub call
512  
513  
514  
515 # Do DB:: configuration stuff here
516 # Default debugger behaviour while it is loading
517 BEGIN {
518 $DB::variables = {()
519 ,'*' => \&dbg_vrbl
520 ,single => \&int_vrbl
521 ,on_frame => \&frm_vrbl
522 ,file => \&frm_vrbl
523 ,goto_frames => \&frm_vrbl
524 ,line => \&frm_vrbl
525 ,package => \&frm_vrbl
526 ,sub => \&frm_vrbl
527 ,type => \&frm_vrbl
528 ,eval => \&frm_vrbl
529 };
530  
531  
532 $IN //= \*STDIN;
533 #TODO: cache output until debugger is connected
534 $OUT //= \*STDOUT;
535  
536 #FIX: Where apply 'ddd' from command line?
537 DB::new;
538 DB::state( single => $DB::single );
539  
540 $options{ undef } //= ''; # Text to print for undefined values
541  
542 # $options{ dd } //= 0; # controls debugger debugging
543 # $options{ ddd } //= 0; # print debug info
544  
545 $options{ s } //= 0; # compile time option
546 $options{ w } //= 0; # compile time option
547 # TODO: camelize options. Q: Why?
548 $options{ frames } //= -1; # compile time & runtime option
549 $options{ dbg_frames } //= 0; # compile time & runtime option
550  
551 #options{ save_path } # TODO: save code path for displaying by graphviz
552 $DB::postponed{ 'DB::DB' } = 1;
553  
554 #NOTE: we should always trace goto frames. Hiding them will prevent
555 # us to complete our work - debugging.
556 # But we still allow to control this behaviour at compiletime & runtime
557 # $options{ trace_goto }; #see DH:import # compile time & runtime option
558 $^P |= 0x80;
559 }
560  
561 # TODO: describe qw/ frames dbg_frames trace_load trace_subs
562 # trace_returns / options
563  
564  
565 # $options{ NonStop } - if true then 0x20 flag is flushed
566  
567  
568  
569  
570 # $^P default values
571 # ! x
572 # 0111 0011 1111
573 # |||| |||| |||^-- Debug subroutine enter/exit.
574 # |||| |||| ||^--- Line-by-line debugging.
575 # |||| |||| |^---- Switch off optimizations.
576 # |||| |||| ^----- Preserve more data for future interactive inspections.
577 # |||| ||||
578 # |||| |||^------- Keep info about source lines on which a subroutine is defined.
579 # |||| ||^-------- Start with single-step on.
580 # |||| |^--------- Use subroutine address instead of name when reporting.
581 # |||| ^---------- Report goto &subroutine as well.
582 # ||||
583 # |||^------------ Provide informative "file" names for evals based on the place they were compiled.
584 # ||^------------- Provide informative names to anonymous subroutines based on the place they were compiled.
585 # |^-------------- Save source code lines into @{"_<$filename"}.
586 # ^--------------- When saving source, include evals that generate no subroutines.
587 # < When saving source, include source that did not compile.
588  
589  
590  
591 # NOTICE: it is better to not use any modules from this one
592 # because we do not want that they appear to compiler before
593 # we can track module loading and subs calling process
594 # Also it is safe that descendant debugger module 'use' us. BUT BE AWARE!!!
595 # That module should not use any module before this one
596 # otherwise sub calls and module loading will not be tracked
597 #
598 # When we 'use' descendant debugger at the end our module appears last at load chain.
599 # Also there is a problem how to pass descendant class name to 'use' it.
600 # Keep this comment for history. Find this commit at 'git blame' to see what was changed
601 BEGIN {
602 if( $options{ w } ) { require 'warnings.pm'; 'warnings'->import(); }
603 if( $options{ s } ) { require 'strict.pm'; 'strict'->import(); }
604 if( $options{ d } ) { require 'Data/Dump.pm'; 'Data::Dump'->import( 'pp'); }
605 # http://perldoc.perl.org/warnings.html
606 # The scope of the strict/warnings pragma is limited to the enclosing block.
607 # But this not truth.
608 # It is limited to the first enclosing block of the BEGIN block
609 }
610  
611  
612 # NOTICE: Because of DB::DB, DB::sub, DB::postpone etc. subs take effect
613 # as soon as compiled we should &applyOptions at compile time
614 BEGIN { # Initialization goes here
615 # When we 'use Something' from this module the DB::sub is called at compile time
616 # If we do not we can still init them when define
617 $DB::interaction //= 0;
618 # TODO: set $DB::trace at CT
619  
620 # Some configuration options may be applied when debugger is loading
621 # When debugger is loaded its &import subroutine will be called (see comment there)
622 applyOptions();
623 }
624  
625  
626  
627 # Hooks to Perl's internals should be first.
628 # Because debugger or its descendants may call them at compile time
629 {
630 {
631 BEGIN{ 'strict'->unimport( 'refs' ) if $options{ s } }
632  
633 sub dd {
634 eval "use Data::Dump";
635 Data::Dump::pp( @_ );
636 }
637  
638  
639  
640 # Returns TRUE if $filename was compiled/evaled
641 # The file is evaled if it looks like (eval 34)
642 # But this may be changed by #file:line. See ??? for info
643 sub file {
644 my $filename = shift // state( 'file' );
645  
646 unless( exists ${ 'main::' }{ "_<$filename" } ) {
647 warn "File '$filename' is not compiled yet";
648  
649 return;
650 }
651  
652 return ${ "::_<$filename" };
653 }
654  
655  
656  
657 # Returns source for $filename
658 sub source {
659 my $filename = shift // state( 'file' );
660  
661 return unless file( $filename );
662  
663 return \@{ "::_<$filename" };
664 }
665  
666  
667  
668 # Returns list of compiled files/evaled strings
669 # The $filename for evaled strings looks like (eval 34)
670 sub sources {
671 return grep{ s/^_<// } keys %{ 'main::' }; #/
672 }
673  
674 sub deparse {
675 my( $coderef ) = shift;
676 require B::Deparse;
677 return $coderef unless ref $coderef;
678 return B::Deparse->new("-p", "-sC")->coderef2text( $coderef );
679 }
680  
681  
682  
683 # Returns hashref of traps for $filename keyed by $line
684 sub traps {
685 #TODO: remove default because current position != view position
686 # this makes confusion
687 my $filename = shift // state( 'file' );
688  
689 return unless file( $filename );
690  
691 # Keep list of $filenames we perhaps manipulate traps
692 $DB::_tfiles->{ $filename } = 1;
693  
694 *dbline = $main::{ "_<$filename" }; #WORKRAOUND RT#119799 (see commit)
695  
696 return \%{ "::_<$filename" };
697 }
698  
699  
700  
701 # Returns TRUE if we can set trap for $file:line
702 sub can_break {
703 my( $file, $line ) = @_;
704  
705 ($file, $line) = split ':', $file
706 unless defined $line;
707  
708 return unless defined( $file = file( $file ) );
709  
710 # TODO: testcase for negative lines
711 return ($line<0?-$line-1:$line) <= $#{ "::_<$file" }
712 && ${ "::_<$file" }[ $line ] != 0;
713  
714 # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
715 # Values in this array are magical in numeric context:
716 # they compare equal to zero only if the line is not breakable.
717 }
718 }
719  
720  
721  
722 sub eval_cleanup {
723 DB::state( 'inDB', 1 );
724 DB::state( 'eval', undef );
725 }
726 mutate_sub_is_debuggable( \&eval_cleanup, 0 );
727  
728  
729  
730 # We put code here to execute it only once
731 (my $usercontext = <<' CODE') =~ s#^\t\t##gm;
732 BEGIN{
733 ( $^H, ${^WARNING_BITS}, my $hr ) = @DB::context[1..3];
734 %^H = %$hr if $hr;
735 }
736 # $@ is cleared when compiller enters *eval* or *BEGIN* block
737 $@ = $DB::context[4];
738 CODE
739 # http://perldoc.perl.org/functions/eval.html
740 # We may define eval in other package if we want to place eval into other
741 # namespace. It will still "doesn't see the usual surrounding lexical scope"
742 # because "it is defined in the DB package"
743 # sub My::eval {
744 sub eval {
745 my( $expr ) = @_;
746 # BUG: PadWalker does not show DB::eval's lexicals
747 # Q? It is better that PadWalker return undef instead of warn when out of level
748  
749 print $DB::OUT "Evaluating '$expr'...\n" if DB::state( 'ddd' );
750  
751 establish_cleanup \&eval_cleanup;
752 DB::state( 'eval', 1 );
753  
754 my $package = DB::state( 'package' );
755 DB::state( 'inDB', undef );
756  
757  
758 # Read BEWARE at DebugHooks.pod about localization of globals
759 local $^D;
760 local $_ = $DB::context[5];
761 local @_ = @{ $DB::context[0] };
762 eval "$usercontext; package $package;\n#line 1\n$expr";
763 #NOTICE: perl implicitly add semicolon at the end of expression
764 #HOWTO reproduce. Run command: X::X;1+2
765 #
766 # print $DB::OUT "Error occur while evaluating: $@" if $@
767 # But if we do this we return wrong value
768 }
769  
770  
771  
772 # Returns the location where $subname is defined in the form:
773 # filename:startline-endline
774 sub location {
775 my $subname = shift;
776  
777 return unless $subname;
778 return ">>$subname<<" if ref $subname; # The subname maybe a coderef
779  
780 # The subs from DB::* are not placed here. Why???
781 # A? Maybe they are placed after module loaded?
782 return $DB::sub{ $subname };
783 }
784  
785  
786  
787 # Returns list of all defined not ANON subs.
788 # We may limit the list by supplying regex
789 sub subs {
790 return keys %DB::sub unless @_;
791  
792 my $re = shift;
793 return grep { /$re/ } keys %DB::sub;
794 }
795  
796  
797  
798 # Returns caller frame info with arguments at given level
799 # or all call stack with goto frames
800 sub frames {
801 my $level = shift;
802  
803 if( defined $level ) {
804 # https://rt.perl.org/Public/Bug/Display.html?id=126872#txn-1380132
805 # Note that we should ignore our frame, so +1
806 my @frame = caller( $level +1 );
807 return ( [ @DB::args ], @frame );
808 }
809  
810  
811 orig_frames() if $options{ orig_frames };
812  
813  
814 # For uninitialized values in frames
815 # $wantarray is undefined in void context, for example
816 BEGIN{ 'warnings'->unimport( 'uninitialized' ) if $DB::options{ w } }
817  
818 my @frames;
819 $level = 0;
820 local $" = ' -';
821  
822 # The $inDB is an internal variable of DB:: module. If it is true
823 # then we know that debugger frames are exists. In other case no sense
824 # to check callstask for frames generated by debugger subs
825 if( DB::state( 'inDB' ) ) {
826  
827 my $found = 0;
828 # Skip debugger frames from stacktrace
829 while( my @frame = caller($level++) ) {
830 # print "DBGF: @frame[0..3,5]\n" if $options{ dbg_frames };
831 push @frames, [ 'D', [ @DB::args ], @frame] if $options{ dbg_frames };
832  
833 if( $frame[3] eq 'DB::trace_subs' ) {
834 $found = 1;
835 # my $args = [ @DB::args ];
836 my @gframe = caller($level);
837 if( @gframe && $gframe[ 3 ] eq 'DB::goto' ) {
838 # print "DBGF: @gframe[0..3,5]\n" if $options{ dbg_frames };
839 # TODO: implement testcase: 'T' should show args for sub calls
840 push @frames, [ 'D', [ @DB::args ], @gframe] if $options{ dbg_frames };
841 $level++;
842 }
843 else {
844 # Because there is no DB::goto frame in stack
845 # we are sure that the @DB::goto_frames will not contain
846 # goto frames also. But only one initial sub frame
847 $level--;
848 # use Data::Dump qw/ pp /;
849 # print pp \@DB::goto_frames, \@gframe; print "<<<<<<<\n";
850  
851 # $frame[3] = $DB::goto_frames[0][3];
852 # push @frames, [ $DB::goto_frames[0][5], $args, @frame ];
853 }
854  
855 last;
856 }
857  
858 if( $frame[3] eq 'DB::DB' ) {
859 $found = 1;
860 last;
861 };
862 }
863  
864 # We can not make $DB::inDB variable private because we use localization
865 # In theory someone may change the $DB::inDB from outside
866 # Therefore we prevent us from empty results when debugger frames
867 # not exist at the stack
868 $level = 0 unless $found;
869 }
870  
871 my $count = $options{ frames };
872 my $ogf = my $gf = DB::state( 'goto_frames' );
873 while( $count && (my @frame = caller( $level++ )) ) {
874 # The call to DB::trace_subs replaces right sub name of last call
875 # We fix that here:
876 $frame[3] = DB::state( 'goto_frames' )->[-1][3]
877 if $count == $options{ frames } && $frame[3] eq 'DB::trace_subs';
878  
879 my $args = [ @DB::args ];
880 if( $options{ trace_goto }
881 && $gf->[0][0] eq $frame[0]
882 && $gf->[0][1] eq $frame[1]
883 && $gf->[0][2] == $frame[2]
884 ) {
885 $frame[3] = $gf->[0][3];
886 push @frames, [ $_->[5], $args, @$_[0..3] ] for @$gf[ reverse 1..$#$gf ];
887 $ogf = $gf;
888 $gf = $gf->[0][4];
889 }
890  
891 push @frames, [ $ogf->[0][5], $args, @frame ];
892 } continue {
893 $count--;
894 }
895  
896  
897 return @frames;
898 }
899  
900  
901  
902 # TODO: implement $DB::options{ trace_internals }
903 sub mcall {
904 my $method = shift;
905 my $context = DB::state( 'instance' );
906  
907 print "mcall ${context}->$method\n"
908 if DB::state( 'ddd' );
909  
910 my $sub = $context->can( $method );
911 scall( $sub, $context, @_ );
912 }
913  
914  
915  
916 sub scall {
917 my $sub = sub_name( $_[0] ) || $_[0];
918 my $ddd = DB::state( 'ddd' );
919 my( $from, $f, $l );
920 if( $ddd ) {
921 my $lvl = 0;
922 if( (caller 1)[3] eq 'DB::mcall' ) {
923 $lvl++;
924 }
925  
926 { local $" = ', '; $sub .= "( @_[ 1..$#_ ] )"; }
927  
928 ($f, $l) = (caller $lvl)[1,2];
929 $f =~ s".*?([^/]+)$"$1";
930 $from = (caller $lvl+1)[3];
931  
932 print $DB::OUT ">> scall from $from($f:$l) --> $sub\n";
933 }
934  
935 # die "You can make debugger call only from debugger"
936 # unless DB::state( 'inDB' );
937  
938  
939 # FIX: http://perldoc.perl.org/perldebguts.html#Debugger-Internals
940 # (This doesn't happen if the subroutine -was compiled in the DB package.)
941 # ...was called and compiled in the DB package
942  
943 # Any subroutine call invoke DB::sub again
944 # The right way is to turn off 'Debug subroutine enter/exit'
945 # local $^P = $^P & ~1; # But this works at compile time only.
946 # So prevent infinite DB::sub reentrance manually. One way to compete this:
947 # my $stub = sub { &$DB::sub };
948 # local *DB::sub = *DB::sub; *DB::sub = $stub;
949 # Another: the { inDB } flag
950  
951 #IT: Call other debugger commands from current command
952 my $old_cmd = DB::state( 'cmd' );
953  
954 # Manual localization
955 my $scall_cleanup = sub {
956 print_state "Debugger command DONE: $sub " if $ddd;
957  
958 # NOTICE: Because we are in debugger here we should setup { inDB }
959 # flag but we are leaving debugger and interesting at user's context
960  
961 DB::state( 'cmd', $old_cmd ); DB::state( 'single', 0, 1 ) if $old_cmd;
962 # $DB::single = DB::state( 'single' );
963 DB::state( 'single', DB::state( 'single' ) ) unless $old_cmd;
964  
965 my $dd;
966 DB::DESTROY if ($dd = DB::state( 'dd' )) && $sub =~ /$dd/;
967  
968 # Enable debugging after current command is finished
969 if( my $debug = DB::state( 'debug' ) ) {
970 DB::state( 'debug', undef );
971 my( $verbose, $sub ) = $debug =~ /^(\d+)?(?:@(.*))?$/;
972 # Set or flush debug flags depending on user's input
973 DB::state( 'ddd', $verbose // undef );
974 DB::state( 'dd', $sub // undef );
975 }
976  
977  
978 print $DB::OUT "<< scall back $from($f:$l) <-- $sub\n" if $ddd;
979 };
980 mutate_sub_is_debuggable( $scall_cleanup, 0 );
981 establish_cleanup $scall_cleanup;
982  
983 # TODO: testcase 'a 3 DB::state( dd => 1 )'
984  
985  
986 # Create new debugger's state instance
987 my $dd;
988 if( ($dd = DB::state( 'dd' )) && $sub =~ /$dd/ ) {
989 # NOTICE: We should not set debugger states directly when create
990 # new state instance. We will not see changes at debug output
991 # So we use &DB::state after instance initialization
992 DB::new();
993 DB::state( 'single', 1 );
994 DB::state( 'inDB', undef );
995 $^D |= 1<<30;
996 }
997 else {
998 DB::state( 'single', 0, 1 ); # Prevent debugging for next call # THIS CONTROLS NESTING
999 DB::state( 'cmd', 1 );
1000 }
1001  
1002 print $DB::OUT "Call debugger command: $sub\n" if $ddd;
1003 return shift->( @_[ 1..$#_ ] );
1004  
1005 # my $method = shift;
1006 # my $context = shift;
1007 # &{ "$context::$method" }( @_ );
1008 }
1009  
1010  
1011  
1012 sub save_context {
1013 @DB::context = ( \@_, (caller 2)[8..10], $@, $_ );
1014 print_state "\nTRAPPED IN ", "\n\n" if _ddd;
1015 DB::state( 'inDB', 1 );
1016 }
1017  
1018  
1019  
1020 # WORKAROUND: &restore_context is called outside of DB::DB, so we should stop debugging it
1021 # to prevent $file:$line updated in unexpected way
1022 mutate_sub_is_debuggable( \&restore_context, 0 );
1023 sub restore_context {
1024 DB::state( 'inDB', undef );
1025 print_state "\nTRAPPED OUT ", "\n\n" if _ddd;
1026 $@ = $DB::context[ 4 ];
1027 # WARNING: Do not keep any references to user's data, in other case we postpone
1028 # object desctruction process.
1029 @DB::context = (); # TODO: IT
1030 }
1031 } # end of provided DB::API
1032  
1033  
1034  
1035  
1036  
1037 sub import { # NOTE: The import is called at CT yet
1038 # CT of callers module. For this one it is RT
1039 my $class = shift;
1040  
1041  
1042 # There are two states: debugger is loaded or not (still loading)
1043 # One options define debugger behaviour while it is loading
1044 # Others define debugger behaviour while main program is running
1045  
1046 # NOTICE: it is useless to set breakpoints for not compiled files
1047 # TODO: spy module loading and set breakpoints
1048 #TODO: Config priority: conf, ENV, cmd_line
1049  
1050  
1051 # Parse cmd_line options:
1052 if( $_[0] and $_[0] eq 'options' ) {
1053 my %params = @_; # FIX? the $_[1] should be HASHREF; $options = @_[1]
1054 @DB::options{ keys %{ $params{ options } } } = values %{ $params{ options } };
1055 }
1056 else {
1057 for( @_ ) {
1058 if( /^(\w+)=([\w\d]+)/ ) {
1059 $DB::options{ $1 } = $2;
1060 }
1061 else {
1062 $DB::options{ $_ } = 1;
1063 }
1064 }
1065 }
1066  
1067  
1068 # Default debugger behaviour for main script
1069 $DB::options{ trace_goto } //= 1;
1070  
1071  
1072 # Now debugger and all required modules are loaded. We should set
1073 # corresponding perl debugger *internal* values based on given %DB::options
1074 applyOptions();
1075 DB::state( 'inDB', undef );
1076 }
1077  
1078  
1079  
1080 # use Sub::Identify qw/ sub_name /;
1081 use B qw(svref_2object);
1082 sub sub_name {
1083 return unless ref( my $r = shift );
1084 return unless my $cv = svref_2object( $r );
1085 return unless $cv->isa( 'B::CV' )
1086 and my $gv = $cv->GV
1087 ;
1088 my $name = '';
1089 if ( my $st = $gv->STASH ) {
1090 $name = $st->NAME . '::';
1091 }
1092 my $n = $gv->NAME;
1093 if ( $n ) {
1094 $name .= $n;
1095 if ( $n eq '__ANON__' ) {
1096 $name .= ' defined at ' . $gv->FILE . ':' . $gv->LINE;
1097 }
1098 }
1099 return $name;
1100 }
1101  
1102  
1103  
1104 # We define posponed/sub as soon as possible to be able watch whole process
1105 # NOTICE: At this sub we reenter debugger
1106 sub postponed {
1107 #TODO: implement local_state to localize debugger state values
1108 my $old_inDB = DB::state( 'inDB' );
1109 DB::state( 'inDB', 1 );
1110 #FIX: process exceptions
1111 emit( 'trace_load', @_ );
1112  
1113 # When we are in debugger and we require module the execution will be
1114 # interrupted and we REENTER debugger
1115 # TODO: study this case and IT:
1116 # T: We are { dd } and run command that 'require'
1117 DB::state( 'inDB', $old_inDB );
1118 }
1119  
1120  
1121  
1122 our %sig = (()
1123 ,trap => \&trap
1124 ,untrap => \&untrap
1125 );
1126  
1127  
1128 mutate_sub_is_debuggable( \&reg, 0 );
1129 sub reg {
1130 my( $sig, $name, @extra ) = @_;
1131  
1132 if( exists $DB::sig{ $sig } ) {
1133 return $DB::sig{ $sig }->( $name, @extra );
1134 }
1135 else {
1136 return default_handler( $sig, $name, @extra );
1137 }
1138 }
1139  
1140  
1141  
1142 sub unreg {
1143 my( $sig, $name, @extra ) = @_;
1144  
1145 if( exists $DB::sig{ $sig } ) {
1146 return $DB::sig{ "un$sig" }->( $name, @extra );
1147 }
1148 else {
1149 return default_unhandler( $sig, $name, @extra );
1150 }
1151 }
1152  
1153  
1154  
1155 sub emit {
1156 my( $name ) = ( shift );
1157  
1158 print $DB::OUT "Emit event '$name' from ", (caller)[1,2], "\n" if DB::state( 'ddd' );
1159  
1160 # Get subscribers for the event
1161 my $ev; {
1162 no strict 'refs';
1163 $ev = defined &{ "${name}_info" }
1164 ? &{ "${name}_info" }( @_ )
1165 : default_handler_info( $name )
1166 ;
1167 }
1168  
1169 my $res = [];
1170 # Events are emitted in context of handler. Event handler should be at least
1171 # HASHREF with key 'code' having CODEREF to sub which will process event
1172 push @$res, process( $ev->{ $_ }, @_ ) for keys %$ev;
1173  
1174 print $DB::OUT "Event '$name' DONE\n" if DB::state( 'ddd' );
1175  
1176 return $res;
1177 }
1178  
1179  
1180  
1181 sub default_handler_info {
1182 return DB::state( "on_$_[0]" ) // {};
1183 }
1184  
1185  
1186  
1187 sub default_handler {
1188 my( $sig, $name ) = @_;
1189 my $subscribers = DB::state( "on_$sig" );
1190 $subscribers = DB::state( "on_$sig", {} ) unless $subscribers;
1191  
1192 # HACK: Autovivify subscriber if it does not exists yet
1193 # Glory Perl. I love it!
1194 return \$subscribers->{ $name };
1195 }
1196  
1197  
1198  
1199 sub default_unhandler {
1200 my( $sig, $name ) = @_;
1201 my $subscribers = DB::state( "on_$sig" );
1202  
1203 delete $subscribers->{ $name };
1204 DB::state( "on_$sig", undef ) unless keys %$subscribers;
1205 }
1206  
1207  
1208  
1209 sub trap_info {
1210 my( $file, $line ) = @_;
1211  
1212 return DB::traps( $file )->{ $line };
1213 }
1214  
1215  
1216  
1217 sub trap {
1218 my( $name, $file, $line ) = @_;
1219 my $traps = DB::traps( $file );
1220  
1221 # HACK: Autovivify subscriber if it does not exists yet
1222 # Glory Perl. I love it!
1223 return \$traps->{ $line }{ $name };
1224 }
1225  
1226  
1227  
1228 sub untrap {
1229 my( $name, $file, $line ) = @_;
1230 my $traps = DB::traps( $file );
1231  
1232 #TODO: clear all traps in all files
1233 #TODO: clear all specific traps, maybe in all files
1234 delete $traps->{ $line }{ $name };
1235  
1236 # Remove info about trap from perl internals if no common traps left
1237 # After this &DB::DB will not be called for this line
1238 unless( keys %{ $traps->{ $line } } ) {
1239 # NOTICE: Deleting a key does not remove a breakpoint for that line
1240 # Because key deleting from common hash does not update internal info
1241 # TODO: bug report
1242 # WORKAROUND: we should explicitly set value to 0 to signal perl
1243 # internals there is no trap anymore then delete the key
1244 $traps->{ $line } = 0;
1245 delete $traps->{ $line };
1246 }
1247 #IT: Deleting one subscriber should keep others
1248  
1249 return;
1250 }
1251  
1252  
1253  
1254 # TODO: implement: on_enter, on_leave, on_compile
1255 sub DB_my {
1256 &save_context;
1257 establish_cleanup \&restore_context;
1258  
1259 my( $p, $f, $l ) = init();
1260 print_state( "DB::DB ", sprintf "\n cursor(DB) => %s, %s, %s\n" ,$p ,$f, $l ) if DB::state( 'ddd' );
1261  
1262 emit( 'trace_line' ) if $DB::trace;
1263 #TODO: $DB::signal $DB::trace
1264  
1265  
1266 my $stop = List::Util::any { $_ } @{ emit( 'trap', $f, $l ) };
1267 my $confirm = List::Util::all { $_ } @{ emit( 'stop', $p, $f, $l ) };
1268  
1269 #IT: stop on breakpoint while stepping
1270 return unless $stop || $DB::single && $confirm || $DB::signal;
1271 # Stop if required or we are in step-by-step mode
1272  
1273  
1274 print_state "\n\nStart to interact with user\n", "\n\n" if DB::state( 'ddd' );
1275  
1276 emit( 'bbreak' );
1277 emit( 'interact' );
1278 emit( 'abreak' );
1279 }
1280  
1281  
1282  
1283 sub DB {
1284 # WORKAROUND: Thanks for mst
1285 # the 'sub DB' pad stack isn't getting pushed to allocate a new pad if
1286 # you set '$^D|=(1<<30) and reenter DB::DB
1287 # So I call general sub. '&' used to leave @_ intact
1288 &DB_my;
1289 }
1290  
1291  
1292  
1293 sub init {
1294 # For each step at client's script we should update current position
1295 # Also we should do same thing at &DB::sub
1296 my( $p, $f, $l ) = caller(2);
1297 state( 'package', $p );
1298 state( 'file', $f );
1299 state( 'line', $l );
1300  
1301 # Someone may stop client's code running through perl debugger interface
1302 # For example until the first line of client's code the $DB::single == 0
1303 # When ($^P & 0x20) perl set $DB::single = 1 before execution of first line
1304 # So we should update our state
1305 DB::state( 'single', $DB::single );
1306  
1307  
1308 # Commented out because of:
1309 # https://rt.perl.org/Ticket/Display.html?id=127249
1310 # die ">$DB::file< ne >" .file( $DB::file ) ."<"
1311 # if $DB::file ne file( $DB::file );
1312  
1313 return( $p, $f, $l );
1314 }
1315  
1316  
1317  
1318 # When handler returns itself (HASHREF) as result it will keep processing (like 'redo'):
1319 # specified handler at 'code' key will be reinvoked
1320 # When handler returns ARRAYREF specified handler also will be reinvoked with
1321 # evaluated results for each returned item in that array
1322 sub process {
1323 my( $handler ) = @_;
1324 my $htype = ref $handler;
1325  
1326 my( $code, @args );
1327 do {
1328 if( $htype eq 'ARRAY' ) {
1329 print $DB::OUT "Got list of expressions to evaluate in usercontext\n"
1330 if DB::state( 'ddd' );
1331 $code = shift @$handler;
1332 @args = ();
1333 for my $expr ( @$handler ) {
1334 # $expr should be simple string. If it is not it is special
1335 push @args, ref $expr ? process( $expr ) : [ DB::eval( $expr ) ];
1336 if( $@ ) {
1337 # Pass reference to copy of error message. Value of error
1338 # message (global variable) may be changed by anyone
1339 $args[-1] = bless { error => $@ }, 'DB::Error';
1340 }
1341 }
1342 }
1343 elsif( $htype eq 'HASH' ) {
1344 $code = $handler->{ code };
1345 @args = @_;
1346 }
1347 else {
1348 die "Handler type should be ARRAY or HASH";
1349 }
1350  
1351 die "Handler is not defined" unless $code;
1352  
1353 if( DB::state( 'ddd' ) ) {
1354 my $sub = sub_name( $code ) || $code;
1355 my @first = ref $args[0] eq 'ARRAY' ? @{ $args[0] } : $args[0] // '';
1356 print $DB::OUT "Run callback: $sub @first ( @args )\n"
1357 }
1358 } while(
1359 defined( $handler = scall( $code, @args ) )
1360 && ( $htype = ref $handler )
1361 );
1362  
1363 return $handler;
1364 }
1365  
1366  
1367  
1368 # TODO: Before run the programm we could deparse sources and insert some code
1369 # in the place of 'goto'. This code may save __FILE__:__LINE__ into DB::
1370 sub goto {
1371 #FIX: IT: when trace_goto disabled we can not step over goto
1372 return unless $options{ trace_goto };
1373 return if DB::state( 'inDB' );
1374  
1375 my $old_inDB = DB::state( 'inDB' );
1376 DB::state( 'inDB', 1 );
1377  
1378 DB::state( 'single', 0 ) if DB::state( 'single' ) & 2;
1379 push_frame( my $tmp = $DB::sub, 'G' );
1380 DB::state( 'inDB', $old_inDB )
1381 };
1382  
1383  
1384  
1385 {
1386 #package DB::Tools;
1387 # my $x = 0;
1388 # use Data::Dump qw/ pp /;
1389 #Q: Why &DB::sub is called for &pop_frame despite on it is compiled at DB:: package
1390 # when Scope::Cleanup?
1391 mutate_sub_is_debuggable( \&pop_frame, 0 );
1392 sub pop_frame {
1393 #NOTICE: We will fall into infinite loop if something dies inside this sub
1394 #because this sub is called when flow run out of scope.
1395 #TODO: Put this code into eval block
1396  
1397 my $old_inDB = DB::state( 'inDB' );
1398 DB::state( 'inDB', 1 );
1399 emit( 'pop_frame' );
1400 DB::state( 'inDB', $old_inDB );
1401 }
1402  
1403 }
1404  
1405  
1406  
1407 sub trace_returns {
1408 DB::state( 'inDB', 1 );
1409 #FIX: process exceptions
1410 emit( 'trace_returns', @_ );
1411 DB::state( 'inDB', undef );
1412 }
1413  
1414  
1415  
1416 sub push_frame {
1417  
1418 print_state "BEFORE CALL: $_[0] " if _ddd;
1419 my $old_inDB = DB::state( 'inDB' );
1420 DB::state( 'inDB', 1 );
1421  
1422 emit( 'push_frame', @_ );
1423  
1424 if( DB::state( 'ddd' ) ) {
1425 print $DB::OUT "STACK:\n";
1426 DB::state( 'stack' );
1427 }
1428  
1429 DB::state( 'inDB', $old_inDB );
1430 print_state "BEFORE CALL DONE: $_[0] " if _ddd;
1431 }
1432  
1433  
1434  
1435 # The sub is installed at compile time as soon as the body has been parsed
1436 sub sub {
1437 #FIX: where to setup 'inDB' state?
1438 print_state "DB::sub ", " --> " .(sub_name( $DB::sub ) // $DB::sub) ."\n"
1439 if sub{ DB::state( 'ddd' ) }->() && $DB::sub ne 'DB::can_break';
1440 #TODO: We could use { trace_internals } flag to see debugger calls
1441  
1442 if( sub{ DB::state( 'inDB' ) }->()
1443 ) {
1444 BEGIN{ 'strict'->unimport( 'refs' ) if $options{ s } }
1445 # TODO: Here we may log internall subs call chain
1446  
1447 # sub{ DB::state( 'inDB', undef ) }->();
1448 #TODO: Do not create extra frames. Speed optimization?
1449 # replace return -> goto
1450 return &$DB::sub
1451 }
1452  
1453 # manual localization
1454 establish_cleanup \&DB::pop_frame; # This should be first because we should
1455 # start to guard frame before any external call
1456  
1457 #FIX: do not call &pop_frame when &push_frame FAILED
1458 sub{ push_frame( my $tmp = $DB::sub, 'C' ) }->();
1459  
1460  
1461 {
1462 BEGIN{ 'strict'->unimport( 'refs' ) if $options{ s } }
1463  
1464  
1465 if( wantarray ) { # list context
1466 my @ret = &$DB::sub;
1467 trace_returns( @ret );
1468 return @ret;
1469 }
1470 elsif( defined wantarray ) { # scalar context
1471 my $ret = &$DB::sub;
1472 trace_returns( $ret );
1473 return $ret;
1474 }
1475 else { # void context
1476 &$DB::sub;
1477 trace_returns;
1478 return;
1479 }
1480 }
1481  
1482  
1483 die "This should be reached never";
1484 #NOTICE: This reached when someone leaves sub by calling 'next/last' outside of LOOP block
1485 #Then 'return' is not called at all???
1486 };
1487  
1488  
1489  
1490 # FIX: debugger dies when lsub is not defined but the call is to an lvalue subroutine
1491 # The perl may not "...fall back to &DB::sub (args)."
1492 # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
1493 sub lsub : lvalue {
1494 my $x;
1495 if( DB::state( 'inDB' ) ) {
1496 BEGIN{ 'strict'->unimport( 'refs' ) if $options{ s } };
1497 $x = &$DB::sub
1498 }
1499 else {
1500 # manual localization
1501 establish_cleanup \&sub_returns;
1502 push @{ DB::state( 'stack' ) }, {
1503 single => DB::state( 'single' ),
1504 sub => $DB::sub,
1505 goto_frames => DB::state( 'goto_frames' ),
1506 };
1507  
1508 DB::state( 'goto_frames', [] );
1509  
1510  
1511 # HERE TOO client's code 'caller' return wrong info
1512 trace_subs( 'L' );
1513  
1514 DB::state( 'single', 0 ) if DB::state( 'single' ) & 2;
1515 {
1516 BEGIN{ 'strict'->unimport( 'refs' ) if $options{ s } }
1517 $x = &$DB::sub;
1518 }
1519 }
1520  
1521 $x;
1522 };
1523  
1524  
1525  
1526 # It is better to load modules at the end of DB::
1527 # because of they will be visible to 'trace_load'
1528 use Devel::DebugHooks::Commands;
1529  
1530  
1531 # DB::state( 'inDB', undef );
1532 # TODO: After this module is loaded the &import is called
1533 # Enable debugging for importing process of DB:: modules
1534 # If you flush { inDB } we will trace sub calls while loading those modules
1535  
1536  
1537  
1538 1;
1539  
1540 __END__
1541  
1542 =head1 SUPPORT
1543  
1544 Bugs may be reported via RT at
1545  
1546 https://rt.cpan.org/Public/Dist/Display.html?Name=Devel-DebugHooks
1547  
1548 Support by IRC may also be found on F<irc.perl.org> in the F<#debughooks>
1549 channel.
1550  
1551 =head1 AUTHOR
1552  
1553 Eugen Konkov <debugger@konkov.top>
1554  
1555 =head1 COPYRIGHT
1556  
1557 The following copyright notice applies to all the files provided in
1558 this distribution, including binary files, unless explicitly noted
1559 otherwise.
1560  
1561 Copyright (c) 2015-2026 Eugen Konkov
1562  
1563 =head1 LICENSE
1564  
1565 The files under C<lib/Devel/*> in this distribution are free software; you
1566 can redistribute them and/or modify them under the same terms as Perl itself.
1567  
1568 This free license applies only to the files under C<lib/Devel/*>. Other files
1569 in this distribution are governed by their own licensing terms.
1570  
1571 =cut
1572  
1573 Describe what is used by perl internals from DB:: at compile time
1574 ${ "::_<$filename" } - $filename
1575 @{ "::_<$filename" } - source lines. Line in compare to 0 shows trapnessability
1576 %{ "::_<$filename" } - traps keyed by line number ***
1577 $DB::sub - the current sub
1578 %DB::sub - the location of sub definition
1579 @DB::args - ref to the @_ at the given level at caller(N)
1580 if the sub returns the @DB::args becomes dirty and we can not access its values
1581 &DB::goto, &DB::sub, &DB::lsub, &DB::postponed - called at appropriate events
1582 $^P - flags to control behaviour
1583 $DB::postponed{subname} - trace sub loads ***
1584 $DB::trace, $DB::single, $DB::signal - controls if the program should break
1585  
1586 initialization steps: rc -> env
1587  
1588  
1589 goto implicitly changes the value of $DB::sub
1590  
1591 At compile time $DB::single is 0
1592  
1593 Which data is preserved by forth bit of $^P?
1594  
1595 How to debug lvalue subs?
1596  
1597 The DOC must describe that DB::sub should have :lvalue attribute
1598 if DB::lsub is not defined. Whithout that the:
1599 'falling back to &DB::sub (args).' is not possible
1600  
1601  
1602  
1603 Can not control what value is assigned to lvalue sub
1604  
1605  
1606 +
1607 if sub does not exists lsub is not called at all
1608  
1609 +
1610 The caller behaves differently in lsub in compare to sub
1611 http://paste.scsys.co.uk/502493
1612 http://paste.scsys.co.uk/502494
1613  
1614 no description/link for the $DEBUGGING variable in perlvar
1615 >>perl -Dxxx command described in perlrun
1616  
1617 Why the 'DB::' namespace is exluded from loading subs process?
1618 whereas 'DB::postpone' is works fine for whole module
1619 BEGIN {
1620 $DB::postponed{ 'DB::DB' } = 1;
1621 } # The DB::postpone( 'DB::DB' ) is not called
1622  
1623  
1624  
1625 +
1626 Why the DB::DB is called twice for:
1627 print "@{[ (caller(0))[0..2] ]}\n";
1628 but only one for this:
1629 print sb();
1630 A: It is called once for caller(0) and second for whole line.
1631 It is called once for each statement at line, maybe.
1632  
1633  
1634 +
1635 use should have args. and the caller called from DB:: namespace should set @DB::args
1636 at compile time 'caller' also does not fill @DB::args
1637 BEGIN {
1638 print caller, @DB::args
1639 }
1640 A: Try, to ensure the DB::args used after the call ot caller
1641 BEGIN {
1642 @caller = caller
1643 print @caller, @DB::args
1644 }
1645  
1646  
1647  
1648 How 'the first non-DB piece of code' is calculated for the 'eval'?
1649  
1650  
1651  
1652 #BUG? I can ${ '!@#$' } = 3, but can not my ${ '!@#$' }
1653  
1654  
1655 BUG?
1656 The localization of $DB::single works fine, but the reference to it does not work:
1657 {
1658 $DB::single = 7; my $x = \$DB::single;
1659 print "Before: ". \$DB::single ." <<$x $$x\n";
1660 local $DB::single = 0;
1661 print "After: ". \$DB::single ." <<$x $$x\n";
1662 }
1663  
1664 The output:
1665 Before: SCALAR(0x10f8310) <<SCALAR(0x10f8310) 7
1666 After: SCALAR(0x110cbc8) <<SCALAR(0x10f8310) 0
1667  
1668 Where as works fine:
1669 {
1670 $DB::z = 7; my $x = \$DB::z;
1671 print "Before: ". \$DB::z ." <<$x $$x\n";
1672 local $DB::z = 0;
1673 print "After: ". \$DB::z ." <<$x $$x\n";
1674 }
1675 The output:
1676 Before: SCALAR(0x134d398) <<SCALAR(0x134d398) 7
1677 After: SCALAR(0x1239bc8) <<SCALAR(0x134d398) 7
1678  
1679 We see that in *first* example the new variable is created: The new address of $DB::single is SCALAR(0x110cbc8)
1680 but when assigning to $DB::single the value by old reference (SCALAR(0x10f8310) changed too.
1681 In *second* example we see that addressing works in same manner, but value 7 is preserved as expected.
1682  
1683 Why the value of $DB::single is not preserved?
1684  
1685 # my $y = \$DB::single;
1686 # # Can not use weaken. See error at 'reports/readline' file
1687 # use Scalar::Util 'weaken';
1688 # weaken $y;
1689 # Because of $DB::single magic we can not access to old value by reference
1690 # The localization is broken if we save a reference to $DB::single
1691 # {
1692 # my $x = $DB::single;
1693 # print "Before: ". \$DB::single ." <<$DB::single $x >$y $$y\n"; # $$x == 0
1694 # local $DB::single = $DB::single +1;
1695 # print "After: ". \$DB::single ." <<$DB::single $x >$y $$y\n"; # $$x == 1, not 0
1696 # }
1697 # print "OUT: ". \$DB::single ." <<$DB::single - $x - $$x >$y\n";
1698  
1699 # {
1700 # print "BEFORE: $DB::single\n";
1701 # local $DB::single = 7;
1702 # print "AFTER $DB::single\n";
1703 # }
1704 # print "OUT $DB::single\n";
1705  
1706 # BUG: The perl goes tracing if you uncomment this
1707 # { local $DB::trace = 1; }
1708 # # But it shows us the value 0 but internally it is 1
1709 # die $DB::trace if $DB::trace != 0;
1710  
1711  
1712  
1713 sub sub {
1714 ...
1715 # BUG: without +0 the localized value is broken
1716 local $DB::single = ($DB::single & 2) ? 0 : $DB::single+0;
1717  
1718  
1719 Breakpoint does not work for this when hash key is initialized
1720 b x64: my $hash = $c->stash->{'mojo.content'} ||= {};
1721  
1722 #TODO: $X=(condition)
1723  
1724 The debugger do not single step into sub called from string
1725  
1726  
1727  
1728 Notice strange file:line
1729 POP FRAME <<<< l:0 b:0:0 e:1 s:1 t:1 -- Apache::DB::handler@1
1730 /home/kes/perl_lib/lib/perl5/x86_64-linux-gnu-thread-multi/Apache/DB.pm:77 }
1731  
1732 else {
1733 if (ref $r) {
1734 $SIG{INT} = \&DB::catch;
1735 $r->register_cleanup(sub {
1736 $SIG{INT} = \&DB::ApacheSIGINT();
1737 });
1738 }
1739 }
1740  
1741 print "HERE: " .$DB::single; #line 77
1742 DB::state( 'trace', 1 );
1743 $DB::single = 1;
1744 print "HERE: A" .$DB::single;
1745  
1746  
1747 print "DONE\n";
1748  
1749 print "DONE\n";
1750 return 0;
1751  
1752 }
1753  
1754 Maybe because DESTROY is called at first OP after closing block
1755  
1756 TODO: Allow to eval: 'shift @_' in debugger
1757  
1758 Suggested edit:
1759 When execution of the program reaches a subroutine call, a call to &DB::sub
1760 (args) is made instead, with $DB::sub holding the name of the called subroutine.
1761 (This happen for all debuggable subroutines called outside of DB::DB. Subroutines
1762 compiled in DB:: package all are not debuggable.)