3 # Debugger for Perl 5.00x; perl5db.pl patch level:
6 $header = "perl5db.pl patch level $VERSION";
8 # Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich)
9 # Latest version available: ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
11 # modified Perl debugger, to be run from Emacs in perldb-mode
12 # Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990
13 # Johan Vromans -- upgrade to 4.0 pl 10
14 # Ilya Zakharevich -- patches after 5.001 (and some before ;-)
17 # This file is automatically included if you do perl -d.
18 # It's probably not useful to include this yourself.
20 # Perl supplies the values for @line and %sub. It effectively inserts
21 # a &DB'DB(<linenum>); in front of every place that can have a
22 # breakpoint. Instead of a subroutine call it calls &DB::sub with
23 # $DB::sub being the called subroutine. It also inserts a BEGIN
24 # {require 'perl5db.pl'} before the first line.
26 # Note that no subroutine call is possible until &DB::sub is defined
27 # (for subroutines defined outside this file). In fact the same is
28 # true if $deep is not defined.
33 # At start reads $rcfile that may set important options. This file
34 # may define a subroutine &afterinit that will be executed after the
35 # debugger is initialized.
37 # After $rcfile is read reads environment variable PERLDB_OPTS and parses
38 # it as a rest of `O ...' line in debugger prompt.
40 # The options that can be specified only at startup:
41 # [To set in $rcfile, call &parse_options("optionName=new_value").]
43 # TTY - the TTY to use for debugging i/o.
45 # noTTY - if set, goes in NonStop mode. On interrupt if TTY is not set
46 # uses the value of noTTY or "/tmp/perldbtty$$" to find TTY using
47 # Term::Rendezvous. Current variant is to have the name of TTY in this
50 # ReadLine - If false, dummy ReadLine is used, so you can debug
51 # ReadLine applications.
53 # NonStop - if true, no i/o is performed until interrupt.
55 # LineInfo - file or pipe to print line number info to. If it is a
56 # pipe, a short "emacs like" message is used.
58 # Example $rcfile: (delete leading hashes!)
60 # &parse_options("NonStop=1 LineInfo=db.out");
61 # sub afterinit { $trace = 1; }
63 # The script will run without human intervention, putting trace
64 # information into db.out. (If you interrupt it, you would better
65 # reset LineInfo to something "interactive"!)
67 # Changes: 0.95: v command shows versions.
69 ##################################################################
72 # A lot of things changed after 0.94. First of all, core now informs
73 # debugger about entry into XSUBs, overloaded operators, tied operations,
74 # BEGIN and END. Handy with `O f=2'.
76 # This can make debugger a little bit too verbose, please be patient
77 # and report your problems promptly.
79 # Now the option frame has 3 values: 0,1,2.
81 # Note that if DESTROY returns a reference to the object (or object),
82 # the deletion of data may be postponed until the next function call,
83 # due to the need to examine the return value.
85 ####################################################################
87 # Needed for the statement after exec():
89 BEGIN { $ini_warn = $^W; $^W = 0 } # Switch compilation warnings off until another BEGIN.
90 local($^W) = 0; # Switch run-time warnings off during init.
94 $dumpvar::dumpDBFiles,
95 $dumpvar::dumpPackages,
96 $dumpvar::quoteHighBit,
107 # Command-line + PERLLIB:
110 # $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?!
112 $trace = $signal = $single = 0; # Uninitialized warning suppression
113 # (local $^W cannot help - other packages!).
118 $option{PrintRet} = 1;
120 @options = qw(hashDepth arrayDepth DumpDBFiles DumpPackages
121 compactDump veryCompact quote HighBit undefPrint
122 globPrint PrintRet UsageOnly frame
123 TTY noTTY ReadLine NonStop LineInfo
124 recallCommand ShellBang pager tkRunning
125 signalLevel warnLevel dieLevel);
128 hashDepth => \$dumpvar::hashDepth,
129 arrayDepth => \$dumpvar::arrayDepth,
130 DumpDBFiles => \$dumpvar::dumpDBFiles,
131 DumpPackages => \$dumpvar::dumpPackages,
132 HighBit => \$dumpvar::quoteHighBit,
133 undefPrint => \$dumpvar::printUndef,
134 globPrint => \$dumpvar::globPrint,
135 tkRunning => \$readline::Tk_toloop,
136 UsageOnly => \$dumpvar::usageOnly,
141 compactDump => \&dumpvar::compactDump,
142 veryCompact => \&dumpvar::veryCompact,
143 quote => \&dumpvar::quote,
146 ReadLine => \&ReadLine,
147 NonStop => \&NonStop,
148 LineInfo => \&LineInfo,
149 recallCommand => \&recallCommand,
150 ShellBang => \&shellBang,
152 signalLevel => \&signalLevel,
153 warnLevel => \&warnLevel,
154 dieLevel => \&dieLevel,
158 compactDump => 'dumpvar.pl',
159 veryCompact => 'dumpvar.pl',
160 quote => 'dumpvar.pl',
163 # These guys may be defined in $ENV{PERL5DB} :
164 $rl = 1 unless defined $rl;
165 $warnLevel = 1 unless defined $warnLevel;
166 $dieLevel = 1 unless defined $dieLevel;
167 $signalLevel = 1 unless defined $signalLevel;
168 warnLevel($warnLevel);
170 signalLevel($signalLevel);
171 &pager(defined($ENV{PAGER}) ? $ENV{PAGER} : "|more") unless defined $pager;
172 &recallCommand("!") unless defined $prc;
173 &shellBang("!") unless defined $psh;
178 $rcfile="perldb.ini";
183 } elsif (defined $ENV{LOGDIR} and -f "$ENV{LOGDIR}/$rcfile") {
184 do "$ENV{LOGDIR}/$rcfile";
185 } elsif (defined $ENV{HOME} and -f "$ENV{HOME}/$rcfile") {
186 do "$ENV{HOME}/$rcfile";
189 if (defined $ENV{PERLDB_OPTS}) {
190 parse_options($ENV{PERLDB_OPTS});
193 if (exists $ENV{PERLDB_RESTART}) {
194 delete $ENV{PERLDB_RESTART};
196 @hist = get_list('PERLDB_HIST');
197 my @visited = get_list("PERLDB_VISITED");
198 for (0 .. $#visited) {
199 %{$postponed{$visited[$_]}} = get_list("PERLDB_FILE_$_");
201 my %opt = get_list("PERLDB_OPT");
203 while (($opt,$val) = each %opt) {
204 $val =~ s/[\\\']/\\$1/g;
205 parse_options("$opt'$val'");
207 @INC = get_list("PERLDB_INC");
214 # Is Perl being run from Emacs?
215 $emacs = ((defined $main::ARGV[0]) and ($main::ARGV[0] eq '-emacs'));
216 $rl = 0, shift(@main::ARGV) if $emacs;
218 #require Term::ReadLine;
221 $console = "/dev/tty";
225 $console = "sys\$command";
229 if (defined $ENV{OS2_SHELL} and ($emacs or $ENV{WINDOWID})) { # In OS/2
233 $console = $tty if defined $tty;
235 if (defined $console) {
236 open(IN,"+<$console") || open(IN,"<$console") || open(IN,"<&STDIN");
237 open(OUT,"+>$console") || open(OUT,">$console") || open(OUT,">&STDERR")
238 || open(OUT,">&STDOUT"); # so we don't dongle stdout
241 open(OUT,">&STDERR") || open(OUT,">&STDOUT"); # so we don't dongle stdout
242 $console = 'STDIN/OUT';
244 # so open("|more") can read from STDOUT and so we don't dingle stdin
249 $| = 1; # for DB::OUT
252 $LINEINFO = $OUT unless defined $LINEINFO;
253 $lineinfo = $console unless defined $lineinfo;
255 $| = 1; # for real STDOUT
257 $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/;
258 unless ($runnonstop) {
259 print $OUT "\nLoading DB routines from $header\n";
260 print $OUT ("Emacs support ",
261 $emacs ? "enabled" : "available",
263 print $OUT "\nEnter h or `h h' for help.\n\n";
270 s/(.*)/'$1'/ unless /^-?[\d.]+$/;
273 if (defined &afterinit) { # May be defined in $rcfile
277 ############################################################ Subroutines
280 unless ($first_time++) { # Do when-running init
281 if ($runnonstop) { # Disable until signal
282 for ($i=0; $i <= $#stack; ) {
288 # Define a subroutine in which we will stop
290 # sub at_end::db {"Debuggee terminating";}
293 # print $OUT "Debuggee terminating.\n";
298 ($package, $filename, $line) = caller;
299 $filename_ini = $filename;
300 $usercontext = '($@, $!, $,, $/, $\, $^W) = @saved;' .
301 "package $package;"; # this won't let them modify, alas
302 local(*dbline) = "::_<$filename";
303 install_breakpoints($filename) unless $visited{$filename}++;
305 if (($stop,$action) = split(/\0/,$dbline{$line})) {
309 $evalarg = "\$DB::signal |= do {$stop;}"; &eval;
310 $dbline{$line} =~ s/;9($|\0)/$1/;
313 if ($single || $trace || $signal) {
316 $position = "\032\032$filename:$line:0\n";
317 print $LINEINFO $position;
320 $prefix = $sub =~ /::/ ? "" : "${'package'}::";
321 $prefix .= "$sub($filename:";
322 $after = ($dbline[$line] =~ /\n$/ ? '' : "\n");
323 if (length($prefix) > 30) {
324 $position = "$prefix$line):\n$line:\t$dbline[$line]$after";
325 print $LINEINFO $position;
330 $position = "$prefix$line$infix$dbline[$line]$after";
331 print $LINEINFO $position;
333 for ($i = $line + 1; $i <= $max && $dbline[$i] == 0; ++$i) { #{ vi
334 last if $dbline[$i] =~ /^\s*[\;\}\#\n]/;
335 $after = ($dbline[$i] =~ /\n$/ ? '' : "\n");
336 $incr_pos = "$prefix$i$infix$dbline[$i]$after";
337 print $LINEINFO $incr_pos;
338 $position .= $incr_pos;
342 $evalarg = $action, &eval if $action;
343 if ($single || $signal) {
344 local $level = $level + 1;
345 $evalarg = $pre, &eval if $pre;
346 print $OUT $#stack . " levels deep in subroutine calls!\n"
350 while (($term || &setterm),
351 defined ($cmd=&readline(" DB" . ('<' x $level) .
352 ($#hist+1) . ('>' x $level) .
354 #{ # <-- Do we know what this brace is for?
357 $cmd =~ s/\\$/\n/ && do {
358 $cmd .= &readline(" cont: ");
361 $cmd =~ /^q$/ && exit 0;
362 $cmd =~ /^$/ && ($cmd = $laststep);
363 push(@hist,$cmd) if length($cmd) > 1;
365 ($i) = split(/\s+/,$cmd);
366 eval "\$cmd =~ $alias{$i}", print $OUT $@ if $alias{$i};
367 $cmd =~ /^h$/ && do {
370 $cmd =~ /^h\s+h$/ && do {
373 $cmd =~ /^h\s+(\S)$/ && do {
375 if ($help =~ /^($asked([\s\S]*?)\n)(\Z|[^\s$asked])/m) {
378 print $OUT "`$asked' is not a debugger command.\n";
381 $cmd =~ /^t$/ && do {
383 print $OUT "Trace = ".($trace?"on":"off")."\n";
385 $cmd =~ /^S(\s+(!)?(.+))?$/ && do {
386 $Srev = defined $2; $Spatt = $3; $Snocheck = ! defined $1;
387 foreach $subname (sort(keys %sub)) {
388 if ($Snocheck or $Srev^($subname =~ /$Spatt/)) {
389 print $OUT $subname,"\n";
393 $cmd =~ /^v$/ && do {
394 list_versions(); next CMD};
395 $cmd =~ s/^X\b/V $package/;
396 $cmd =~ /^V$/ && do {
397 $cmd = "V $package"; };
398 $cmd =~ /^V\b\s*(\S+)\s*(.*)/ && do {
399 local ($savout) = select($OUT);
401 @vars = split(' ',$2);
402 do 'dumpvar.pl' unless defined &main::dumpvar;
403 if (defined &main::dumpvar) {
406 &main::dumpvar($packname,@vars);
408 print $OUT "dumpvar.pl not available.\n";
412 $cmd =~ s/^x\b/ / && do { # So that will be evaled
414 $cmd =~ /^f\b\s*(.*)/ && do {
417 print $OUT "The old f command is now the r command.\n";
418 print $OUT "The new f command switches filenames.\n";
421 if (!defined $main::{'_<' . $file}) {
422 if (($try) = grep(m#^_<.*$file#, keys %main::)) {{
423 $file = substr($try,2);
427 if (!defined $main::{'_<' . $file}) {
428 print $OUT "There's no code here matching $file.\n";
430 } elsif ($file ne $filename) {
431 *dbline = "::_<$file";
438 $cmd =~ /^l\b\s*([\':A-Za-z_][\':\w]*)/ && do {
440 $subname =~ s/\'/::/;
441 $subname = "main::".$subname unless $subname =~ /::/;
442 $subname = "main".$subname if substr($subname,0,2) eq "::";
443 @pieces = split(/:/,$sub{$subname});
444 $subrange = pop @pieces;
445 $file = join(':', @pieces);
446 if ($file ne $filename) {
447 *dbline = "::_<$file";
453 if (eval($subrange) < -$window) {
454 $subrange =~ s/-.*/+/;
456 $cmd = "l $subrange";
458 print $OUT "Subroutine $subname not found.\n";
461 $cmd =~ /^\.$/ && do {
463 $filename = $filename_ini;
464 *dbline = "::_<$filename";
466 print $LINEINFO $position;
468 $cmd =~ /^w\b\s*(\d*)$/ && do {
472 #print $OUT 'l ' . $start . '-' . ($start + $incr);
473 $cmd = 'l ' . $start . '-' . ($start + $incr); };
474 $cmd =~ /^-$/ && do {
476 $cmd = 'l ' . ($start-$window*2) . '+'; };
477 $cmd =~ /^l$/ && do {
479 $cmd = 'l ' . $start . '-' . ($start + $incr); };
480 $cmd =~ /^l\b\s*(\d*)\+(\d*)$/ && do {
483 $incr = $window - 1 unless $incr;
484 $cmd = 'l ' . $start . '-' . ($start + $incr); };
485 $cmd =~ /^l\b\s*((-?[\d\$\.]+)([-,]([\d\$\.]+))?)?/ && do {
486 $end = (!defined $2) ? $max : ($4 ? $4 : $2);
487 $end = $max if $end > $max;
489 $i = $line if $i eq '.';
492 print $OUT "\032\032$filename:$i:0\n";
495 for (; $i <= $end; $i++) {
496 ($stop,$action) = split(/\0/, $dbline{$i});
498 and $filename eq $filename_ini)
501 $arrow .= 'b' if $stop;
502 $arrow .= 'a' if $action;
503 print $OUT "$i$arrow\t", $dbline[$i];
507 $start = $i; # remember in case they want more
508 $start = $max if $start > $max;
510 $cmd =~ /^D$/ && do {
511 print $OUT "Deleting all breakpoints...\n";
512 for ($i = 1; $i <= $max ; $i++) {
513 if (defined $dbline{$i}) {
514 $dbline{$i} =~ s/^[^\0]+//;
515 if ($dbline{$i} =~ s/^\0?$//) {
521 $cmd =~ /^L$/ && do {
522 for ($i = 1; $i <= $max; $i++) {
523 if (defined $dbline{$i}) {
524 print $OUT "$i:\t", $dbline[$i];
525 ($stop,$action) = split(/\0/, $dbline{$i});
526 print $OUT " break if (", $stop, ")\n"
528 print $OUT " action: ", $action, "\n"
534 $cmd =~ /^b\b\s*([':A-Za-z_][':\w]*)\s*(.*)/ && do {
537 $subname =~ s/\'/::/;
538 $subname = "${'package'}::" . $subname
539 unless $subname =~ /::/;
540 $subname = "main".$subname if substr($subname,0,2) eq "::";
541 # Filename below can contain ':'
542 ($file,$i) = ($sub{$subname} =~ /^(.*):(.*)$/);
546 *dbline = "::_<$filename";
547 $visited{$filename}++;
549 ++$i while $dbline[$i] == 0 && $i < $max;
550 $dbline{$i} =~ s/^[^\0]*/$cond/;
552 print $OUT "Subroutine $subname not found.\n";
555 $cmd =~ /^b\b\s*(\d*)\s*(.*)/ && do {
558 if ($dbline[$i] == 0) {
559 print $OUT "Line $i not breakable.\n";
561 $dbline{$i} =~ s/^[^\0]*/$cond/;
564 $cmd =~ /^d\b\s*(\d+)?/ && do {
566 $dbline{$i} =~ s/^[^\0]*//;
567 delete $dbline{$i} if $dbline{$i} eq '';
569 $cmd =~ /^A$/ && do {
570 for ($i = 1; $i <= $max ; $i++) {
571 if (defined $dbline{$i}) {
572 $dbline{$i} =~ s/\0[^\0]*//;
573 delete $dbline{$i} if $dbline{$i} eq '';
577 $cmd =~ /^O\s*$/ && do {
582 $cmd =~ /^O\s*(\S.*)/ && do {
585 $cmd =~ /^<\s*(.*)/ && do {
588 $cmd =~ /^>\s*(.*)/ && do {
591 $cmd =~ /^a\b\s*(\d+)(\s+(.*))?/ && do {
593 if ($dbline[$i] == 0) {
594 print $OUT "Line $i may not have an action.\n";
596 $dbline{$i} =~ s/\0[^\0]*//;
597 $dbline{$i} .= "\0" . action($j);
600 $cmd =~ /^n$/ && do {
604 $cmd =~ /^s$/ && do {
608 $cmd =~ /^c\b\s*([\w:]*)\s*$/ && do {
610 if ($i =~ /\D/) { # subroutine name
611 ($file,$i) = ($sub{$i} =~ /^(.*):(.*)$/);
615 *dbline = "::_<$filename";
616 $visited{$filename}++;
618 ++$i while $dbline[$i] == 0 && $i < $max;
620 print $OUT "Subroutine $subname not found.\n";
625 if ($dbline[$i] == 0) {
626 print $OUT "Line $i not breakable.\n";
629 $dbline{$i} =~ s/($|\0)/;9$1/; # add one-time-only b.p.
631 for ($i=0; $i <= $#stack; ) {
635 $cmd =~ /^r$/ && do {
636 $stack[$#stack] |= 1;
637 $doret = $option{PrintRet} ? $#stack - 1 : -2;
639 $cmd =~ /^R$/ && do {
640 print $OUT "Warning: a lot of settings and command-line options may be lost!\n";
641 my (@script, @flags, $cl);
642 push @flags, '-w' if $ini_warn;
643 # Put all the old includes at the start to get
646 push @flags, '-I', $_;
648 # Arrange for setting the old INC:
649 set_list("PERLDB_INC", @ini_INC);
651 for (1..$#{'::_<-e'}) { # The first line is PERL5DB
652 chomp ($cl = $ {'::_<-e'}[$_]);
653 push @script, '-e', $cl;
658 set_list("PERLDB_HIST",
659 $term->Features->{getHistory}
660 ? $term->GetHistory : @hist);
661 my @visited = keys %visited;
662 set_list("PERLDB_VISITED", @visited);
663 set_list("PERLDB_OPT", %option);
664 for (0 .. $#visited) {
665 *dbline = "::_<$visited[$_]";
666 set_list("PERLDB_FILE_$_", %dbline);
668 $ENV{PERLDB_RESTART} = 1;
669 #print "$^X, '-d', @flags, @script, ($emacs ? '-emacs' : ()), @ARGS";
670 exec $^X, '-d', @flags, @script, ($emacs ? '-emacs' : ()), @ARGS;
671 print $OUT "exec failed: $!\n";
673 $cmd =~ /^T$/ && do {
674 local($p,$f,$l,$s,$h,$a,$e,$r,@a,@sub);
676 ($p,$f,$l,$s,$h,$w,$e,$r) = caller($i);
683 unless /^(?: -?[\d.]+ | \*[\w:]* )$/x;
684 s/([\200-\377])/sprintf("M-%c",ord($1)&0177)/eg;
685 s/([\0-\37\177])/sprintf("^%c",ord($1)^64)/eg;
688 $w = $w ? '@ = ' : '$ = ';
689 $a = $h ? '(' . join(', ', @a) . ')' : '';
690 $e =~ s/\n\s*\;\s*\Z// if $e;
691 $e =~ s/[\\\']/\\$1/g if $e;
694 } elsif (defined $r) {
696 } elsif ($s eq '(eval)') {
699 $f = "file `$f'" unless $f eq '-e';
700 push(@sub, "$w$s$a called from $f line $l\n");
703 for ($i=0; $i <= $#sub; $i++) {
708 $cmd =~ /^\/(.*)$/ && do {
710 $inpat =~ s:([^\\])/$:$1:;
712 eval '$inpat =~ m'."\a$inpat\a";
723 $start = 1 if ($start > $max);
724 last if ($start == $end);
725 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
727 print $OUT "\032\032$filename:$start:0\n";
729 print $OUT "$start:\t", $dbline[$start], "\n";
734 print $OUT "/$pat/: not found\n" if ($start == $end);
736 $cmd =~ /^\?(.*)$/ && do {
738 $inpat =~ s:([^\\])\?$:$1:;
740 eval '$inpat =~ m'."\a$inpat\a";
751 $start = $max if ($start <= 0);
752 last if ($start == $end);
753 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
755 print $OUT "\032\032$filename:$start:0\n";
757 print $OUT "$start:\t", $dbline[$start], "\n";
762 print $OUT "?$pat?: not found\n" if ($start == $end);
764 $cmd =~ /^$rc+\s*(-)?(\d+)?$/ && do {
765 pop(@hist) if length($cmd) > 1;
766 $i = $1 ? ($#hist-($2?$2:1)) : ($2?$2:$#hist);
767 $cmd = $hist[$i] . "\n";
770 $cmd =~ /^$sh$sh\s*([\x00-\xff]]*)/ && do {
773 $cmd =~ /^$rc([^$rc].*)$/ && do {
775 pop(@hist) if length($cmd) > 1;
776 for ($i = $#hist; $i; --$i) {
777 last if $hist[$i] =~ /$pat/;
780 print $OUT "No such command!\n\n";
783 $cmd = $hist[$i] . "\n";
786 $cmd =~ /^$sh$/ && do {
787 &system($ENV{SHELL}||"/bin/sh");
789 $cmd =~ /^$sh\s*([\x00-\xff]*)/ && do {
790 &system($ENV{SHELL}||"/bin/sh","-c",$1);
792 $cmd =~ /^H\b\s*(-(\d+))?/ && do {
793 $end = $2?($#hist-$2):0;
794 $hist = 0 if $hist < 0;
795 for ($i=$#hist; $i>$end; $i--) {
796 print $OUT "$i: ",$hist[$i],"\n"
797 unless $hist[$i] =~ /^.?$/;
800 $cmd =~ s/^p$/print \$DB::OUT \$_/;
801 $cmd =~ s/^p\b/print \$DB::OUT /;
803 if (local($k,$v) = ($cmd =~ /^=\s*(\S+)\s+(.*)/)) {
804 $alias{$k}="s~$k~$v~";
805 print $OUT "$k = $v\n";
806 } elsif ($cmd =~ /^=\s*$/) {
807 foreach $k (sort keys(%alias)) {
808 if (($v = $alias{$k}) =~ s~^s\~$k\~(.*)\~$~$1~) {
809 print $OUT "$k = $v\n";
811 print $OUT "$k\t$alias{$k}\n";
816 $cmd =~ /^\|\|?\s*[^|]/ && do {
817 if ($pager =~ /^\|/) {
818 open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
819 open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
821 open(SAVEOUT,">&OUT") || &warn("Can't save DB::OUT");
823 unless ($piped=open(OUT,$pager)) {
824 &warn("Can't pipe output to `$pager'");
825 if ($pager =~ /^\|/) {
826 open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
827 open(STDOUT,">&SAVEOUT")
828 || &warn("Can't restore STDOUT");
831 open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
835 $SIG{PIPE}= "DB::catch" if $pager =~ /^\|/
836 && "" eq $SIG{PIPE} || "DEFAULT" eq $SIG{PIPE};
837 $selected= select(OUT);
839 select( $selected ), $selected= "" unless $cmd =~ /^\|\|/;
842 # XXX Local variants do not work!
843 $cmd =~ s/^t\s/\$DB::trace = 1;\n/;
844 $cmd =~ s/^s\s/\$DB::single = 1;\n/ && do {$laststep = 's'};
845 $cmd =~ s/^n\s/\$DB::single = 2;\n/ && do {$laststep = 'n'};
847 #} # <-- Do we know what this brace is for?
848 $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd"; &eval;
850 $onetimeDump = undef;
856 if ($pager =~ /^\|/) {
857 $?= 0; close(OUT) || &warn("Can't close DB::OUT");
858 &warn( "Pager `$pager' failed: ",
859 ($?>>8) > 128 ? ($?>>8)-256 : ($?>>8),
860 ( $? & 128 ) ? " (core dumped)" : "",
861 ( $? & 127 ) ? " (SIG ".($?&127).")" : "", "\n" ) if $?;
862 open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
863 open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
864 $SIG{PIPE}= "DEFAULT" if $SIG{PIPE} eq "DB::catch";
865 # Will stop ignoring SIGPIPE if done like nohup(1)
866 # does SIGINT but Perl doesn't give us a choice.
868 open(OUT,">&SAVEOUT") || &warn("Can't restore DB::OUT");
871 select($selected), $selected= "" unless $selected eq "";
876 $evalarg = $post; &eval;
878 } # if ($single || $signal)
879 ($@, $!, $,, $/, $\, $^W) = @saved;
883 # The following code may be executed now:
887 my ($al, $ret, @ret) = "";
888 if ($sub =~ /::AUTOLOAD$/) {
889 $al = " for $ {$` . '::AUTOLOAD'}";
891 print $LINEINFO ' ' x $#stack, "entering $sub$al\n" if $frame;
892 push(@stack, $single);
894 $single |= 4 if $#stack == $deep;
897 $single |= pop(@stack);
898 print ($OUT "list context return from $sub:\n"), dumpit( \@ret ),
899 $doret = -2 if $doret eq $#stack;
900 print $LINEINFO ' ' x $#stack, "exited $sub$al\n" if $frame > 1;
904 $single |= pop(@stack);
905 print ($OUT "scalar context return from $sub: "), dumpit( $ret ),
906 $doret = -2 if $doret eq $#stack;
907 print $LINEINFO ' ' x $#stack, "exited $sub$al\n" if $frame > 1;
913 @saved = ($@, $!, $,, $/, $\, $^W);
914 $, = ""; $/ = "\n"; $\ = ""; $^W = 0;
917 # The following takes its argument via $evalarg to preserve current @_
922 local (@stack) = @stack; # guard against recursive debugging
924 my $osingle = $single;
926 @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug
935 } elsif ($onetimeDump) {
940 sub install_breakpoints {
941 my $filename = shift;
942 return unless exists $postponed{$filename};
943 my %break = %{$postponed{$filename}};
946 #if (/\D/) { # Subroutine name
948 $dbline{$i} = $break{$_}; # Cannot be done before the file is around
953 local ($savout) = select($OUT);
954 my $osingle = $single;
956 $single = $trace = 0;
959 unless (defined &main::dumpValue) {
962 if (defined &main::dumpValue) {
963 &main::dumpValue(shift);
965 print $OUT "dumpvar.pl not available.\n";
974 while ($action =~ s/\\$//) {
989 # We save, change, then restore STDIN and STDOUT to avoid fork() since
990 # many non-Unix systems can do system() but have problems with fork().
991 open(SAVEIN,"<&STDIN") || &warn("Can't save STDIN");
992 open(SAVEOUT,">&OUT") || &warn("Can't save STDOUT");
993 open(STDIN,"<&IN") || &warn("Can't redirect STDIN");
994 open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
996 open(STDIN,"<&SAVEIN") || &warn("Can't restore STDIN");
997 open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
998 close(SAVEIN); close(SAVEOUT);
999 &warn( "(Command returned ", ($?>>8) > 128 ? ($?>>8)-256 : ($?>>8), ")",
1000 ( $? & 128 ) ? " (core dumped)" : "",
1001 ( $? & 127 ) ? " (SIG ".($?&127).")" : "", "\n" ) if $?;
1008 local @stack = @stack; # Prevent growth by failing `use'.
1009 eval { require Term::ReadLine } or die $@;
1012 open(IN,"<$tty") or die "Cannot open TTY `$TTY' for read: $!";
1013 open(OUT,">$tty") or die "Cannot open TTY `$TTY' for write: $!";
1016 my $sel = select($OUT);
1020 eval "require Term::Rendezvous;" or die $@;
1021 my $rv = $ENV{PERLDB_NOTTY} || "/tmp/perldbtty$$";
1022 my $term_rv = new Term::Rendezvous $rv;
1024 $OUT = $term_rv->OUT;
1028 $term = new Term::ReadLine::Stub 'perldb', $IN, $OUT;
1030 $term = new Term::ReadLine 'perldb', $IN, $OUT;
1032 $readline::rl_basic_word_break_characters .= "[:"
1033 if defined $readline::rl_basic_word_break_characters
1034 and index($readline::rl_basic_word_break_characters, ":") == -1;
1036 $LINEINFO = $OUT unless defined $LINEINFO;
1037 $lineinfo = $console unless defined $lineinfo;
1039 if ($term->Features->{setHistory} and "@hist" ne "?") {
1040 $term->SetHistory(@hist);
1046 my $left = @typeahead;
1047 my $got = shift @typeahead;
1048 print $OUT "auto(-$left)", shift, $got, "\n";
1049 $term->AddHistory($got)
1050 if length($got) > 1 and defined $term->Features->{addHistory};
1055 $term->readline(@_);
1059 my ($opt, $val)= @_;
1060 if (defined $optionVars{$opt}
1061 and defined $ {$optionVars{$opt}}) {
1062 $val = $ {$optionVars{$opt}};
1063 } elsif (defined $optionAction{$opt}
1064 and defined &{$optionAction{$opt}}) {
1065 $val = &{$optionAction{$opt}}();
1066 } elsif (defined $optionAction{$opt}
1067 and not defined $option{$opt}
1068 or defined $optionVars{$opt}
1069 and not defined $ {$optionVars{$opt}}) {
1072 $val = $option{$opt};
1074 $val =~ s/([\\\'])/\\$1/g;
1075 printf $OUT "%20s = '%s'\n", $opt, $val;
1081 s/^(\w+)(\s*$|\W)// or print($OUT "Invalid option `$_'\n"), last;
1082 my ($opt,$sep) = ($1,$2);
1085 print($OUT "Option query `$opt?' followed by non-space `$_'\n"), last
1087 #&dump_option($opt);
1088 } elsif ($sep !~ /\S/) {
1090 } elsif ($sep eq "=") {
1093 } else { #{ to "let some poor schmuck bounce on the % key in B<vi>."
1094 my ($end) = "\\" . substr( ")]>}$sep", index("([<{",$sep), 1 ); #}
1095 s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)// or
1096 print($OUT "Unclosed option value `$opt$sep$_'\n"), last;
1098 $val =~ s/\\([\\$end])/$1/g;
1102 grep( /^\Q$opt/ && ($option = $_), @options );
1103 $matches = grep( /^\Q$opt/i && ($option = $_), @options )
1105 print $OUT "Unknown option `$opt'\n" unless $matches;
1106 print $OUT "Ambiguous option `$opt'\n" if $matches > 1;
1107 $option{$option} = $val if $matches == 1 and defined $val;
1108 eval "local \$frame = 0; local \$doret = -2;
1109 require '$optionRequire{$option}'"
1110 if $matches == 1 and defined $optionRequire{$option} and defined $val;
1111 $ {$optionVars{$option}} = $val
1113 and defined $optionVars{$option} and defined $val;
1114 & {$optionAction{$option}} ($val)
1116 and defined $optionAction{$option}
1117 and defined &{$optionAction{$option}} and defined $val;
1118 &dump_option($option) if $matches == 1 && $OUT ne \*STDERR; # Not $rcfile
1124 my ($stem,@list) = @_;
1126 $ENV{"$ {stem}_n"} = @list;
1127 for $i (0 .. $#list) {
1129 $val =~ s/\\/\\\\/g;
1130 $val =~ s/([\0-\37\177\200-\377])/"\\0x" . unpack('H2',$1)/eg;
1131 $ENV{"$ {stem}_$i"} = $val;
1138 my $n = delete $ENV{"$ {stem}_n"};
1140 for $i (0 .. $n - 1) {
1141 $val = delete $ENV{"$ {stem}_$i"};
1142 $val =~ s/\\((\\)|0x(..))/ $2 ? $2 : pack('H2', $3) /ge;
1153 my($msg)= join("",@_);
1154 $msg .= ": $!\n" unless $msg =~ /\n$/;
1160 &warn("Too late to set TTY!\n") if @_;
1169 &warn("Too late to set noTTY!\n") if @_;
1171 $notty = shift if @_;
1178 &warn("Too late to set ReadLine!\n") if @_;
1187 &warn("Too late to set up NonStop mode!\n") if @_;
1189 $runnonstop = shift if @_;
1197 $pager="|".$pager unless $pager =~ /^(\+?\>|\|)/;
1204 $sh = quotemeta shift;
1205 $sh .= "\\b" if $sh =~ /\w$/;
1209 $psh =~ s/\\(.)/$1/g;
1216 $rc = quotemeta shift;
1217 $rc .= "\\b" if $rc =~ /\w$/;
1221 $prc =~ s/\\(.)/$1/g;
1227 return $lineinfo unless @_;
1229 my $stream = ($lineinfo =~ /^(\+?\>|\|)/) ? $lineinfo : ">$lineinfo";
1230 $emacs = ($stream =~ /^\|/);
1231 open(LINEINFO, "$stream") || &warn("Cannot open `$stream' for write");
1232 $LINEINFO = \*LINEINFO;
1233 my $save = select($LINEINFO);
1247 if (defined $ { $_ . '::VERSION' }) {
1248 $version{$file} = "$ { $_ . '::VERSION' } from ";
1250 $version{$file} .= $INC{$file};
1252 do 'dumpvar.pl' unless defined &main::dumpValue;
1253 if (defined &main::dumpValue) {
1255 &main::dumpValue(\%version);
1257 print $OUT "dumpvar.pl not available.\n";
1264 s [expr] Single step [in expr].
1265 n [expr] Next, steps over subroutine calls [in expr].
1266 <CR> Repeat last n or s command.
1267 r Return from current subroutine.
1268 c [line] Continue; optionally inserts a one-time-only breakpoint
1269 at the specified line.
1270 l min+incr List incr+1 lines starting at min.
1271 l min-max List lines min through max.
1272 l line List single line.
1273 l subname List first window of lines from subroutine.
1274 l List next window of lines.
1275 - List previous window of lines.
1276 w [line] List window around line.
1277 . Return to the executed line.
1278 f filename Switch to viewing filename.
1279 /pattern/ Search forwards for pattern; final / is optional.
1280 ?pattern? Search backwards for pattern; final ? is optional.
1281 L List all breakpoints and actions for the current file.
1282 S [[!]pattern] List subroutine names [not] matching pattern.
1283 t Toggle trace mode.
1284 t expr Trace through execution of expr.
1285 b [line] [condition]
1286 Set breakpoint; line defaults to the current execution line;
1287 condition breaks if it evaluates to true, defaults to '1'.
1288 b subname [condition]
1289 Set breakpoint at first line of subroutine.
1290 d [line] Delete the breakpoint for line.
1291 D Delete all breakpoints.
1293 Set an action to be done before the line is executed.
1294 Sequence is: check for breakpoint, print line if necessary,
1295 do action, prompt user if breakpoint or step, evaluate line.
1296 A Delete all actions.
1297 V [pkg [vars]] List some (default all) variables in package (default current).
1298 Use ~pattern and !pattern for positive and negative regexps.
1299 X [vars] Same as \"V currentpackage [vars]\".
1300 x expr Evals expression in array context, dumps the result.
1301 O [opt[=val]] [opt\"val\"] [opt?]...
1302 Set or query values of options. val defaults to 1. opt can
1303 be abbreviated. Several options can be listed.
1304 recallCommand, ShellBang: chars used to recall command or spawn shell;
1305 pager: program for output of \"|cmd\";
1306 The following options affect what happens with V, X, and x commands:
1307 arrayDepth, hashDepth: print only first N elements ('' for all);
1308 compactDump, veryCompact: change style of array and hash dump;
1309 globPrint: whether to print contents of globs;
1310 DumpDBFiles: dump arrays holding debugged files;
1311 DumpPackages: dump symbol tables of packages;
1312 quote, HighBit, undefPrint: change style of string dump;
1313 tkRunning: run Tk while prompting (with ReadLine);
1314 signalLevel warnLevel dieLevel: level of verbosity;
1315 Option PrintRet affects printing of return value after r command,
1316 frame affects printing messages on entry and exit from subroutines.
1317 During startup options are initialized from \$ENV{PERLDB_OPTS}.
1318 You can put additional initialization options TTY, noTTY,
1319 ReadLine, and NonStop there.
1320 < command Define command to run before each prompt.
1321 > command Define command to run after each prompt.
1322 $prc number Redo a previous command (default previous command).
1323 $prc -number Redo number'th-to-last command.
1324 $prc pattern Redo last command that started with pattern.
1325 See 'O recallCommand' too.
1326 $psh$psh cmd Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
1327 . ( $rc eq $sh ? "" : "
1328 $psh [cmd] Run cmd in subshell (forces \"\$SHELL -c 'cmd'\")." ) . "
1329 See 'O shellBang' too.
1330 H -number Display last number commands (default all).
1331 p expr Same as \"print DB::OUT expr\" in current package.
1332 |dbcmd Run debugger command, piping DB::OUT to current pager.
1333 ||dbcmd Same as |dbcmd but DB::OUT is temporarilly select()ed as well.
1334 \= [alias value] Define a command alias, or list current aliases.
1335 command Execute as a perl statement in current package.
1336 v Show versions of loaded modules.
1337 R Pure-man-restart of debugger, debugger state and command-line
1339 h [db_command] Get help [on a specific debugger command], enter |h to page.
1340 h h Summary of debugger commands.
1344 $summary = <<"END_SUM";
1345 List/search source lines: Control script execution:
1346 l [ln|sub] List source code T Stack trace
1347 - or . List previous/current line s [expr] Single step [in expr]
1348 w [line] List around line n [expr] Next, steps over subs
1349 f filename View source in file <CR> Repeat last n or s
1350 /pattern/ ?patt? Search forw/backw r Return from subroutine
1351 v Show versions of modules c [line] Continue until line
1352 Debugger controls: L List break pts & actions
1353 O [...] Set debugger options t [expr] Toggle trace [trace expr]
1354 < command Command for before prompt b [ln] [c] Set breakpoint
1355 > command Command for after prompt b sub [c] Set breakpoint for sub
1356 $prc [N|pat] Redo a previous command d [line] Delete a breakpoint
1357 H [-num] Display last num commands D Delete all breakpoints
1358 = [a val] Define/list an alias a [ln] cmd Do cmd before line
1359 h [db_cmd] Get help on command A Delete all actions
1360 |[|]dbcmd Send output to pager $psh\[$psh\] syscmd Run cmd in a subprocess
1361 q or ^D Quit R Attempt a restart
1362 Data Examination: expr Execute perl code, also see: s,n,t expr
1363 S [[!]pat] List subroutine names [not] matching pattern
1364 V [Pk [Vars]] List Variables in Package. Vars can be ~pattern or !pattern.
1365 X [Vars] Same as \"V current_package [Vars]\".
1366 x expr Evals expression in array context, dumps the result.
1367 p expr Print expression (uses script's current package).
1369 # '); # Fix balance of Emacs parsing
1375 $SIG{'ABRT'} = DEFAULT;
1376 kill 'ABRT', $$ if $panic++;
1377 print $DB::OUT "Got $_[0]!\n"; # in the case cannot continue
1378 local $SIG{__WARN__} = '';
1380 local $Carp::CarpLevel = 2; # mydie + confess
1381 &warn(Carp::longmess("Signal @_"));
1388 local $SIG{__WARN__} = '';
1390 #&warn("Entering dbwarn\n");
1391 my ($mysingle,$mytrace) = ($single,$trace);
1392 $single = 0; $trace = 0;
1393 my $mess = Carp::longmess(@_);
1394 ($single,$trace) = ($mysingle,$mytrace);
1395 #&warn("Warning in dbwarn\n");
1397 #&warn("Exiting dbwarn\n");
1403 local $SIG{__DIE__} = '';
1404 local $SIG{__WARN__} = '';
1405 my $i = 0; my $ineval = 0; my $sub;
1406 #&warn("Entering dbdie\n");
1407 if ($dieLevel != 2) {
1408 while ((undef,undef,undef,$sub) = caller(++$i)) {
1409 $ineval = 1, last if $sub eq '(eval)';
1412 local $SIG{__WARN__} = \&dbwarn;
1413 &warn(@_) if $dieLevel > 2; # Ineval is false during destruction?
1415 #&warn("dieing quietly in dbdie\n") if $ineval and $dieLevel < 2;
1416 die @_ if $ineval and $dieLevel < 2;
1419 # We do not want to debug this chunk (automatic disabling works
1420 # inside DB::DB, but not in Carp).
1421 my ($mysingle,$mytrace) = ($single,$trace);
1422 $single = 0; $trace = 0;
1423 my $mess = Carp::longmess(@_);
1424 ($single,$trace) = ($mysingle,$mytrace);
1425 #&warn("dieing loudly in dbdie\n");
1431 $prevwarn = $SIG{__WARN__} unless $warnLevel;
1434 $SIG{__WARN__} = 'DB::dbwarn';
1436 $SIG{__WARN__} = $prevwarn;
1444 $prevdie = $SIG{__DIE__} unless $dieLevel;
1447 $SIG{__DIE__} = 'DB::dbdie'; # if $dieLevel < 2;
1448 #$SIG{__DIE__} = 'DB::diehard' if $dieLevel >= 2;
1449 print $OUT "Stack dump during die enabled",
1450 ( $dieLevel == 1 ? " outside of evals" : ""), ".\n";
1451 print $OUT "Dump printed too.\n" if $dieLevel > 2;
1453 $SIG{__DIE__} = $prevdie;
1454 print $OUT "Default die handler restored.\n";
1462 $prevsegv = $SIG{SEGV} unless $signalLevel;
1463 $prevbus = $SIG{BUS} unless $signalLevel;
1464 $signalLevel = shift;
1466 $SIG{SEGV} = 'DB::diesignal';
1467 $SIG{BUS} = 'DB::diesignal';
1469 $SIG{SEGV} = $prevsegv;
1470 $SIG{BUS} = $prevbus;
1476 # The following BEGIN is very handy if debugger goes havoc, debugging debugger?
1478 BEGIN { # This does not compile, alas.
1479 $IN = \*STDIN; # For bugs before DB::OUT has been opened
1480 $OUT = \*STDERR; # For errors before DB::OUT has been opened
1484 $deep = 100; # warning if stack gets this deep
1488 $SIG{INT} = "DB::catch";
1489 # This may be enabled to debug debugger:
1490 #$warnLevel = 1 unless defined $warnLevel;
1491 #$dieLevel = 1 unless defined $dieLevel;
1492 #$signalLevel = 1 unless defined $signalLevel;
1494 $db_stop = 0; # Compiler warning
1496 $level = 0; # Level of recursive debugging
1499 BEGIN {$^W = $ini_warn;} # Switch warnings back
1501 #use Carp; # This did break, left for debuggin