-
Notifications
You must be signed in to change notification settings - Fork 2
/
DebugHooks.pm
1753 lines (1285 loc) · 46.2 KB
/
DebugHooks.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Devel::DebugHooks;
BEGIN {
if( $DB::options{ w } ) { require 'warnings.pm'; 'warnings'->import(); }
if( $DB::options{ s } ) { require 'strict.pm'; 'strict'->import(); }
if( $options{ d } ) { require 'Data/Dump.pm'; 'Data::Dump'->import( 'pp'); }
}
our $VERSION = '0.04';
=head1 NAME
C<Devel::DebugHooks> - Hooks for perl debugger
=head1 SYNOPSIS
perl -d:DebugHooks::Terminal script.pl
## If you want to debug remotely you required additionally install IO::Async
# on remote
perl -d:DebugHooks::Server script.pl
# on local
./dclient.pl 1.2.3.4 9000
=cut
# We should init $DB::dbg as soon as possible, because if trace_subs/load are
# enabled at compile time (at the BEGIN block) the DB:: module will make call
# to $dbg->trace_subs/load. Also these subs should be declared before the
# 'use Devel::DebugHooks' in other case you will get:
# 'Call to undefined sub YourModule::trace_subs/load is made...'
# That is because perl internals make calls to DB::* as soon as the subs in it
# are compiled even whole file is not processed yet.
# Also do not forget to 'push @ISA, "YourModule"' if you set these DB:: options at
# compile time: trace_load, trace_subs,
BEGIN {
unless( defined $DB::dbg ) {
my $level = 0;
while( my $frame = caller($level++) ) {
$DB::dbg = $frame if $frame =~ /^Devel::/;
}
$DB::dbg //= __PACKAGE__;
# ISSUE: We can not make 'main' package as descendant of 'Devel::DebugHooks'
# because of broken info from 'caller', so I restrict pkg_names to 'Devel::'
# TODO: Ask #p5p about that 'caller' shows strange file:line for (eval)
# https://rt.perl.org/Public/Bug/Display.html?id=127083
}
}
sub pop_frame {
#NOTICE: We will fall into infinite loop if something dies inside this sub
#because this sub is called when flow run out of scope.
#TODO: Put this code into eval block
my $stack = DB::state( 'stack' );
my $last = pop @$stack;
DB::print_state( "POP FRAME <<<< ",
" -- $last->{ sub }\@". @$stack ."\n"
." $last->{ file }:$last->{ line }\n\n"
) if DB::state( 'ddd' );
if( @{ DB::state( 'stack' ) } ) {
# Restore $DB::single for upper frame
DB::state( 'single', DB::state( 'single' ) );
} else {
# Something nasty happened at &push_frame, because of we are at
# &pop_frame already but not "push @{ state( 'stack' ) }" done yet
print $DB::OUT "Error happen while &pop_frame. Pay attention to this!\n";
$DB::single = 0;
}
}
{
my $handler = DB::reg( 'pop_frame', 'DebugHooks' );
$$handler->{ context } = $DB::dbg;
$$handler->{ code } = \&pop_frame;
}
sub test {
1;
2;
}
sub push_frame {
{ # these lines exists for testing purpose
no warnings 'void';
test();
3;
}
shift; #Turf event context
my $sub = shift;
DB::print_state( "PUSH FRAME $_[0] >>>> ", " -- $sub\n" ) if DB::state( 'ddd' );
if( $_[0] ne 'G' ) {
# http://stackoverflow.com/questions/34595192/how-to-fix-the-dbgoto-frame
# WORKAROUND: for broken frame. Here we are trying to be closer to goto call
# Most actual info we get when we trace script step-by-step at this case
# those vars have sharp last opcode location.
if( !DB::state( 'eval' ) ) {
#TODO: If $DB::single == 1 we can skip this because cursor is updated at DB::DB
my( $p, $f, $l ) = caller 5;
DB::state( 'package', $p );
DB::state( 'file', $f );
DB::state( 'line', $l );
DB::print_state( "", sprintf "\n cursor(PF) => %s, %s, %s\n" ,$p ,$f, $l ) if DB::state( 'ddd' );
}
my $stack = DB::state( 'stack' );
my $frame = {()
# Until we stop at a callee last known cursor position is the caller position
,package => $stack->[-1]{ package }
,file => $stack->[-1]{ file }
,line => $stack->[-1]{ line }
,single => $stack->[-1]{ single }
,sub => $sub
,goto_frames => []
,type => $_[0]
};
DB::emit( 'frame', $frame );
#TODO: Now we push always. Q: How to skip coresopnding &pop_frame?
# Think about this feature: if( $confirm ) {
push @{ $stack }, $frame;
}
else {
push @{ DB::state( 'goto_frames' ) },
[ DB::state( 'package' ), DB::state( 'file' ), DB::state( 'line' ), $sub, $_[0] ]
}
DB::emit( 'call', $sub );
1;
}
{
my $handler = DB::reg( 'push_frame', 'DebugHooks' );
$$handler->{ context } = $DB::dbg;
$$handler->{ code } = \&push_frame;
}
# NOTICE: We do not inherit DB:: interface, we use it
sub import {
if( $_[0] eq 'Devel::DebugHooks' ) {
shift;
for my $module ( @_ ) {
my( $package, $args ) = $module =~ m/^([^=]+)=?(.*)$/;
$DB::dbg = "Devel::DebugHooks::$package";
$package =~ s/::/\//;
require "Devel/DebugHooks/$package.pm";
$DB::dbg->import( split ':', $args );
}
}
else {
DB::import( @_ );
}
# shift->SUPER::import( @_ );
}
package
x;
sub x { # This is 'invader' :)
# When we returns from this sub the $DB::single is restored at 'DB::sub_returns'
DB::state( 'stack' )->[-1]{ single } = 1 if !@_ || $_[0];
# TODO: Allow to disable trap
}
# NOTICE: x::x; does not work at the end of sub
package
X;
sub X {
local $^D |= (1<<30);
DB::state( 'stack' )->[-1]{ single } = 1;
DB::state( 'single', 1 );
1;
}
package DB::Error;
use overload bool => sub {1}, '""' => sub { shift->error }, fallback => 1;
sub error {
return shift->{ error };
}
package DB;
# In theory this may break user's code because this usage cause dependencies are loaded
# in different order under debugger
use Scope::Cleanup qw/ establish_cleanup /;
use Sub::Metadata qw/ mutate_sub_is_debuggable /;
use List::Util;
BEGIN {
# https://metacpan.org/pod/release/PEVANS/Scalar-List-Utils-1.27/lib/List/Util.pm#SUGGESTED-ADDITIONS
# Perl <=5.18 have List::Utils 1.27 which have not next functions:
$List::Util::VERSION <= 1.27 && eval '
sub List::Util::any(&@) { my $sub = shift; $sub->() && return 1 for @_; 0 }
sub List::Util::all(&@) { my $sub = shift; $sub->() || return 0 for @_; 1 }
';
}
## Utility subs
sub orig_frames {
BEGIN{ 'warnings'->unimport( 'uninitialized' ) if $DB::options{ w } }
my( $count, $warn ) = @_;
$count //= -1; # infinite
my $lvl = 0;
# $x && $y = 3 in this case '=' op precedence should be higher then &&
while( $count-- && (my @frame = caller( $lvl++ )) ) {
$_ = "@frame[0..3,5]\n";
print $DB::OUT $_ unless $warn;
warn $_ if $warn;
}
print $DB::OUT "\n" unless $warn;
}
# This sub is called twice: at compile time and before run time of 'main' package
sub applyOptions {
# Q: is warn expected when $DB::trace == undef?
$DB::trace = $DB::options{ trace_line } || 0
if defined $DB::options{ trace_line };
$^P &= ~0x20 if $DB::options{ NonStop };
DB::state( 'single', 1 ) if $DB::options{ Stop };
}
sub print_state {
my( $before, $after ) = @_;
local $DB::state->[ -1 ]{ ddd };
my( undef, $f, $l ) = caller;
print $DB::OUT
$before
."DB::state: l:" .@$DB::state ." d:" .(DB::state('inDB')//0)
." s:$DB::single t:$DB::trace"
." $f:$l"
.($after // "\n")
;
}
sub log_access {
my( $debug, $context, $hash, $name, $value ) = @_;
my $old_value = $hash->{ $name } // 'undef';
my $new_value = '';
if( @_ >= 5 ) {
$new_value = ' -> '. ($value//'undef');
defined $value
? $hash->{ $name } = $value
: delete $hash->{ $name };
}
if( $debug && ( @_ >= 5 || $debug >= 2 ) ) {
# We are not interested at address of value only its state
# Also this makes life happy when we compare diff for two debugger output
$old_value = ref $old_value ? ref $old_value : $old_value;
$new_value = ref $new_value ? ref $new_value : $new_value;
print $DB::OUT " ${context}::$name: $old_value$new_value\n";
}
return $hash->{ $name };
}
sub int_vrbl {
my( $self, $name, $value, $preserve_frame ) = @_;
#TODO: do not affect current debugger state if we are { inDB } mode
if( @_ >= 3 ) {
no strict "refs";
if( $self->{ debug } ) {
print $DB::OUT " ( DB::$name: ${ \"DB::$name\" } -> $value )";
$self->{ debug }++ if $preserve_frame;
}
${ "DB::$name" } = $value;
}
return frm_vrbl( $self, $name, (@_>=3 && !$preserve_frame ? $value : ()) );
}
sub dbg_vrbl {
my $self = shift;
my $dbg = $self->{ instance } // $DB::state->[-1];
return log_access( $self->{ debug }, 'DBG', $dbg, @_ );
}
sub frm_vrbl {
my $self = shift;
my $frame;
{
local $self->{ debug };
$frame = dbg_vrbl( $self, 'stack' )->[ -1 ];
}
return log_access( $self->{ debug }, 'FRM', $frame, @_ );
}
mutate_sub_is_debuggable( \&state, 0 );
sub state {
return unless $DB::state && @$DB::state;
my( $name, $value ) = @_;
# Do not debug access into 'ddd' flag
my $debug = $name ne 'ddd' && $DB::state->[ -1 ]{ ddd } // 0;
# If we run debugger command do not trace access to debugger state
$debug -= 3 if $DB::state->[ -1 ]{ cmd } && $name ne 'cmd';
$debug = 0 if $debug < 0;
# Show full stack only when verbose mode ON and only before changes
# or before implicit changes: when debugger command take whole 'stack'
# and manipulate data directly
if( $debug && (($debug >= 3 && @_ >= 2) || $name eq 'stack' ) ) {
print_state "\n ";
for( @$DB::state ) {
print $DB::OUT " ***\n";
for my $option ( sort keys %$_ ) {
my $value = $_->{ $option };
$value = ref $value ? ref $value : $value;
print $DB::OUT ' ', $option, " = $value\n";
}
my $CNT = 5;
for( @{ $_->{ stack } } ) {
last if $CNT-- == 0;
print $DB::OUT " ";
for my $key ( sort keys %$_ ) {
my $value = $_->{ $key };
$value = ref $value ? ref $value : $value;
print $DB::OUT " $key => $value;";
}
print $DB::OUT "\n";
}
}
print $DB::OUT ' ', '-'x20 ."\n";
}
# Force access into last instance if we are in debugger
my $inDB = $DB::state->[ -1 ]{ inDB };
my $level = -1;
$level = -2 if @$DB::state >= 2 && !$inDB && $name ne 'inDB';
my $instance = $DB::state->[ $level ];
if( $debug && ( @_ >= 2 || $debug >= 2 ) ) {
my($file, $line) = (caller 0)[1,2];
$file =~ s'.*?([^/]+)$'$1'e;
print $DB::OUT " " .-$level ." $file:$line: ";
}
unless( $instance ) {
my($file, $line) = (caller 0)[1,2];
$file =~ s'.*?([^/]+)$'$1'e;
print $DB::OUT "!!!!!! No debugger at level: $level at $file:$line<<<<<<<<<\n";
return;
}
if( $name eq 'instance' ) {
print $DB::OUT " INT::instance\n" if $debug && ( @_ >= 2 || $debug >= 2 );
return $instance;
}
$name = '*' unless exists $DB::variables->{ $name };
return $DB::variables->{ $name }({()
,debug => $debug
,instance => $instance
}
,@_
);
}
sub _ddd {
return $DB::state->[ -1 ]{ ddd };
}
sub new {
my $ddd = DB::state( 'ddd' );
# NOTICE: After creating new debugger instance we are in debugger yet
# So we set { inDB } flag. It allows us safely initialize new debugger
# instance through &DB::state ( see &DB::state ). We do not do that directly
# to spy which state and how it is changed when { ddd } is turned on
my $dbg_instance = bless { inDB => 1, stack => [ {()
,goto_frames => []
# ,type => 'D'
} ], @_ }, $DB::dbg;
push @$DB::state, $dbg_instance;
# New debugger instance should have same { ddd } flag
# DB::state( 'ddd', $ddd ) if defined $ddd;
if( @$DB::state > 1 ) {
my @events = grep{ /^on_/ } keys %{ $DB::state->[-2] };
@{ $DB::state->[-1] }{ @events } = @{ $DB::state->[-2] }{ @events };
}
print $DB::OUT "\nIN DEBUGGER >>>>>>>>>>>>>>>>>>>>>>\n\n"
if DB::state( 'ddd' );
my $self;
}
sub DESTROY {
# Clear { dd } flag to prevent debugging for next command
DB::state( 'dd', undef );
DB::state( 'debug', undef );
print $DB::OUT "\nOUT DEBUGGER <<<<<<<<<<<<<<<<<<<<<<\n\n"
if _ddd;
pop @$DB::state;
# NOTICE: previous frame is always have { inDB } flag on because there is
# no any way to run new debugger instance as from debugger
# (See &DB::scall and assert { inDB } check)
}
# Used perl internal variables:
# ${ ::_<filename } # maintained at 'file' and 'sources'
# @{ ::_<filename } # maintained at 'source' and 'can_break'
# %{ ::_<filename } # maintained at 'traps'
# $DB::single
# $DB::signal
# $DB::trace
# $DB::sub # NOTICE: this maybe the reference to sub, not just the name of it
# %DB::sub # maintained at 'location' and 'subs'
# %DB::postponed
# @DB::args # maintained at 'frames'
# Perl sets up $DB::single to 1 after the 'script.pl' is compiled, so we are able
# to debug it from first OP. We can disable this feature through NonStop option.
our $dbg; # debugger object/class
# our $package; # current package
# our $file; # current file
# our $line; # current line number
# our @goto_frames; # save sequence of places where nested gotos are called
our $commands; # hash of commands to interact user with debugger
# our @stack; # array of hashes that keeps aliases of DB::'s ours for current frame
# This allows us to spy the DB::'s values for a given frame
# our $ddlvl; # Level of debugger debugging <= @$DB::state
# our $dbg_call; # keep silent at DB::sub/lsub while do external call from DB::*
# our $inDB; # Flag which shows we are currently in debugger
# our $inSUB; # Flag which shows we are currently in debugger
# TODO? does it better to implement TTY object?
our $IN;
our $OUT;
our %options;
our $interaction; # True if we interact with dbg client
our $variables; # Hash which defines behaviour for values available through &DB::state
# There three types of variables:
# Debugger internal variables -- global values from DB:: package
# Debugger instance variables -- values which exists in current debugger instance
# Frame variables -- values for each sub call
# Do DB:: configuration stuff here
# Default debugger behaviour while it is loading
BEGIN {
$DB::variables = {()
,'*' => \&dbg_vrbl
,single => \&int_vrbl
,on_frame => \&frm_vrbl
,file => \&frm_vrbl
,goto_frames => \&frm_vrbl
,line => \&frm_vrbl
,package => \&frm_vrbl
,sub => \&frm_vrbl
,type => \&frm_vrbl
,eval => \&frm_vrbl
};
$IN //= \*STDIN;
#TODO: cache output until debugger is connected
$OUT //= \*STDOUT;
#FIX: Where apply 'ddd' from command line?
DB::new;
DB::state( single => $DB::single );
$options{ undef } //= ''; # Text to print for undefined values
# $options{ dd } //= 0; # controls debugger debugging
# $options{ ddd } //= 0; # print debug info
$options{ s } //= 0; # compile time option
$options{ w } //= 0; # compile time option
# TODO: camelize options. Q: Why?
$options{ frames } //= -1; # compile time & runtime option
$options{ dbg_frames } //= 0; # compile time & runtime option
#options{ save_path } # TODO: save code path for displaying by graphviz
$DB::postponed{ 'DB::DB' } = 1;
#NOTE: we should always trace goto frames. Hiding them will prevent
# us to complete our work - debugging.
# But we still allow to control this behaviour at compiletime & runtime
# $options{ trace_goto }; #see DH:import # compile time & runtime option
$^P |= 0x80;
}
# TODO: describe qw/ frames dbg_frames trace_load trace_subs
# trace_returns / options
# $options{ NonStop } - if true then 0x20 flag is flushed
# $^P default values
# ! x
# 0111 0011 1111
# |||| |||| |||^-- Debug subroutine enter/exit.
# |||| |||| ||^--- Line-by-line debugging.
# |||| |||| |^---- Switch off optimizations.
# |||| |||| ^----- Preserve more data for future interactive inspections.
# |||| ||||
# |||| |||^------- Keep info about source lines on which a subroutine is defined.
# |||| ||^-------- Start with single-step on.
# |||| |^--------- Use subroutine address instead of name when reporting.
# |||| ^---------- Report goto &subroutine as well.
# ||||
# |||^------------ Provide informative "file" names for evals based on the place they were compiled.
# ||^------------- Provide informative names to anonymous subroutines based on the place they were compiled.
# |^-------------- Save source code lines into @{"_<$filename"}.
# ^--------------- When saving source, include evals that generate no subroutines.
# < When saving source, include source that did not compile.
# NOTICE: it is better to not use any modules from this one
# because we do not want that they appear to compiler before
# we can track module loading and subs calling process
# Also it is safe that descendant debugger module 'use' us. BUT BE AWARE!!!
# That module should not use any module before this one
# otherwise sub calls and module loading will not be tracked
#
# When we 'use' descendant debugger at the end our module appears last at load chain.
# Also there is a problem how to pass descendant class name to 'use' it.
# Keep this comment for history. Find this commit at 'git blame' to see what was changed
BEGIN {
if( $options{ w } ) { require 'warnings.pm'; 'warnings'->import(); }
if( $options{ s } ) { require 'strict.pm'; 'strict'->import(); }
if( $options{ d } ) { require 'Data/Dump.pm'; 'Data::Dump'->import( 'pp'); }
# http://perldoc.perl.org/warnings.html
# The scope of the strict/warnings pragma is limited to the enclosing block.
# But this not truth.
# It is limited to the first enclosing block of the BEGIN block
}
# NOTICE: Because of DB::DB, DB::sub, DB::postpone etc. subs take effect
# as soon as compiled we should &applyOptions at compile time
BEGIN { # Initialization goes here
# When we 'use Something' from this module the DB::sub is called at compile time
# If we do not we can still init them when define
$DB::interaction //= 0;
# TODO: set $DB::trace at CT
# Some configuration options may be applied when debugger is loading
# When debugger is loaded its &import subroutine will be called (see comment there)
applyOptions();
}
# Hooks to Perl's internals should be first.
# Because debugger or its descendants may call them at compile time
{
{
BEGIN{ 'strict'->unimport( 'refs' ) if $options{ s } }
sub dd {
eval "use Data::Dump";
Data::Dump::pp( @_ );
}
# Returns TRUE if $filename was compiled/evaled
# The file is evaled if it looks like (eval 34)
# But this may be changed by #file:line. See ??? for info
sub file {
my $filename = shift // state( 'file' );
unless( exists ${ 'main::' }{ "_<$filename" } ) {
warn "File '$filename' is not compiled yet";
return;
}
return ${ "::_<$filename" };
}
# Returns source for $filename
sub source {
my $filename = shift // state( 'file' );
return unless file( $filename );
return \@{ "::_<$filename" };
}
# Returns list of compiled files/evaled strings
# The $filename for evaled strings looks like (eval 34)
sub sources {
return grep{ s/^_<// } keys %{ 'main::' }; #/
}
sub deparse {
my( $coderef ) = shift;
require B::Deparse;
return $coderef unless ref $coderef;
return B::Deparse->new("-p", "-sC")->coderef2text( $coderef );
}
# Returns hashref of traps for $filename keyed by $line
sub traps {
#TODO: remove default because current position != view position
# this makes confusion
my $filename = shift // state( 'file' );
return unless file( $filename );
# Keep list of $filenames we perhaps manipulate traps
$DB::_tfiles->{ $filename } = 1;
*dbline = $main::{ "_<$filename" }; #WORKRAOUND RT#119799 (see commit)
return \%{ "::_<$filename" };
}
# Returns TRUE if we can set trap for $file:line
sub can_break {
my( $file, $line ) = @_;
($file, $line) = split ':', $file
unless defined $line;
return unless defined( $file = file( $file ) );
# TODO: testcase for negative lines
return ($line<0?-$line-1:$line) <= $#{ "::_<$file" }
&& ${ "::_<$file" }[ $line ] != 0;
# http://perldoc.perl.org/perldebguts.html#Debugger-Internals
# Values in this array are magical in numeric context:
# they compare equal to zero only if the line is not breakable.
}
}
sub eval_cleanup {
DB::state( 'inDB', 1 );
DB::state( 'eval', undef );
}
mutate_sub_is_debuggable( \&eval_cleanup, 0 );
# We put code here to execute it only once
(my $usercontext = <<' CODE') =~ s#^\t\t##gm;
BEGIN{
( $^H, ${^WARNING_BITS}, my $hr ) = @DB::context[1..3];
%^H = %$hr if $hr;
}
# $@ is cleared when compiller enters *eval* or *BEGIN* block
$@ = $DB::context[4];
CODE
# http://perldoc.perl.org/functions/eval.html
# We may define eval in other package if we want to place eval into other
# namespace. It will still "doesn't see the usual surrounding lexical scope"
# because "it is defined in the DB package"
# sub My::eval {
sub eval {
my( $expr ) = @_;
# BUG: PadWalker does not show DB::eval's lexicals
# Q? It is better that PadWalker return undef instead of warn when out of level
print $DB::OUT "Evaluating '$expr'...\n" if DB::state( 'ddd' );
establish_cleanup \&eval_cleanup;
DB::state( 'eval', 1 );
my $package = DB::state( 'package' );
DB::state( 'inDB', undef );
# Read BEWARE at DebugHooks.pod about localization of globals
local $^D;
local $_ = $DB::context[5];
local @_ = @{ $DB::context[0] };
eval "$usercontext; package $package;\n#line 1\n$expr";
#NOTICE: perl implicitly add semicolon at the end of expression
#HOWTO reproduce. Run command: X::X;1+2
#
# print $DB::OUT "Error occur while evaluating: $@" if $@
# But if we do this we return wrong value
}
# Returns the location where $subname is defined in the form:
# filename:startline-endline
sub location {
my $subname = shift;
return unless $subname;
return ">>$subname<<" if ref $subname; # The subname maybe a coderef
# The subs from DB::* are not placed here. Why???
# A? Maybe they are placed after module loaded?
return $DB::sub{ $subname };
}
# Returns list of all defined not ANON subs.
# We may limit the list by supplying regex
sub subs {
return keys %DB::sub unless @_;
my $re = shift;
return grep { /$re/ } keys %DB::sub;
}
# Returns caller frame info with arguments at given level
# or all call stack with goto frames
sub frames {
my $level = shift;
if( defined $level ) {
# https://rt.perl.org/Public/Bug/Display.html?id=126872#txn-1380132
# Note that we should ignore our frame, so +1
my @frame = caller( $level +1 );
return ( [ @DB::args ], @frame );
}
orig_frames() if $options{ orig_frames };
# For uninitialized values in frames
# $wantarray is undefined in void context, for example
BEGIN{ 'warnings'->unimport( 'uninitialized' ) if $DB::options{ w } }
my @frames;
$level = 0;
local $" = ' -';
# The $inDB is an internal variable of DB:: module. If it is true
# then we know that debugger frames are exists. In other case no sense
# to check callstask for frames generated by debugger subs
if( DB::state( 'inDB' ) ) {
my $found = 0;
# Skip debugger frames from stacktrace
while( my @frame = caller($level++) ) {
# print "DBGF: @frame[0..3,5]\n" if $options{ dbg_frames };
push @frames, [ 'D', [ @DB::args ], @frame] if $options{ dbg_frames };
if( $frame[3] eq 'DB::trace_subs' ) {
$found = 1;
# my $args = [ @DB::args ];
my @gframe = caller($level);
if( @gframe && $gframe[ 3 ] eq 'DB::goto' ) {
# print "DBGF: @gframe[0..3,5]\n" if $options{ dbg_frames };
# TODO: implement testcase: 'T' should show args for sub calls
push @frames, [ 'D', [ @DB::args ], @gframe] if $options{ dbg_frames };
$level++;
}
else {
# Because there is no DB::goto frame in stack
# we are sure that the @DB::goto_frames will not contain
# goto frames also. But only one initial sub frame
$level--;
# use Data::Dump qw/ pp /;
# print pp \@DB::goto_frames, \@gframe; print "<<<<<<<\n";
# $frame[3] = $DB::goto_frames[0][3];
# push @frames, [ $DB::goto_frames[0][5], $args, @frame ];
}
last;
}
if( $frame[3] eq 'DB::DB' ) {
$found = 1;
last;
};
}
# We can not make $DB::inDB variable private because we use localization
# In theory someone may change the $DB::inDB from outside
# Therefore we prevent us from empty results when debugger frames
# not exist at the stack
$level = 0 unless $found;
}
my $count = $options{ frames };
my $ogf = my $gf = DB::state( 'goto_frames' );
while( $count && (my @frame = caller( $level++ )) ) {
# The call to DB::trace_subs replaces right sub name of last call
# We fix that here:
$frame[3] = DB::state( 'goto_frames' )->[-1][3]
if $count == $options{ frames } && $frame[3] eq 'DB::trace_subs';
my $args = [ @DB::args ];
if( $options{ trace_goto }
&& $gf->[0][0] eq $frame[0]
&& $gf->[0][1] eq $frame[1]
&& $gf->[0][2] == $frame[2]
) {
$frame[3] = $gf->[0][3];
push @frames, [ $_->[5], $args, @$_[0..3] ] for @$gf[ reverse 1..$#$gf ];
$ogf = $gf;
$gf = $gf->[0][4];
}
push @frames, [ $ogf->[0][5], $args, @frame ];
} continue {
$count--;
}
return @frames;
}
# TODO: implement $DB::options{ trace_internals }
sub mcall {
my $method = shift;
my $context = DB::state( 'instance' );
print "mcall ${context}->$method\n"
if DB::state( 'ddd' );
my $sub = $context->can( $method );
scall( $sub, $context, @_ );
}
sub scall {
my $sub = sub_name( $_[0] ) || $_[0];
my $ddd = DB::state( 'ddd' );
my( $from, $f, $l );
if( $ddd ) {
my $lvl = 0;
if( (caller 1)[3] eq 'DB::mcall' ) {
$lvl++;
}
{ local $" = ', '; $sub .= "( @_[ 1..$#_ ] )"; }
($f, $l) = (caller $lvl)[1,2];
$f =~ s".*?([^/]+)$"$1";
$from = (caller $lvl+1)[3];
print $DB::OUT ">> scall from $from($f:$l) --> $sub\n";
}
# die "You can make debugger call only from debugger"
# unless DB::state( 'inDB' );
# FIX: http://perldoc.perl.org/perldebguts.html#Debugger-Internals
# (This doesn't happen if the subroutine -was compiled in the DB package.)
# ...was called and compiled in the DB package
# Any subroutine call invoke DB::sub again
# The right way is to turn off 'Debug subroutine enter/exit'
# local $^P = $^P & ~1; # But this works at compile time only.
# So prevent infinite DB::sub reentrance manually. One way to compete this:
# my $stub = sub { &$DB::sub };
# local *DB::sub = *DB::sub; *DB::sub = $stub;
# Another: the { inDB } flag
#IT: Call other debugger commands from current command
my $old_cmd = DB::state( 'cmd' );
# Manual localization
my $scall_cleanup = sub {
print_state "Debugger command DONE: $sub " if $ddd;
# NOTICE: Because we are in debugger here we should setup { inDB }
# flag but we are leaving debugger and interesting at user's context
DB::state( 'cmd', $old_cmd ); DB::state( 'single', 0, 1 ) if $old_cmd;
# $DB::single = DB::state( 'single' );
DB::state( 'single', DB::state( 'single' ) ) unless $old_cmd;
my $dd;
DB::DESTROY if ($dd = DB::state( 'dd' )) && $sub =~ /$dd/;
# Enable debugging after current command is finished
if( my $debug = DB::state( 'debug' ) ) {
DB::state( 'debug', undef );
my( $verbose, $sub ) = $debug =~ /^(\d+)?(?:@(.*))?$/;
# Set or flush debug flags depending on user's input
DB::state( 'ddd', $verbose // undef );
DB::state( 'dd', $sub // undef );
}
print $DB::OUT "<< scall back $from($f:$l) <-- $sub\n" if $ddd;
};
mutate_sub_is_debuggable( $scall_cleanup, 0 );
establish_cleanup $scall_cleanup;
# TODO: testcase 'a 3 DB::state( dd => 1 )'
# Create new debugger's state instance
my $dd;
if( ($dd = DB::state( 'dd' )) && $sub =~ /$dd/ ) {
# NOTICE: We should not set debugger states directly when create
# new state instance. We will not see changes at debug output
# So we use &DB::state after instance initialization
DB::new();
DB::state( 'single', 1 );
DB::state( 'inDB', undef );
$^D |= 1<<30;
}
else {
DB::state( 'single', 0, 1 ); # Prevent debugging for next call # THIS CONTROLS NESTING
DB::state( 'cmd', 1 );
}