lib/DB/Hooks.pm untested

filter: Statementstmt 0.0% 0 / 322 Branchbran 0.0% 0 / 150 Conditioncond 0.0% 0 / 62 MC/DCmcdc 0.0% 0 / 31 Subroutinesub 0.0% 0 / 36 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 627 CC 74 SCAR 41.3
CC
74
Cov
0%
sub
210.0
dbcall
132.0
state
90.0
CRAP 62.4
1 package DB::Hooks;
2  
3 our $VERSION = '0.0201';
4  
5 =head1 NAME
6  
7 C<DB::Hooks> - Hooks for perl debugger
8  
9 =cut
10  
11 =head2 Possible options
12  
13 undef - configures visible representation for 'undef' during dumps.
14  
15 =cut
16  
17  
18 =head2 Possible events
19  
20 load - after module is compiled
21 goto - after 'goto' was executed
22 call - before calling a subroutine
23 return - before returning from a subroutine
24 Next events occur only during 'interact' and when additionally:
25 trace - $DB::trace is true
26 trap - $DB::trap configured for that file:line
27 stop - DB::state('single') is true
28 binteract, interact, ainteract - 'trap' and 'stop' handlers did not cancel interaction
29 OR $DB::signal is true
30  
31 User defined events.
32  
33 =cut
34  
35  
36  
37 =head2 Debugger verbosity
38  
39 DB::state( 'ddd' )
40  
41 &64 - shows when context is stored and restored
42  
43 &32 - display the information about:
44 what events were emitted
45 what expressions were evaluated in user context during 'process'
46 state of a debug debugging for the next call depending on DB::state( 'dd' )
47 what callbacks were run during 'process' and finished
48 when 'dbcall' (call to the debugger) happened and who called it
49 when 'dbcall' finished. Start and stop info lines are marked by 'D<random'
50 the next value of $DB::single when nested debugger was destroyed
51  
52 &16 - display information when debugger is created/destroyed with the information
53 about its state. Also displays messages when compilation was started/finished.
54 &8 - track reads to DB::state
55 &4 - track writes to DB::state
56 &2 - track subroutine calls
57 &1 - enable basic messages from debugger
58 display which additional debugger modules are loaded
59 display info from debugger commands
60  
61 =cut
62  
63 =head2
64  
65 DB::flags displayed during debugging debugger: s:0 t:0 i:0 c:1
66  
67 "s:$DB::single t:$DB::trace i:$DB::instance c:".@DB::state;
68  
69 s -- step-by-step debugging enabled or not.
70 t -- tracing enabled or note.
71 i -- current debugger instance.
72 c -- number of contexts. TODO? Should we name it d -- number of debuggers.
73  
74 =cut
75  
76 # PERLDB_OPTS='CTddd=2 white_box=~' PERL5DB="use DB::Hooks qw'::Terminal ::TraceLoad ::TraceSubs ::TraceVariable NonStop'" PERL5OPT='-d' prove -v ./script.pl
77  
78  
79 # The precendence is next:
80 # 1. Module is compiled
81 # 2. on_load event if emitted
82 # 3. Module is run
83 # 4. If it return 1 its &import is called
84  
85 # NOTICE: We do not inherit DB:: interface, we use it
86 sub import {
87 my( $class ) = shift;
88  
89 DB::parse_options( @_ );
90  
91 my $ddd = DB::state( 'ddd' ) &1;
92 if( $class eq 'DB::Hooks' ) {
93 for my $module ( @_ ) {
94 next unless $module =~ m/^::/;
95 my( $package, $args ) = $module =~ m/^::([^=]+)=?(.*)$/;
96 $args //= '';
97 my $dbg = "DB::Hooks::$package";
98 $package =~ s/::/\//;
99 DB::say( "Requiring " .DB::_c( "DB::Hooks::$package", '32' ) ." $args" ) if $ddd;
100 require "DB/Hooks/$package.pm";
101 $dbg->import( split ':', $args );
102 }
103 }
104  
105  
106 DB::_leave( $class, @_ );
107 DB::say( DB::_c( "DB::Hooks import done", 31 ) ) if $ddd;
108 return;
109 }
110  
111  
112  
113 package DB::Error;
114 use overload bool => sub {1}, '""' => sub { shift->error }, fallback => 1;
115  
116 sub error {
117 return shift->{ error };
118 }
119  
120  
121  
122 package DB;
123  
124 ## Managment routines
125  
126 # Hooks to Perl's internals should be first.
127 # Because debugger or its descendants may call them at compile time
128 use DB::Utils();
129  
130 # Though this is located before BEGIN{ #INIT } block, this will be executed later,
131 # after DB:: compilation.
132 DB::say "DB:: Initialization is started" if DB::state( 'ddd' ) &17;
133  
134 use strict;
135 use warnings;
136  
137 # Used perl internal variables:
138 # ${ ::_<filename } # maintained at 'file' and 'sources'
139 # @{ ::_<filename } # maintained at 'source' and 'can_break'
140 # %{ ::_<filename } # maintained at 'traps'
141 # $DB::single
142 # $DB::signal
143 # $DB::trace
144 # $DB::sub # NOTICE: this maybe the reference to sub, not just the name of it
145 # %DB::sub # maintained at 'location' and 'subs'
146 # %DB::postponed # Run callback after 'subname' was compiled
147 # @DB::args # maintained at 'frames'
148  
149 # $^P -- http://perldoc.perl.org/perlvar.html#$^P
150 # Default values
151 # 1 x
152 # 0111 0011 1111
153 # |||| |||| |||^-- Debug subroutine enter/exit.
154 # |||| |||| ||^--- Line-by-line debugging.
155 # |||| |||| |^---- Switch off optimizations.
156 # |||| |||| ^----- Preserve more data for future interactive inspections.
157 # |||| ||||
158 # |||| |||^------- Keep info about source lines on which a subroutine is defined.
159 # |||| ||^-------- Start with single-step on. { NonStop }
160 # |||| |^--------- Use subroutine address instead of name when reporting.
161 # |||| ^---------- Report goto &subroutine as well. # We always turn it ON
162 # ||||
163 # |||^------------ Provide informative "file" names for evals based on the place they were compiled.
164 # ||^------------- Provide informative names to anonymous subroutines based on the place they were compiled.
165 # |^-------------- Save source code lines into @{"_<$filename"}.
166 # ^--------------- When saving source, include evals that generate no subroutines.
167 # < When saving source, include source that did not compile.
168  
169 # Perl sets up $DB::single to 1 after the 'script.pl' is compiled, so we are able
170 # to debug it from first OP. We can disable this feature by $^P &= ~0x20 { NonStop }
171  
172  
173  
174  
175  
176 our $IN;
177 our $OUT;
178 our @state; # The array of debugger instances
179 our %options;
180 our $commands; # hash of commands available in debugger
181 our %variables; # Hash which defines behaviour for values available through &DB::state
182 # There three types of variables:
183 # Debugger internal variables -- global values from DB:: package
184 # Debugger instance variables -- values which exists in current debugger instance
185 # Frame variables -- values for each sub call
186 our $instance;BEGIN{ $instance = 0 } # The default debugger instance visible for DB::state calls
187  
188 our $_fix_caller; # For easier debugger debugging we prettify __ANON__ stack frames at &save_context
189 our $after_dbcall; # Setup handler for 'dbcall'. Used to destroy CT debugger instance.
190  
191  
192 sub dbcall {
193 local $_; # See save_context
194 my( $level, $ctx, $sub ) = (shift,shift,shift);
195  
196 my @args;
197 my $ddd = DB::state( 'ddd' );
198 if( $ddd &32 ) {
199 local $" = ', ';
200 @args = vis_undef( @_ );
201 $args[0] = "\e[33m" .$args[0] ."\e[2;33m" if @args;
202 }
203  
204 # save_context (&64) adds an empty line too. Do not double it here.
205 my @new_line = $ddd &64? () : '';
206 my $sub_name = DB::sub_name( $sub );
207 my @msg = ( @new_line, DB::who ." " .DB::_c( DB::flags, '1;90' ),
208 " $sub_name( @args\e[0m )" );
209  
210 # if( $sub_name eq 'DB::emit' && !DB::events( $_[0] ) ) {
211 # DB::say @msg, "<-- dbcall No subscribers. Skipped." if $ddd &32;
212  
213 # restore_context( $ctx );
214  
215 # DB::say '' if $ddd &32;
216  
217 # return;
218 # }
219  
220  
221 my $rand;
222 if( $ddd &32 ) {
223 $rand = int rand( 65535 );
224 $msg[1] .= " D>$rand";
225 DB::say @msg;
226 }
227  
228 my @res;
229 {
230 # IT: 2+2;e;
231 # This will require Data::Dump which triggers postpone method to be called
232 # and reenter the debugger. So we should check recurse when DB::dbcall is made:
233 # TODO? Should we move this into DB::new?
234 DB::start_dd if DB::state( 'dbcall' );
235  
236  
237 # NOTICE: Old value of $DB::single/trace/signal is stored by constructor
238 # and restored when we leave this block
239 my $dd_frame = DB::new( $ctx );
240  
241  
242 # Here we control debugger debugging (also see DB::process)
243 $^D |= (1<<30) if DB::state( 'dd' );
244  
245 DB::state( dbcall => 1 +$level );
246 defined wantarray? @res= &$sub : &$sub;
247 DB::state( dbcall => undef );
248  
249 # $^D &= ~(1<<30) if DB::state( 'dd' ); # TODO??? Should we turn off flag at the end
250 }
251  
252 ($DB::after_dbcall->(), undef $DB::after_dbcall) if $DB::after_dbcall;
253  
254 DB::say '<-- dbcall'. " " .DB::_c( DB::flags, '1;90' ) ." D<$rand" if $ddd &32;
255 return defined wantarray? @res : ();
256 }
257  
258  
259 # NOTICE:
260 # In theory any additional pakcage usage may break user's code
261 # because this usage cause packages to be loaded in different order under debugger
262 # in compare to the order they are loaded without it
263 use Sub::Metadata qw/ mutate_sub_is_debuggable /;
264  
265  
266 ## The debugger instance
267 mutate_sub_is_debuggable( \&state, 0 );
268 sub state {
269 my( $name, $value ) = @_;
270 # During a global destruction if something was loaded before the debugger it will be
271 # destroyed after the debugger. Calls to `DESTROY` will still fire DB::sub, but the
272 # debugger does not exists already, thus @DB::state is empty
273 # TODO: We can undefine DB::sub if last instance was destroyed instead of frequently
274 # checks here
275 return @_>1 ? $DB::state[-1]{ ddd } = $value : $DB::state[-1] && $DB::state[-1]{ ddd } // 0
276 if $name eq 'ddd';
277  
278 my $hash = $DB::state[$DB::instance];
279  
280 my $ddd = $hash->{ ddd } // 0;
281 # Track changes to DB::state OR reads from DB::state
282 if( $ddd&4 && @_>1 || $ddd&8 && @_<=1 ) {
283 my( $sub ) = (caller(1))[3];
284 my( $file, $line ) = (caller)[1,2];
285 my $old_value = vis_undef( $hash->{ $name } );
286 my $new_value = @_ > 1 ? ' -> ' .vis_undef( $value ) : '';
287  
288 DB::say "Access from $sub ($file:$line) to "
289 .DB::_c( $name, 36 ) ." state($DB::instance): "
290 .DB::_c( "$old_value$new_value", '3;37' )
291 }
292  
293 return $hash->{ $name } unless @_ > 1;
294 delete $hash->{ $name }, return unless defined $value;
295  
296 $DB::trace = $value if $name eq 'trace';
297 return $hash->{ $name } = $value;
298  
299 $name = '*' unless exists $DB::variables{ $name };
300 return $DB::variables{ $name }( @_ );
301 }
302  
303  
304  
305 sub int_vrbl {
306 my( $name, $value ) = @_;
307  
308 if( @_ > 1 ) {
309 ${ "DB::$name" } = $value;
310 }
311  
312 return dbg_vrbl( @_ );
313 }
314  
315  
316  
317 sub dbg_vrbl {
318 my( $name, $value ) = @_;
319  
320 # TODO: Assert the change to saved 'context'
321 # We should not rewrite saved context otherwise we restore to wrong context
322 # Access to context(0) state: ARRAY -> ARRAY
323  
324 my $hash = $DB::state[-1];
325 if( @_ > 1 ) {
326 defined $value
327 ? $hash->{ $name } = $value
328 : delete $hash->{ $name };
329 }
330  
331 return $hash->{ $name };
332 }
333  
334  
335  
336 sub new {
337 my $ctx = shift;
338  
339 my( $ddd, $t, $dd ) = 0;
340 if( @DB::state ) { # There is no debugger states if debugger loading is in progress
341 # Save internal flags when we enter debugger
342 DB::state( context => $ctx );
343 DB::state( single => $DB::single );
344 DB::state( trace => $DB::trace );
345 # DB::state( signal => $DB::signal );
346  
347 # Update debugger cursor
348 my( $p, $f, $l ) = @{ $ctx->[0] }[0..2];
349 DB::state( 'package', $p );
350 DB::state( 'file', $f );
351 DB::state( 'line', $l );
352  
353  
354 $ddd = DB::state( 'ddd' );
355 $t = DB::state( 'trace' );
356 $dd = DB::state( 'dd' );
357 }
358 else {
359 $ddd = $DB::options{ CTddd } //0;
360 }
361  
362  
363 # Display this message instantly after $ddd becomes available
364 DB::say "", DB::who, "IN DEBUGGER >>>>>>>>>>>>>>>>>>>>>> " .DB::_c( DB::flags ."+1", '1;90' )
365 if $ddd &17;
366  
367  
368 push @DB::state, { events => {} };
369 DB::state( ddd => $ddd ) if $ddd;
370 DB::state( trace => --$t ) if $t;
371  
372 DB::say DB::_c( "New debugger instance ", '2;92' ), DB::dumper \@DB::state if $ddd &16;
373  
374 return bless{ cleaner => shift }, 'DB';
375 }
376  
377  
378  
379 sub DESTROY {
380 my $ddd = DB::state( 'ddd' );
381  
382 DB::say DB::_c( "Destroy debugger instance ", '2;92' ), DB::dumper \@DB::state if $ddd &16;
383 DB::say "OUT DEBUGGER <<<<<<<<<<<<<<<<<<<<<< " .DB::_c( DB::flags ."-1", '1;90' ), "" if $ddd &17;
384  
385 pop @DB::state;
386  
387  
388 # Cleanup stuff when frame is restored
389 my $cleaner = shift->{ cleaner };
390 $cleaner && $cleaner->();
391  
392 # Restore internal flags when we leave debugger
393 # Find testcase for this condition
394 if( @DB::state ) { # There is no debugger states if main script was terminated
395 $DB::single = DB::state( 'single' ) // 0;
396 $DB::trace = DB::state( 'trace' ) // 0;
397 DB::say 'Debug flag is restored: $single = ' .$DB::single if $ddd &32;
398  
399 my $ctx = DB::state( 'context' );
400 # WARNING: Do not keep any references to user's data eg. @_
401 # Otherwise we postpone object desctruction process.
402 DB::state( context => undef ); # $ctx->[0] = undef # TODO: IT
403 DB::finish_dd if DB::state( 'xx' );
404 # TODO: Flag should be restored from main frame if we do not continue debugging
405 # TODO: IT; Compare with 090da7c: NOTICE: Create debugger instance only ...
406 restore_context( $ctx );
407 }
408 }
409  
410  
411  
412 # Parse x=y pairs. Options in different format are skipped. Eg. ::Name will be handled
413 # later by ::import.
414 sub parse_options {
415 my @opts = split ' ', $ENV{ PERLDB_OPTS } if defined $ENV{ PERLDB_OPTS };
416  
417 for( @opts, @_ ) {
418 if( /^([:\w]+)=(.*)/ ) {
419 $DB::options{ $1 } = $2;
420 }
421 else {
422 $DB::options{ $_ } = 1;
423 }
424 }
425 }
426  
427  
428  
429 # This sub applies options from $DB::options to DB::state
430 # NOTICE: This sub is called twice: at compile time and before run time of 'main' package
431 sub apply_options {
432 $DB::options{ DumpObjects } //= 1;
433 if( $DB::options{ DumpObjects } ) {
434 require Scalar::Util;
435 Scalar::Util->import(qw/ reftype blessed /);
436 mutate_sub_is_debuggable( \&DB::reftype, 0 );
437 mutate_sub_is_debuggable( \&DB::blessed, 0 );
438 }
439  
440  
441 my $ct = shift // '';
442 # { ddd } flag should be first to see debugging messages for next
443 for( qw/ ddd dd trace TraceLoad TraceGoto TraceCall TraceStack TraceReturn / ) {
444 DB::state( $_ => $DB::options{ "${ct}$_" } );
445 }
446  
447 # When we are going to work at white_box we must activate black_box
448 # because white_box can be activated only from black_box (see DB::sub)
449 if( $DB::options{ "${ct}white_box" } ) {
450 DB::state( black_box_active => 1 );
451 }
452  
453 # We may check if (caller)[3] eq 'import' to distinguish CT and RT
454 $^P &= ~0x20 if $DB::options{ NonStop };
455 DB::state( 'single', 1 ) if $DB::options{ Stop }; # IT: commit:1191c38
456 }
457  
458  
459  
460 sub _leave {
461 my $class = shift;
462  
463 # Now debugger and all required modules are loaded (except Descendant).
464 # We should inspect %DB::options and setup corresponding perl debugger
465 # *internal* values
466 # When <DEBUGGER>::import returns the next OP will be first OP from main::
467  
468 # We are leaving debugger
469 my $handler; $handler = DB::on( return => sub{
470 #TODO? Should be call this from 'postpone'?
471 return unless $_[0] eq $class .'::import';
472  
473 DB::unsubscribe( return => $handler );
474 $DB::after_dbcall = sub{
475 my $dbg = DB::new; # Create RT debugger
476 $DB::instance++;
477 # NOTICE: Circular reference is here.
478 # The debugger instance exists until main script is terminated
479 DB::state( debugger => $dbg ); # Make debugger instance accessable via state
480 #TODO? Probably we want apply options as soon as possible, but keep an eye to
481 # DB::instance, because we may apply them to a wrong instance.
482 apply_options();
483  
484 # TODO: Because RT and CT options are differ on command line
485 # We may leave CT debugger alive for history reasons
486 # Delete CT debugger
487 push @DB::state, shift @DB::state; # Swap RT and CT debuggers
488 DB::state( debugger => undef );
489 $DB::instance--;
490  
491  
492 no strict 'refs'; no warnings 'redefine';
493 *{ "DB::on" } = \&{ "DB::RT_on" };
494 *{ "DB::unsubscribe" } = \&{ "DB::RT_unsubscribe" };
495  
496 DB::say DB::c_( "RT debugger initialized:" , '1;32' ), DB::dumper \@DB::state
497 if DB::state( 'ddd' ) &16;
498 };
499  
500 return;
501 });
502 }
503  
504  
505  
506 ## Evaluation in usercontext
507 # We put code here to execute it only once
508 my $usercontext; BEGIN {
509 ($usercontext = <<'CODE') =~ s#^\t##gm;
510 BEGIN {
511 ( $^H, ${^WARNING_BITS}, my $hr ) = @{ DB::state( 'context' )->[0] }[8..10];
512 %^H = %$hr if $hr;
513 }
514 # $@ is cleared when compiller enters *eval* or *BEGIN* block
515 $@ = (DB::state( 'context' ))[2];
516 CODE
517 }
518 sub eval {
519 my $expr = shift // return;
520  
521 DB::state( last_eval => $expr );
522  
523 my $ctx = DB::state( 'context' );
524 my $pkg = $ctx->[0][0];
525 # Read BEWARE at DebugHooks.pod about localization of globals
526 local $^D;
527 local $_ = $ctx->[3];
528 local @_ = @{ $ctx->[1] };
529 # TODO: Beware that using eval neither silences Perl from printing warnings to STDERR,
530 # nor does it stuff the text of warning messages into $@
531 # How to reproduce: $expr = '234asd';
532 eval "$usercontext; package $pkg;\n$expr";
533 #NOTICE: perl implicitly add semicolon at the end of expression
534 #HOWTO reproduce. Run command: X::X;1+2
535 #
536 # print $DB::OUT "Error occur while evaluating: $@" if $@
537 # But if we do this we return wrong value
538 }
539  
540 # In theory &save_context should be called as soon, as possible.
541 sub save_context {
542 # TODO: What to save:
543 # https://metacpan.org/source/OPI/Perl-AtEndOfScope-0.03/lib/Perl/AtEndOfScope.pm
544 # also see perl5db.pl
545 # TODO: Debugger destroyes $1, $2 etc variables in scope
546  
547 my $ctx = [ [caller 1], \@_, $@, $_ ]; # The benefit of this is access to stored global values
548 DB::say '', "Context is stored for $DB::_fix_caller" if DB::state( 'ddd' ) &64;
549  
550 # Replace __ANON__[lib/DB/Hooks.pm:-2] with target sub
551 $ctx->[0][3] = $DB::_fix_caller if $DB::_fix_caller;
552 $ctx->[0][1] =~ s/$DB::options{ pwd }/~/;
553  
554 return $ctx;
555 }
556  
557  
558  
559 # WORKAROUND: &restore_context is called outside of DB::DB, so we should stop debugging it
560 # to prevent $file:$line updated in unexpected way
561 # mutate_sub_is_debuggable( \&restore_context, 0 );
562  
563 sub restore_context {
564 my $ctx = shift;
565 # $_ is implicitly localized at &emit by 'for'
566 # But we still beware about it in &DB::interact if you change it there
567 # then it will broke the user's context. TODO: IT
568 ( $@ ) = @$ctx[ 2 ];
569 DB::say 'Context is restored' if DB::state( 'ddd' ) &64;
570 }
571  
572  
573 ### Initialization
574 # NOTICE: Everything should be defined before first subroutine call
575  
576  
577 no strict 'refs';
578  
579  
580 # Do DB:: configuration stuff here
581 # Default debugger behaviour while it is loading
582 # NOTICE: Order is important. Once subs, which are hooks into Perl internals, are compiled,
583 # they are invoked immediately when their conditions are met. Perl will crash if required
584 # subroutines are not available yet.
585 BEGIN { #INIT
586 # TODO: This does not work if program is run: script.pl < input
587 $DB::IN //= \*STDIN if -t STDIN;
588  
589 #TODO: cache output until debugger is connected
590 $DB::OUT //= \*STDOUT;
591 my $ofh = select $DB::OUT; $|= 1; select $ofh;
592  
593 $DB::ERR //= \*STDERR;
594 $ofh = select $DB::ERR; $|= 1; select $ofh;
595  
596  
597 srand(0); # Required for the same values between runs # if $ddd &32
598 # It is useful when we diff debugger's output between separate runs.
599  
600 # This call will read options from PERLDB_OPTS only. All other options passed to
601 # 'use DB::Hooks XXX' will be available after the compilation and 'import' call.
602 parse_options();
603 # NOTICE: options becomes available via DB::state only after the debugger
604 # instance is created and 'apply_options' call. Thus access 'ddd' directly.
605 my $ddd = $DB::options{ CTddd } // 0; # The first access to 'ddd' option
606 DB::say "DB:: Compilation is started" if $ddd &17;
607  
608 %DB::variables = (()
609 ,'*' => \&dbg_vrbl
610 ,single => \&int_vrbl
611 );
612  
613 my $pwd = $ENV{NO_ROOT}? '!!!%%%' : `pwd`; chomp $pwd;
614 $DB::options{ undef } //= 'undef'; # Text to print for undefined values
615 $DB::options{ pwd } //= "$pwd/";
616  
617  
618 #NOTICE: we should always trace goto frames. Hiding them will prevent
619 # us to complete our work - debugging.
620 # But we still allow to control this behaviour at compiletime & runtime
621 # !!! $options{ trace_goto }; #see DH:import # compile time & runtime option
622 # See the summarized flag description above or full one in the official documentation:
623 # http://perldoc.perl.org/perlvar.html#$^P
624 $^P |= 0x80;
625  
626 my $dbg = DB::new; # Create CT debugger and new state buffer
627 DB::state( debugger => $dbg ); # Save debugger instance into that buffer
628 DB::state( init => 1 );
629  
630  
631 # NOTICE: Because of DB::DB, DB::sub, DB::postpone etc. subs take effect as soon as they
632 # compiled we should &apply_options before that at compile time
633 apply_options( 'CT' );
634  
635 # Though we can use "DB::state( 'ddd' )" here the $ddd is used for performance.
636 DB::say DB::_c( "CT debugger initialized: ", '1;32' ) .DB::_c( DB::flags, '1;90' ),
637 DB::dumper \@DB::state if $ddd &16;
638  
639 # When DB package is loaded its &import subroutine is called (see comment there)
640 }
641  
642  
643  
644 # HOOKS
645 # NOTICE: They take effect as soon as compiled
646 # NOTICE: If you 'use' something or make call then next subs will not be defined atomary
647 # calls will be made to them
648  
649 sub postponed {
650 return if !DB::events( 'load' );
651  
652 local $DB::_fix_caller = 'DB::postponed';
653  
654 dbcall 0, &save_context, \&emit, 'load', @_;
655 }
656  
657  
658  
659 sub goto {
660 return if !DB::events( 'goto' );
661  
662 my $sub_name = sub_name( my $tmp = $DB::sub );
663 local $DB::_fix_caller = "$sub_name; DB::goto";
664  
665 # dbcall 1, [ [caller 1], [ @DB::args ], $@, $_ ], \&emit, 'goto', sub_name( $DB::sub );
666 # panic: Attemt to copy freed scalar at ... when ::TraceSubs
667 # PERL5DB="use DB::Hooks qw'::Terminal NonStop ::TraceLoad ::TraceSubs'"
668 # The problem occur at HiRes::AUTOLOAD:51 where we goto ...
669 dbcall 1, [ [caller 1], [ ], $@, $_ ], \&emit, 'goto', $sub_name;
670 }
671  
672  
673  
674 # This is called from DB::DB when user's program reaches a point that can hold a breakpoint.
675 sub interact {
676 my( $f, $l ) = @_;
677  
678 # Perl has bug: after eval the source is not available through
679 # DB::source interface. It is available lately at some point
680 my $source = DB::source( $f )->[ $l ] //''; chomp $source;
681 emit( 'trace', $source, $f, $l ) if $DB::trace;
682  
683 my @trap;
684 if( my $info = DB::traps( $f )->{ $l } ) {
685 @trap = emit( 'trap', $info, $f, $l );
686 # Stop unconditionally if there is no subscribers for the event
687 @trap = (1) unless @trap;
688 }
689  
690  
691 # DB::state( 'single' ) may be changed by some 'trap' handler: a 4 go 6
692 my @stop;
693 if( DB::state( 'single' ) ) {
694 @stop = emit( 'stop', $f, $l );
695 # Stop unconditionally if there is no subscribers for the event
696 @stop = (1) unless @stop;
697 }
698  
699 return unless (grep{$_} @stop) || (grep{$_} @trap) || ($DB::signal);
700 # Stop if required or we are in step-by-step mode
701  
702  
703  
704 emit( 'binteract', $source, $f, $l );
705 emit( 'interact' );
706 emit( 'ainteract' );
707 }
708  
709  
710  
711 sub db {
712 DB::say DB::_c( 'DB::DB', '2;33' ) ." is called: Breakpoint meet"
713 if DB::state( 'ddd' ) &1;
714  
715 # die "DDD $DB::instance" . DB::dumper( \@DB::state ) .DB::dumper \%DB::options;
716  
717 my $ctx = shift;
718 dbcall 1, $ctx, \&interact, @{ $ctx->[0] }[1,2];
719 }
720  
721  
722  
723 # Hook to Perl internals
724 # https://perldoc.perl.org/perldebguts
725 # When the execution of your program reaches a point that can hold a breakpoint,
726 # the DB::DB() subroutine is called if any of the variables $DB::trace, $DB::single,
727 # or $DB::signal is true.
728 sub DB {
729 local $DB::_fix_caller = 'DB::DB';
730  
731 # WORKAROUND for perl before 5.18: Thanks for mst
732 # the 'sub DB' pad isn't getting pushed to allocate a new pad if
733 # you set '$^D|=(1<<30) and reenter DB::DB
734 # So I call general sub. '&' used to leave @_ intact
735 db( &save_context );
736 }
737  
738  
739  
740 # Hook to perl internals
741 # https://perldoc.perl.org/perldebguts
742 # When execution of the program reaches a subroutine call, a call to &DB::sub(args)
743 # is made instead
744  
745 # NOTICE: This call does not create frames
746 sub sub {
747 DB::say DB::who( sub_name( my $tmp1 = $DB::sub ) ) .' ' .DB::_c( "SUB " .DB::flags, '1;90' )
748 if sub{ DB::state( 'ddd' ) }->() &2;
749  
750 my $dbg = $DB::state[$DB::instance];
751  
752 # Do not trace call/return when we are in debugger
753 return &$DB::sub if $dbg->{ dbcall };
754  
755 # my @s = ( $1, $2, $3, $4, $5, $6, $7, $8, $9 ); # IT. See commit
756 # FIX: https://github.com/Perl/perl5/issues/19767
757  
758 # bb/wb functionality
759 my $sub_name = sub_name( my $tmp2 = $DB::sub );
760 my $wb = $DB::options{ white_box };
761 my $match_wb = $wb && $sub_name eq $wb && $dbg->{ black_box_active };
762  
763 # my $match = join '-', map{ $_ //'#' } @s;
764 # @s = map{ $_ //'' } @s;
765 # $match =~ m/^(?:(\Q$s[0]\E)|#)-(?:(\Q$s[1]\E)|#)-(?:(\Q$s[2]\E)|#)-(?:(\Q$s[3]\E)|#)-(?:(\Q$s[4]\E)|#)-(?:(\Q$s[5]\E)|#)-(?:(\Q$s[6]\E)|#)-(?:(\Q$s[7]\E)|#)-(?:(\Q$s[8]\E)|#)$/;
766  
767 # Do not trace call/return when we are in blackbox
768 return &$DB::sub if $dbg->{ black_box_active } && !$match_wb;
769  
770  
771 # Store state and prepare context
772 DB::state( black_box_active => undef ) if $match_wb;
773  
774 # NOTICE: $sub_name, $context and @$args/@ret/$ret are paramters for the event handler.
775 # Though $sub_name and $context could be accessed from a handler via saved context,
776 # they are passed in hope to simplify their life. Also these parameters are visible
777 # during a debugger debugging with &32 ddd flag.
778 if( DB::events( 'call' ) ) {
779 local $DB::_fix_caller = "$sub_name; DB::sub call " .scalar @_;
780 my $ctx = sub{ &save_context }->( @_ );
781 my $context = $ctx->[0][5]; # wantarray
782 my $args = \@_; # TODO? Pass the copy
783 sub{ dbcall 0, $ctx, \&emit, 'call', $sub_name, $context, @$args }->();
784 }
785  
786  
787 local $DB::_fix_caller = "$sub_name; DB::sub return";
788 my $context = sub{ (caller 0)[5] }->();
789 if( $context ) { # list context
790 my @ret = &$DB::sub;
791  
792 if( DB::events( 'return' ) ) {
793 my $ctx = sub{ &save_context }->( @ret );
794 sub{ dbcall 0, $ctx, \&emit, 'return', $sub_name, $context, @ret }->();
795 }
796  
797 DB::state( black_box_active => 1 ) if $match_wb;
798  
799 return @ret;
800 }
801 elsif( defined $context ) { # scalar context
802 my $ret = &$DB::sub;
803  
804 if( DB::events( 'return' ) ) {
805 my $ctx = sub{ &save_context }->( $ret );
806 sub{ dbcall 0, $ctx, \&emit, 'return', $sub_name, $context, $ret }->();
807 }
808  
809 DB::state( black_box_active => 1 ) if $match_wb;
810  
811 return $ret;
812 }
813 else { # void context
814 &$DB::sub;
815  
816 if( DB::events( 'return' ) ) {
817 # TODO: IT: check $hasargs. Should be same as calling sub
818 my $ctx = sub{ &save_context }->();
819 sub{ dbcall 0, $ctx, \&emit, 'return', $sub_name, $context }->();
820 }
821  
822 DB::state( black_box_active => 1 ) if $match_wb;
823  
824 return;
825 }
826  
827 die "This should be reached never";
828 #NOTICE: This reached when someone leaves sub by calling 'next/last' outside of LOOP block
829 }
830  
831 # Hook to perl internals
832 # https://perldoc.perl.org/perldebguts
833 # NOTICE: This does not work as documented?
834 sub lsub : lvalue { &$DB::sub }
835  
836  
837 DB::say "DB:: Initialization is finished" if DB::state( 'ddd' ) &17;
838 1;
839  
840 =head1 AUTHOR
841  
842 Eugen Konkov <debugger@konkov.top>
843  
844 =head1 COPYRIGHT
845  
846 Copyright (c) 2015-2026 Eugen Konkov
847  
848 =head1 LICENSE
849  
850 This module is distributed under the Perl Debugger Evaluation and Commercial
851 License. See the LICENSE file included with this distribution.
852  
853 =cut
854  
855 # These code lines are very handy in understanding the stages during DB activation.
856 # Eg. "Compiliation" occurs before "Initialization".
857 BEGIN{ DB::say "DB:: Compilation is finished" if DB::state( 'ddd' ) &17 }
858 package DB::Compilation;
859 BEGIN{} #IT
860  
861 __END__