-
Notifications
You must be signed in to change notification settings - Fork 2
/
perl5db.pl
4047 lines (3665 loc) · 117 KB
/
perl5db.pl
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
# perl5db.pl
#
# Modified version of PerlDB.pl, for use with the ActiveState
# debugger protocol, DBGp
# See http://aspn.activestate.com/ASPN/DBGP for more info.
#
# Copyright (c) 1998-2006 ActiveState Software Inc.
# All rights reserved.
#
# Xdebug compatibility, UNIX domain socket support and misc fixes
# by Mattia Barbon <mattia@barbon.org>
#
# This software (the Perl-DBGP package) is covered by the Artistic License
# (http://www.opensource.org/licenses/artistic-license.php).
# Start with some lengthy, unattributed comments from perl5db.pl
=head2 REMOTE DEBUGGING
Copy the following files from a Komodo installation to
the target system
<Komodo InstallDir>/perllib/* <TargetDir>
Set the following shell variables. On Windows use C<set>
instead of C<export>, use double-quoting instead of
single-quoting, and use backslashes instead of forward-slashes.
export PERLDB_OPTS=RemotePort=hostname:port
export PERL5DB='BEGIN { require q(<TargetDir>/perl5db.pl) }'
export PERL5LIB=<TargetDir>
export DBGP_IDEKEY="username"
=cut
=head2 FLAGS, FLAGS, FLAGS
There is a certain C programming legacy in the debugger. Some variables,
such as C<$single>, C<$trace>, and C<$frame>, have "magical" values composed
of 1, 2, 4, etc. (powers of 2) OR'ed together. This allows several pieces
of state to be stored independently in a single scalar.
=head4 C<$signal>
Used to track whether or not an C<INT> signal has been detected. C<DB::DB()>,
which is called before every statement, checks this and puts the user into
command mode if it finds C<$signal> set to a true value.
=head4 C<$single>
Controls behavior during single-stepping. Stacked in C<@stack> on entry to
each subroutine; popped again at the end of each subroutine.
=over 4
=item * 0 - run continuously.
=item * 1 - single-step, go into subs. The 's' command.
=item * 2 - single-step, don't go into subs. The 'n' command.
=item * 4 - print current sub depth (turned on to force this when "too much
recursion" occurs.
=back
=head4 C<@saved>
Saves important globals (C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, C<$^W>)
so that the debugger can substitute safe values while it's running, and
restore them when it returns control.
=head4 C<@stack>
Saves the current value of C<$single> on entry to a subroutine.
Manipulated by the C<c> command to turn off tracing in all subs above the
current one.
=head4 C<%dbline>
Keys are line numbers, values are "condition\0action". If used in numeric
context, values are 0 if not breakable, 1 if breakable, no matter what is
in the actual hash entry.
=cut
=head1 DEBUGGER INITIALIZATION
The debugger\'s initialization actually jumps all over the place inside this
package. This is because there are several BEGIN blocks (which of course
execute immediately) spread through the code. Why is that?
The debugger needs to be able to change some things and set some things up
before the debugger code is compiled; most notably, the C<$deep> variable that
C<DB::sub> uses to tell when a program has recursed deeply. In addition, the
debugger has to turn off warnings while the debugger code is compiled, but then
restore them to their original setting before the program being debugged begins
executing.
The first C<BEGIN> block simply turns off warnings by saving the current
setting of C<$^W> and then setting it to zero. The second one initializes
the debugger variables that are needed before the debugger begins executing.
The third one puts C<$^X> back to its former value.
We'll detail the second C<BEGIN> block later; just remember that if you need
to initialize something before the debugger starts really executing, that's
where it has to go.
=cut
package DB;
sub DB {}
BEGIN {
# kill the empty sub installed by Enbugger
my ($scalar, $array, $hash) = (*DB::sub{SCALAR}, *DB::sub{ARRAY}, *DB::sub{HASH});
undef *DB::sub;
*DB::sub = $scalar; *DB::sub = $array; *DB::sub = $hash;
}
sub DEBUG_ALL() { 0x7ff }
sub DEBUG_SINGLE_STEP_ON() { 0x20 }
sub DEBUG_USE_SUB_ADDRESS() { 0x40 }
sub DEBUG_REPORT_GOTO() { 0x80 }
sub DEBUG_DEFAULT_FLAGS() # 0x73f
{ DEBUG_ALL & ~(DEBUG_USE_SUB_ADDRESS|DEBUG_REPORT_GOTO) }
sub DEBUG_PREPARE_FLAGS() # 0x73c
{ DEBUG_ALL & ~(DEBUG_USE_SUB_ADDRESS|DEBUG_REPORT_GOTO|DEBUG_SINGLE_STEP_ON) }
sub DB_RECURSIVE_DEBUG() { 0x40000000 }
# 'my' variables used here could leak into (that is, be visible in)
# the context that the code being evaluated is executing in. This means that
# the code could modify the debugger's variables.
#
# Fiddling with the debugger's context could be Bad. We insulate things as
# much as we can.
sub eval {
# 'my' would make it visible from user code
# but so does local! --tchrist
# Remember: this localizes @DB::res, not @main::res.
local @res;
{
# Try to keep the user code from messing with us. Save these so that
# even if the eval'ed code changes them, we can put them back again.
# Needed because the user could refer directly to the debugger's
# package globals (and any 'my' variables in this containing scope)
# inside the eval(), and we want to try to stay safe.
local $otrace = $trace;
local $osingle = $single;
local $od = $^D;
local $op = $^P;
local ($^W) = 0; # Switch run-time warnings off during eval.
# speed up evaluation if no recursive debugging is required
clobber_db_sub() unless $^D & DB_RECURSIVE_DEBUG;
$^P = DEBUG_PREPARE_FLAGS unless $^D & DB_RECURSIVE_DEBUG;
# Untaint the incoming eval() argument.
{ ($evalarg) = $evalarg =~ /(.*)/s; }
# $usercontext built in DB::DB near the comment
# "set up the context for DB::eval ..."
# Evaluate and save any results.
# Do this in case there are user args in the expression --
# pull them from the user's context.
local @_; # Clear each time.
local @unused = caller($evalSkipFrames);
local $additionalLevels = 0;
# first term is for the extra stack frame of pure-Perl DB::sub
# second term is for eval BLOCK stack frames
local $notRealSubCall = $unused[0] eq 'DB' || ($unused[3] eq '(eval)' && !$unused[4]);
while ($evalStackLevel > 0 || $notRealSubCall) {
$evalStackLevel-- if !$notRealSubCall;
$additionalLevels++;
@unused = caller($evalSkipFrames + $additionalLevels);
$notRealSubCall = $unused[0] eq 'DB' || ($unused[3] eq '(eval)' && !$unused[4]);
last unless @unused;
}
if ($unused[4]) {
# hasargs field is set -- an instance of @_ was set up.
eval { @_ = @args; };
@_ = () if $@;
}
my $usercontext2 = (($evalarg =~ /[\$\@\%]\w*[^\x00-\x7f]/)
? "$usercontext use utf8; "
: $usercontext);
@res = eval "$usercontext2 $evalarg;\n"; # '\n' for nice recursive debug
if ($ldebug) {
if ($@) {
dblog("eval($evalarg) => exception [$@]\n");
} elsif (scalar @res) {
if (substr($evalarg, 0, 1) eq '%') {
dblog("eval($evalarg) => [hash val]\n");
} elsif (scalar @res == 1 && ! defined $res[0]) {
dblog("eval($evalarg) => (undef)\n");
$no_value = 1;
@res = ("");
} else {
my $str_out = join('', @res);
my $max_len = $settings{max_data}[0];
$max_len = 103 if $max_len > 103;
if (length($str_out) > $max_len) {
$str_out = substr($str_out, 0, $max_len - 3) . '...';
}
$str_out = nonXmlChar_Encode($str_out) unless ref $str_out;
dblog("eval($evalarg) => <<$str_out>>\n");
}
} else {
dblog("eval($evalarg) => no value\n");
$no_value = 1;
@res = ("");
}
} elsif (!$@ && scalar @res == 1 && ! defined $res[0]) {
$no_value = 1;
@res = ("");
}
# Restore those old values.
$trace = $otrace;
$single = $osingle;
$^D = $od;
$^P = $op;
restore_db_sub() unless $^D & DB_RECURSIVE_DEBUG;
}
# Save the current value of $@, and preserve it in the debugger's copy
# of the saved precious globals.
my $at = $@;
# Since we're only saving $@, we only have to localize the array element
# that it will be stored in.
local $saved[0]; # Preserve the old value of $@
eval { &save };
# Now see whether we need to report an error back to the user.
if ($at) {
die $at;
}
@res;
} ## end sub eval
# moved here to avoid it seeing the lexical context
sub simple_eval {
eval $_[0];
}
use strict qw(vars subs);
use IO::Handle;
# Debugger for Perl 5.00x; perl5db.pl patch level:
our $VERSION = 0.30;
# $Log$
=head1 DEBUGGER INITIALIZATION
The debugger starts up in phases.
=head2 BASIC SETUP
First, it initializes the environment it wants to run in: turning off
warnings during its own compilation, defining variables which it will need
to avoid warnings later, setting itself up to not exit when the program
terminates, and defaulting to printing return values for the C<r> command.
=cut
our ($no_value, $evalarg, $usercontext, $evalSkipFrames, $evalStackLevel, @saved); # used by sub eval above
our ($single, $trace, $signal, $sub, %sub, @args);
our ($ldebug); # it should be my (), as all other $ldebug around the code
my ($currentFilename, $currentLine);
my ($pending_check_enabled, $pending_check_count, $pending_check_lim, $pending_check_timeout, $pending_check_interval, $skip_alarm, @pending_commands);
my ($setup_once_after_connection, $ready, $ini_warn);
my %firstFileInfo;
my (@stack, $deep);
our ($stack_depth, $level); # for local()
BEGIN {
# Switch compilation warnings off until another BEGIN.
$ini_warn = $^W;
$^W = 0;
#init $deep to avoid warning
# By default it doesn't stop.
$deep = -1;
$skip_alarm = 1;
# True if we're logging
$ldebug = 0;
# uninitialized warning suppression
$signal = $single = $trace = 0;
# important stuff
@stack = (0);
$stack_depth = 0; # Localized repeatedly; simple way to track $#stack
$level = 0;
$evalSkipFrames = $evalStackLevel = 0;
}
local ($^W) = 0; # Switch run-time warnings off during init.
# more stuff
require Config;
# We set these variables to safe values. We don't want to blindly turn
# off warnings, because other packages may still want them.
my ($finished, $runnonstop, $fall_off_end) = (0, 0, 0);
our ($inPostponed) = (0); # because of local()
my @postponedFiles;
=head1 DEBUGGER SETTINGS
Keep track of the various settings in this hash
=cut
use DB::DbgrCommon;
use DB::DbgrProperties;
use DB::DbgrContext;
use DB::DbgrXS;
my %supportedCommands = (
status => 1,
feature_get => 1,
feature_set => 1,
run => 1,
step_into => 1,
step_over => 1,
step_out => 1,
stop => 1, #xxxstop
detach => 1,
breakpoint_set => 1,
breakpoint_get => 1,
breakpoint_update => 1,
breakpoint_remove => 1,
breakpoint_list => 1,
stack_depth => 1,
stack_get => 1,
context_names => 1,
context_get => 1,
typemap_get => 1,
property_get => 1,
property_set => 1,
property_value => 1,
source => 1,
stdout => 1,
stderr => 1,
stdin => 0,
break => 0,
'eval' => 1,
interact => 0,
);
# Feature name => [bool(3): is supported, is settable, has associated value]
my %supportedFeatures = (
encoding => [1, 1, 1],
data_encoding => [1, 1, 1],
max_children => [1, 1, 1],
max_data => [1, 1, 1],
max_depth => [1, 1, 1],
multiple_sessions => [0, 0, 0],
language_supports_threads => [0, 0, 0],
language_name => [1, 0, 1],
language_version => [1, 0, 1],
protocol_version => [1, 0, 1],
supports_async => [0, 0, 0],
multiple_sessions => [0, 0, 0],
);
# Feature name => [value, allowed settable values, if constrained]
# this is shared with DB::DbgrCommon and DB::DbgrProperties via exporting
%settings = (
encoding => ['UTF-8', ['UTF-8', 'iso-8859-1']],
# binary and 'none' are the same
data_encoding => ['base64', [qw(urlescape base64 none binary)]],
max_children => [10, 1],
max_data => [32767, 1],
max_depth => [1, 1],
language_name => ['Perl'],
language_version => [sprintf("%vd", $^V)],
protocol_version => ['1.0'],
);
sub xsdNamespace() {
return q(xmlns:xsd="http://www.w3.org/2001/XMLSchema");
}
sub xsiNamespace() {
return q(xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance");
}
sub decodeData($;$) {
my ($str, $encoding) = @_;
my $finalStr;
my $currDataEncoding = defined $encoding ? $encoding : $settings{data_encoding}->[0];
$finalStr = $str;
eval {
if ($currDataEncoding eq 'none' || $currDataEncoding eq 'binary') {
$finalStr = $str;
} elsif ($currDataEncoding eq 'urlescape') {
$finalStr = DB::CGI::Util::unescape($str);
} elsif ($currDataEncoding eq 'base64') {
$finalStr = DB::MIME::Base64::decode_base64($str);
} else {
dblog("Converting $str with unknown encoding of $currDataEncoding\n") if $ldebug;
$finalStr = $str;
}
};
if ($ldebug) {
if ($@) {
# Log the string that caused problems.
$str = (substr($str, 0, 100) . '...') if length($str) > 100;
dblog("decodeData($str) => [$@]\n");
}
}
return $finalStr;
}
my $fakeFirstStepInto = 0;
my $sentInitString = 0;
my $startedAsInteractiveShell = undef;
my $lastContinuationCommand = undef;
my $lastContinuationStatus = 'break';
my $lastTranID = 0; # The transactionID that started
my $stopReason = STOP_REASON_STARTING();
my @stopReasons = (qw(starting stopping stopped running break interactive));
=head1 StopReasons
Why we are stopping
=over 4
=item * 0 - started program
=item * 1 - user did a step_into
=item * 2 - user did a step_over
=item * 4 - user did a step_out
=item * 8 - program hit max-recursion depth
=back
=cut
# open input and output (to and from console)
open(IN, "<&STDIN") || warn "open(IN)";
open(OUT, ">&STDERR") || open(OUT, ">&STDOUT") || warn "open(OUT)";
# force autoflush of output
eval {
select(OUT);
$| = 1; # for DB::OUT
select(STDERR);
$| = 1;
select(STDOUT);
$| = 1; # for real STDOUT
};
# Variables and subs for doing option processing
# (Copied from standard perl5db.pl to support PDK products)
my $remoteport;
my $remotepath;
my $connect_at_start = 1;
my $keep_running = 0;
my $xdebug_file_line_in_step = undef;
our $xdebug_no_value_tag = undef; # used by DB::DbgrProperties
my $xdebug_full_values_in_context = undef;
my $xdebug_temporary_breakpoint_state = undef;
# If the PERLDB_OPTS variable has options in it, parse those out next.
if (defined $ENV{PERLDB_OPTS}) {
parse_options($ENV{PERLDB_OPTS});
}
if (!defined $remoteport && !defined $remotepath) {
if (exists $ENV{RemotePort}) {
$remoteport = $ENV{RemotePort};
} else {
die "Env variable RemotePort not set.";
}
}
if ($remoteport =~ /^\d+$/) {
die "Env variable RemotePort not numeric (set to $remoteport).";
}
my $has_xs = 0;
if (DB::DbgrXS::HAS_XS() && !$ENV{DBGP_PURE_PERL}) {
eval {
require XSLoader;
XSLoader::load('dbgp-helper::perl5db');
use_xs_sub();
$has_xs = 1;
1;
} or do {
my $error = $@ || "Unknown error";
dblog("Error loading XS code: $error") if $ldebug;
if ($ENV{DBGP_XS_ONLY}) {
dblog("Not falling back to pure-Perl, as per DBGP_XS_ONLY");
die "Aborting after error loading XS code: $error";
}
};
} else {
if ($ENV{DBGP_XS_ONLY}) {
dblog("DBGP_XS_ONLY but XS not compiled: aborting");
die "DBGP_XS_ONLY but XS not compiled: aborting";
}
}
sub emitBanner {
my $version_str;
if ($Config::Config{PERL_REVISION}) {
$version_str = $Config::Config{PERL_REVISION};
if ($Config::Config{PERL_VERSION}) {
$version_str .= '.' . $Config::Config{PERL_VERSION};
if ($Config::Config{PERL_SUBVERSION}) {
$version_str .= '.' . $Config::Config{PERL_SUBVERSION};
}
}
} else {
$version_str = $];
}
my $str = "# ";
$str .= ($Config::Config{cf_by} =~ /activestate/i
? "ActivePerl" : ($Config::Config{perl} || "Perl"));
$str .= " v$version_str";
$str .= " [$Config::Config{archname}]\n";
# $str .= "# Type `perl -v` for more info.\n";
print STDOUT $str;
}
my ($PID, $IN, $OUT, $OUT_selector);
sub disconnect {
# force-close any copies of the file descriptor in other processes
if (ref $OUT and UNIVERSAL::isa($OUT, 'IO::Socket')) {
$OUT->shutdown(2);
}
$OUT = $IN = $OUT_selector = undef;
$stopReason = STOP_REASON_STARTING();
$lastContinuationCommand = undef;
$lastContinuationStatus = 'break';
$lastTranID = 0; # The transactionID that started
}
sub connectOrReconnect {
dblog("Trying to open connection to client") if $ldebug;
$PID = $$;
disconnect() if $OUT;
# If RemotePort was defined in the options, connect input and output
# to the socket.
require IO::Socket;
if ($remoteport) {
$OUT = new IO::Socket::INET(
Timeout => '10',
PeerAddr => $remoteport,
Proto => 'tcp',
);
} elsif ($remotepath) {
$OUT = new IO::Socket::UNIX(
Timeout => '10',
Peer => $remotepath,
);
}
# disabled by 'detach'
map { $supportedCommands{$_} = 1 } (qw(run step_into step_over step_out detach));
if (!$OUT) {
my ($error_num, $error_str) = ($!, "$!");
if ($remoteport) {
dblog("Unable to connect to remote host: $remoteport ($error_str)") if $ldebug;
warn "Unable to connect to remote host: $remoteport ($error_str)\n";
} else {
dblog("Unable to connect to Unix socket: $remotepath ($error_str)") if $ldebug;
warn "Unable to connect to Unix socket: $remotepath ($error_str)\n";
}
dblog("Running program outside the debugger") if $ldebug;
warn "Running program outside the debugger...\n";
# Disable the debugger to keep the Perl program running
disable();
} else {
$signal = $single = $finished = $runnonstop = 0;
$stopReason = STOP_REASON_STARTING();
$sentInitString = 0;
$fakeFirstStepInto = 1;
setDefaultOutput($OUT);
$IN = $OUT;
eval {
require IO::Select;
$OUT_selector = IO::Select->new();
$OUT_selector->add($OUT);
# Indicate that we support asynchrousness
$supportedCommands{break} = 1;
if (!$skip_alarm) {
$supportedFeatures{supports_async} = [1, 1, 1];
$settings{supports_async} = [1];
$pending_check_enabled = 1;
}
$pending_check_count = 0;
$pending_check_lim = 100;
$pending_check_timeout = .000001;
$pending_check_interval = 1; # Check for a break every 1 second
@pending_commands = ();
};
# print "# Talking to port $remoteport\n" if $ldebug;
# Moved stuff to start of init loop
# sendInitString();
setupOnceAfterConnection();
}
}
sub isConnected { !!$OUT }
if (!$connect_at_start) {
# Keep going
disable();
} elsif (defined $remoteport || defined $remotepath) {
connectOrReconnect();
} else {
dblog("RemotePort not set for debugger") if $ldebug;
warn "RemotePort not set for debugger\n";
# Keep going
disable();
}
sub setupOnceAfterConnection {
return if $setup_once_after_connection;
# Unbuffer DB::OUT. We need to see responses right away.
my $previous = select($OUT);
# for DB::OUT
$| = 1;
select STDERR;
$| = 1;
select($previous);
# $single = 1;
if (!$skip_alarm) {
$SIG{ALRM} = \&_break_check_handler;
}
$setup_once_after_connection = 1;
}
# Set a breakpoint for the first line of breakable code now,
# so we don't have to duplicate the reason in two places.
# Chat with the debug server until we get a continuation command.
# things to help the breakpoint mechanism
# Data structures for managing breakpoints
use DB::DbgrURI qw(canonicalizeFName
canonicalizeURI
filenameToURI
uriToFilename
);
use DB::RedirectStdOutput;
use DB::CGI::Util;
use DB::MIME::Base64;
use constant BKPT_DISABLE => 1;
use constant BKPT_ENABLE => 2;
use constant BKPT_TEMPORARY => 3;
use constant BKPT_REQ_ENABLED => 'enabled';
use constant BKPT_REQ_DISABLED => 'disabled';
use constant BKPT_REQ_TEMPORARY => 'temporary';
# Indices into the breakpoint Table
use constant BKPTBL_FILEURI => 0;
use constant BKPTBL_LINENO => 1;
use constant BKPTBL_STATE => 2;
use constant BKPTBL_TYPE => 3;
use constant BKPTBL_FUNCTION_NAME => 4;
use constant BKPTBL_CONDITION => 5;
use constant BKPTBL_EXCEPTION => 6;
use constant BKPTBL_HIT_INFO => 7;
use constant HIT_TBL_COUNT => 0; # No. Times we've hit this bpt
use constant HIT_TBL_VALUE => 1; # Target hit value
use constant HIT_TBL_EVAL_FUNC => 2; # Function to call(VALUE, COUNT)
use constant HIT_TBL_COND_STRING => 3; # Condition string
use constant STOP_REASON_STARTING => 0;
use constant STOP_REASON_STOPPING => 1;
use constant STOP_REASON_STOPPED => 2;
use constant STOP_REASON_RUNNING => 3;
use constant STOP_REASON_BREAK => 4;
use constant STOP_REASON_INTERACT => 5;
use DB::Data::Dump;
use File::Basename;
use File::Spec;
use Getopt::Std;
# Load the proper base class at compile time
BEGIN {
require File::Spec::Functions;
if ($^O eq 'MSWin32') {
require File::Spec::Win32;
} else {
require File::Spec::Unix;
}
my $junk = File::Spec::Functions::devnull();
dblog("dev-null => $junk");
}
my @bkptLookupTable = (); # Map fileURI_No -> hash of (lineNo => breakPtID)
my %bkptInfoTable = (); # Map breakPtID -> [fileURINo, lineNo, state, type, function, expression, exception, hitInfo]
my %FQFnNameLookupTable = (); # Map fully qualified fn names =>
# { call => breakPtID, return => breakPtID }
my @fileNameTable = (); # Map fileURI_No => [
# $bFileURI,
# $bFileName, (fwd slashes)
# $perlFileName (backwd slashes)
# ]
my %watchedExpressionLookupTable = (); # Map watchedExpn => breakPtID
my $nextBkPtIndex = 0;
my (@watchPoints, @watchPointValues);
my $numWatchPoints = 0;
my ($tiedStdout, $tiedStderr);
# End of initialization code.
my $full_dbgp_prefix;
{
my $hostname = 'unknown';
local $@;
eval {
require 'Sys/Hostname.pm';
$hostname = Sys::Hostname::hostname();
$hostname =~ s/\..*$//; # Keep only the first part of a dotted name
$hostname =~ s/[^-_\w\d]+/_/g; # Turn non-alnums to safe chars
dblog("**** \$hostname=$hostname") if $ldebug;
};
if ($@) {
dblog("Error -- [$@]\n") if $ldebug;
}
$full_dbgp_prefix = "dbgp://perl/$hostname/$$";
}
{
require Cwd;
# get current directory
my $cwd = Cwd::cwd();
# cwd bug: returns C: rather than C:/ if we're in the root
if ($cwd =~ /^[A-Z]:$/i) {
$cwd .= "/";
}
DB::DbgrURI::init(ldebug => $ldebug, cwd => $cwd);
}
# Handle postponed requests that came in earlier.
finish_postponed();
$ready = 1;
$single = 0;
sub sendInitString {
# Send the init command at this point
my $ppid = $ENV{DEBUGGER_APPID} || "";
my $appid = $$; # getpid
my $ideKey = $ENV{DBGP_IDEKEY} || "";
my $initString = sprintf(qq(%s\n<init %s
appid="%s"
idekey="%s"
parent="%s"
),
xmlHeader(),
namespaceAttr(),
$appid,
$ideKey,
$ppid,
);
if (exists $ENV{DBGP_COOKIE} && $ENV{DBGP_COOKIE}) {
$initString .= qq( session="$ENV{DBGP_COOKIE}");
}
$initString .= sprintf(qq( thread="%s"
language="%s"
protocol_version="%s"),
0, # Main thread in a program defined to be 0
'Perl', # Language
$settings{protocol_version}[0],
);
if ($startedAsInteractiveShell) {
$initString .= ' interactive="%"';
} else {
$initString .= ' fileuri="' . filenameToURI($0, 0) . '"';
}
my $hostname;
if (!($hostname = $ENV{HOST_HTTP})) {
# Get the hostname from perl
require Sys::Hostname;
$hostname = eval { Sys::Hostname::hostname() };
}
$initString .= qq( hostname="$hostname") if $hostname;
$initString .= '/>';
printWithLength($initString);
$ENV{DEBUGGER_APPID} = $appid;
}
sub getArg {
my ($cmdArgsARef, $optString) = @_;
my $i;
# Don't look at the last arg -- if it's an option, we're out of luck
for ($i = 0; $i <= $#$cmdArgsARef - 1; $i++) {
if ($cmdArgsARef->[$i] eq $optString) {
return splice(@$cmdArgsARef, $i, 2);
} elsif ($cmdArgsARef->[$i] eq '--') {
last;
}
}
return undef;
}
# Never delete entries here.
my (%fileURILookupTable, %perlNameToFileURINo, @fileURI_No_ReverseLookupTable);
sub internFileURI {
my ($bFileURI) = @_;
$bFileURI = canonicalizeURI($bFileURI);
if (!exists $fileURILookupTable{$bFileURI}) {
my $tblSize = scalar keys %fileURILookupTable;
$fileURILookupTable{$bFileURI} = $tblSize + 1;
$fileURI_No_ReverseLookupTable[$tblSize + 1] = $bFileURI;
}
return $fileURILookupTable{$bFileURI};
}
sub internFileURINo_LineNo {
my ($bFileURINo, $bLine) = @_;
if (!$bkptLookupTable[$bFileURINo]) {
$bkptLookupTable[$bFileURINo] = {$bLine => $nextBkPtIndex};
return $nextBkPtIndex++;
} elsif (! exists $bkptLookupTable[$bFileURINo]->{$bLine}) {
$bkptLookupTable[$bFileURINo]->{$bLine} = $nextBkPtIndex;
return $nextBkPtIndex++;
}
return $bkptLookupTable[$bFileURINo]->{$bLine};
}
sub internFunctionName_CallType_Breakpoint($$) {
my ($functionName, $bType) = @_;
if (! exists $FQFnNameLookupTable{$functionName}) {
$FQFnNameLookupTable{$functionName} = { $bType => $nextBkPtIndex };
return $nextBkPtIndex++;
} elsif (exists $FQFnNameLookupTable{$functionName}{$bType}) {
# Overwrite existing breakpoint
return $FQFnNameLookupTable{$functionName}{$bType};
} else {
$FQFnNameLookupTable{$functionName}{$bType} = $nextBkPtIndex;
return $nextBkPtIndex++;
}
}
sub internFunctionName_watchedExpn($) {
my ($bExpn) = @_;
if (! exists $watchedExpressionLookupTable{$bExpn}) {
$watchedExpressionLookupTable{$bExpn} = $nextBkPtIndex++;
}
return $watchedExpressionLookupTable{$bExpn};
}
sub getURIByNo {
my ($fileURINo) = @_;
return $fileURI_No_ReverseLookupTable[$fileURINo] || "";
}
sub storeBkPtInfo {
my ($bkptID, $bFileURINo, $bLine, $bstate, $bType, $bFunction, $bCondition) = @_;
$bkptInfoTable{$bkptID} = [$bFileURINo, $bLine, $bstate, $bType, $bFunction, $bCondition, undef, undef];
}
# No conditions, but we want to maintain a hit count on the breakpoint.
sub setNullBkPtHitInfo {
my ($bkptID) = @_;
$bkptInfoTable{$bkptID}[BKPTBL_HIT_INFO] = [0, 0, undef, undef];
}
# Take a target value and a string representing a hit condition,
# and return a closure encapsulating the test.
# We need to expose the target, so there's no point encapsulating
# it into the closure.
# $bkptHitCount is the current value (hit count) on the breakpoint
# $bkptHitValue is the target value
sub testGE {
my ($bkptHitCount, $bkptHitValue) = @_;
return $bkptHitCount >= $bkptHitValue;
}
sub testEQ {
my ($bkptHitCount, $bkptHitValue) = @_;
return $bkptHitCount == $bkptHitValue;
}
sub testMod {
my ($bkptHitCount, $bkptHitValue) = @_;
return $bkptHitValue > 0 && $bkptHitCount % $bkptHitValue == 0;
}
sub parseBkPtHitInfo($) {
my ($bkptHitConditionFunc) = @_;
if ($bkptHitConditionFunc eq '>=') {
return \&testGE;
} elsif ($bkptHitConditionFunc eq '==') {
return \&testEQ;
} elsif ($bkptHitConditionFunc eq '%') {
return \&testMod;
} else {
return undef;
}
}
sub setBkPtHitInfo($$$) {
my ($bkptID, $bkptHitValue, $bkptHitConditionString) = @_;
$bkptHitConditionString = '>=' if (!defined $bkptHitConditionString);
my $sub = parseBkPtHitInfo($bkptHitConditionString);
if (!defined $sub) {
# Formulate an error condition
return 0;
}
if (! defined $bkptInfoTable{$bkptID}[BKPTBL_HIT_INFO]) {
$bkptInfoTable{$bkptID}[BKPTBL_HIT_INFO] = [];
}
# Always reset hit-count to 0 -- part of bug 40561
$bkptInfoTable{$bkptID}[BKPTBL_HIT_INFO][HIT_TBL_COUNT] = 0;
$bkptInfoTable{$bkptID}[BKPTBL_HIT_INFO][HIT_TBL_VALUE] = $bkptHitValue; # Target
$bkptInfoTable{$bkptID}[BKPTBL_HIT_INFO][HIT_TBL_EVAL_FUNC] = $sub;
$bkptInfoTable{$bkptID}[BKPTBL_HIT_INFO][HIT_TBL_COND_STRING] = $bkptHitConditionString;
}
sub getBkPtInfo {
my ($bkptID) = @_;
if (!exists $bkptInfoTable{$bkptID} || (ref $bkptInfoTable{$bkptID}) ne 'ARRAY') {
return;
} else {
return wantarray ? @{$bkptInfoTable{$bkptID}} : $bkptInfoTable{$bkptID};
}
}
sub setBkPtState {
my ($bkptID, $bstate) = @_;
if (!exists $bkptInfoTable{$bkptID} || (ref $bkptInfoTable{$bkptID}) ne 'ARRAY') {
# No such breakpoint
return 0;
}
$bkptInfoTable{$bkptID}->[2] = $bstate;
return 1;
}
sub getBkPtState {
my ($bkptID, $bstate) = @_;
if (!exists $bkptInfoTable{$bkptID} || (ref $bkptInfoTable{$bkptID}) ne 'ARRAY') {
# No such breakpoint
return BKPT_DISABLE;
}
return $bkptInfoTable{$bkptID}->[2];
}
sub deleteBkPtInfo {
my ($bkptID) = @_;
if (!exists $bkptInfoTable{$bkptID} || (ref $bkptInfoTable{$bkptID}) ne 'ARRAY') {
# No such breakpoint
return 0;
}
delete $bkptInfoTable{$bkptID};
return 1;
}