home *** CD-ROM | disk | FTP | other *** search
/ CLIX - Fazer Clix Custa Nix / CLIX-CD.cdr / mac / lib / perl5db.pl < prev    next >
Perl Script  |  1997-12-25  |  64KB  |  2,067 lines

  1. package DB;
  2.  
  3. # Debugger for Perl 5.00x; perl5db.pl patch level:
  4.  
  5. $VERSION = 1.00;
  6. $header = "perl5db.pl version $VERSION";
  7.  
  8. # Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich)
  9. # Latest version available: ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
  10.  
  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 ;-)
  15.  
  16. #
  17. # This file is automatically included if you do perl -d.
  18. # It's probably not useful to include this yourself.
  19. #
  20. # Perl supplies the values for %sub.  It effectively inserts
  21. # a &DB'DB(); 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.
  25. #
  26. # After each `require'd file is compiled, but before it is executed, a
  27. # call to DB::postponed($main::{'_<'.$filename}) is emulated. Here the
  28. # $filename is the expanded name of the `require'd file (as found as
  29. # value of %INC).
  30. #
  31. # Additional services from Perl interpreter:
  32. #
  33. # if caller() is called from the package DB, it provides some
  34. # additional data.
  35. #
  36. # The array @{$main::{'_<'.$filename} is the line-by-line contents of
  37. # $filename.
  38. #
  39. # The hash %{'_<'.$filename} contains breakpoints and action (it is
  40. # keyed by line number), and individual entries are settable (as
  41. # opposed to the whole hash). Only true/false is important to the
  42. # interpreter, though the values used by perl5db.pl have the form
  43. # "$break_condition\0$action". Values are magical in numeric context.
  44. #
  45. # The scalar ${'_<'.$filename} contains "_<$filename".
  46. #
  47. # Note that no subroutine call is possible until &DB::sub is defined
  48. # (for subroutines defined outside of the package DB). In fact the same is
  49. # true if $deep is not defined.
  50. #
  51. # $Log: perl5db.pl,v $
  52. # Revision 1.3  1997/05/19 12:32:04  neeri
  53. # 5.004 merge, round 1
  54. #
  55. # Revision 1.1.1.2  1997/05/17 21:41:35  neeri
  56. # Import of Perl 5.004
  57. #
  58. # Revision 1.2  1997/04/07 20:52:00  neeri
  59. # Synchronized with MacPerl 5.1.4a1
  60. #
  61. # Revision 1.1.1.1  1997/04/06 21:06:29  neeri
  62. # Import of Perl 5.002
  63. #
  64.  
  65. #
  66. # At start reads $rcfile that may set important options.  This file
  67. # may define a subroutine &afterinit that will be executed after the
  68. # debugger is initialized.
  69. #
  70. # After $rcfile is read reads environment variable PERLDB_OPTS and parses
  71. # it as a rest of `O ...' line in debugger prompt.
  72. #
  73. # The options that can be specified only at startup:
  74. # [To set in $rcfile, call &parse_options("optionName=new_value").]
  75. #
  76. # TTY  - the TTY to use for debugging i/o.
  77. #
  78. # noTTY - if set, goes in NonStop mode.  On interrupt if TTY is not set
  79. # uses the value of noTTY or "/tmp/perldbtty$$" to find TTY using
  80. # Term::Rendezvous.  Current variant is to have the name of TTY in this
  81. # file.
  82. #
  83. # ReadLine - If false, dummy ReadLine is used, so you can debug
  84. # ReadLine applications.
  85. #
  86. # NonStop - if true, no i/o is performed until interrupt.
  87. #
  88. # LineInfo - file or pipe to print line number info to.  If it is a
  89. # pipe, a short "emacs like" message is used.
  90. #
  91. # Example $rcfile: (delete leading hashes!)
  92. #
  93. # &parse_options("NonStop=1 LineInfo=db.out");
  94. # sub afterinit { $trace = 1; }
  95. #
  96. # The script will run without human intervention, putting trace
  97. # information into db.out.  (If you interrupt it, you would better
  98. # reset LineInfo to something "interactive"!)
  99. #
  100. ##################################################################
  101. # Changelog:
  102.  
  103. # A lot of things changed after 0.94. First of all, core now informs
  104. # debugger about entry into XSUBs, overloaded operators, tied operations,
  105. # BEGIN and END. Handy with `O f=2'.
  106.  
  107. # This can make debugger a little bit too verbose, please be patient
  108. # and report your problems promptly.
  109.  
  110. # Now the option frame has 3 values: 0,1,2.
  111.  
  112. # Note that if DESTROY returns a reference to the object (or object),
  113. # the deletion of data may be postponed until the next function call,
  114. # due to the need to examine the return value.
  115.  
  116. # Changes: 0.95: `v' command shows versions.
  117. # Changes: 0.96: `v' command shows version of readline.
  118. #    primitive completion works (dynamic variables, subs for `b' and `l',
  119. #        options). Can `p %var'
  120. #    Better help (`h <' now works). New commands <<, >>, {, {{.
  121. #    {dump|print}_trace() coded (to be able to do it from <<cmd).
  122. #    `c sub' documented.
  123. #    At last enough magic combined to stop after the end of debuggee.
  124. #    !! should work now (thanks to Emacs bracket matching an extra
  125. #    `]' in a regexp is caught).
  126. #    `L', `D' and `A' span files now (as documented).
  127. #    Breakpoints in `require'd code are possible (used in `R').
  128. #    Some additional words on internal work of debugger.
  129. #    `b load filename' implemented.
  130. #    `b postpone subr' implemented.
  131. #    now only `q' exits debugger (overwriteable on $inhibit_exit).
  132. #    When restarting debugger breakpoints/actions persist.
  133. #     Buglet: When restarting debugger only one breakpoint/action per 
  134. #        autoloaded function persists.
  135. # Changes: 0.97: NonStop will not stop in at_exit().
  136. #    Option AutoTrace implemented.
  137. #    Trace printed differently if frames are printed too.
  138. #    new `inhibitExit' option.
  139. #    printing of a very long statement interruptible.
  140. # Changes: 0.98: New command `m' for printing possible methods
  141. #    'l -' is a synonim for `-'.
  142. #    Cosmetic bugs in printing stack trace.
  143. #    `frame' & 8 to print "expanded args" in stack trace.
  144. #    Can list/break in imported subs.
  145. #    new `maxTraceLen' option.
  146. #    frame & 4 and frame & 8 granted.
  147. #    new command `m'
  148. #    nonstoppable lines do not have `:' near the line number.
  149. #    `b compile subname' implemented.
  150. #    Will not use $` any more.
  151. #    `-' behaves sane now.
  152. # Changes: 0.99: Completion for `f', `m'.
  153. #    `m' will remove duplicate names instead of duplicate functions.
  154. #    `b load' strips trailing whitespace.
  155. #    completion ignores leading `|'; takes into account current package
  156. #    when completing a subroutine name (same for `l').
  157.  
  158. ####################################################################
  159.  
  160. # Needed for the statement after exec():
  161.  
  162. BEGIN { $ini_warn = $^W; $^W = 0 } # Switch compilation warnings off until another BEGIN.
  163. local($^W) = 0;            # Switch run-time warnings off during init.
  164. warn (            # Do not ;-)
  165.       $dumpvar::hashDepth,     
  166.       $dumpvar::arrayDepth,    
  167.       $dumpvar::dumpDBFiles,   
  168.       $dumpvar::dumpPackages,  
  169.       $dumpvar::quoteHighBit,  
  170.       $dumpvar::printUndef,    
  171.       $dumpvar::globPrint,     
  172.       $dumpvar::usageOnly,
  173.       @ARGS,
  174.       $Carp::CarpLevel,
  175.       $panic,
  176.       $second_time,
  177.      ) if 0;
  178.  
  179. # Command-line + PERLLIB:
  180. @ini_INC = @INC;
  181.  
  182. # $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?!
  183.  
  184. $trace = $signal = $single = 0;    # Uninitialized warning suppression
  185.                                 # (local $^W cannot help - other packages!).
  186. $inhibit_exit = $option{PrintRet} = 1;
  187.  
  188. @options     = qw(hashDepth arrayDepth DumpDBFiles DumpPackages 
  189.           compactDump veryCompact quote HighBit undefPrint
  190.           globPrint PrintRet UsageOnly frame AutoTrace
  191.           TTY noTTY ReadLine NonStop LineInfo maxTraceLen
  192.           recallCommand ShellBang pager tkRunning ornaments
  193.           signalLevel warnLevel dieLevel inhibit_exit);
  194.  
  195. %optionVars    = (
  196.          hashDepth    => \$dumpvar::hashDepth,
  197.          arrayDepth    => \$dumpvar::arrayDepth,
  198.          DumpDBFiles    => \$dumpvar::dumpDBFiles,
  199.          DumpPackages    => \$dumpvar::dumpPackages,
  200.          HighBit    => \$dumpvar::quoteHighBit,
  201.          undefPrint    => \$dumpvar::printUndef,
  202.          globPrint    => \$dumpvar::globPrint,
  203.          UsageOnly    => \$dumpvar::usageOnly,     
  204.          frame          => \$frame,
  205.          AutoTrace      => \$trace,
  206.          inhibit_exit   => \$inhibit_exit,
  207.          maxTraceLen    => \$maxtrace,
  208. );
  209.  
  210. %optionAction  = (
  211.           compactDump    => \&dumpvar::compactDump,
  212.           veryCompact    => \&dumpvar::veryCompact,
  213.           quote        => \&dumpvar::quote,
  214.           TTY        => \&TTY,
  215.           noTTY        => \&noTTY,
  216.           ReadLine    => \&ReadLine,
  217.           NonStop    => \&NonStop,
  218.           LineInfo    => \&LineInfo,
  219.           recallCommand    => \&recallCommand,
  220.           ShellBang    => \&shellBang,
  221.           pager        => \&pager,
  222.           signalLevel    => \&signalLevel,
  223.           warnLevel    => \&warnLevel,
  224.           dieLevel    => \&dieLevel,
  225.           tkRunning    => \&tkRunning,
  226.           ornaments    => \&ornaments,
  227.          );
  228.  
  229. %optionRequire = (
  230.           compactDump    => 'dumpvar.pl',
  231.           veryCompact    => 'dumpvar.pl',
  232.           quote        => 'dumpvar.pl',
  233.          );
  234.  
  235. # These guys may be defined in $ENV{PERL5DB} :
  236. $rl = 1 unless defined $rl;
  237. $warnLevel = 1 unless defined $warnLevel;
  238. $dieLevel = 1 unless defined $dieLevel;
  239. $signalLevel = 1 unless defined $signalLevel;
  240. $pre = [] unless defined $pre;
  241. $post = [] unless defined $post;
  242. $pretype = [] unless defined $pretype;
  243. warnLevel($warnLevel);
  244. dieLevel($dieLevel);
  245. signalLevel($signalLevel);
  246. &pager(defined($ENV{PAGER}) ? $ENV{PAGER} : "|more") unless defined $pager;
  247. &recallCommand("!") unless defined $prc;
  248. &shellBang("!") unless defined $psh;
  249. $maxtrace = 400 unless defined $maxtrace;
  250.  
  251. if (-e "/dev/tty") {
  252.   $rcfile=".perldb";
  253. } else {
  254.   $rcfile="perldb.ini";
  255. }
  256.  
  257. if (-f $rcfile) {
  258.     do "./$rcfile";
  259. } elsif (defined $ENV{LOGDIR} and -f "$ENV{LOGDIR}/$rcfile") {
  260.     do "$ENV{LOGDIR}/$rcfile";
  261. } elsif (defined $ENV{HOME} and -f "$ENV{HOME}/$rcfile") {
  262.     do "$ENV{HOME}/$rcfile";
  263. }
  264.  
  265. if (defined $ENV{PERLDB_OPTS}) {
  266.   parse_options($ENV{PERLDB_OPTS});
  267. }
  268.  
  269. if (exists $ENV{PERLDB_RESTART}) {
  270.   delete $ENV{PERLDB_RESTART};
  271.   # $restart = 1;
  272.   @hist = get_list('PERLDB_HIST');
  273.   %break_on_load = get_list("PERLDB_ON_LOAD");
  274.   %postponed = get_list("PERLDB_POSTPONE");
  275.   my @had_breakpoints= get_list("PERLDB_VISITED");
  276.   for (0 .. $#had_breakpoints) {
  277.     my %pf = get_list("PERLDB_FILE_$_");
  278.     $postponed_file{$had_breakpoints[$_]} = \%pf if %pf;
  279.   }
  280.   my %opt = get_list("PERLDB_OPT");
  281.   my ($opt,$val);
  282.   while (($opt,$val) = each %opt) {
  283.     $val =~ s/[\\\']/\\$1/g;
  284.     parse_options("$opt'$val'");
  285.   }
  286.   @INC = get_list("PERLDB_INC");
  287.   @ini_INC = @INC;
  288.   $pretype = [get_list("PERLDB_PRETYPE")];
  289.   $pre = [get_list("PERLDB_PRE")];
  290.   $post = [get_list("PERLDB_POST")];
  291.   @typeahead = get_list("PERLDB_TYPEAHEAD", @typeahead);
  292. }
  293.  
  294. if ($notty) {
  295.   $runnonstop = 1;
  296. } else {
  297.   # Is Perl being run from Emacs?
  298.   $emacs = ((defined $main::ARGV[0]) and ($main::ARGV[0] eq '-emacs'));
  299.   $rl = 0, shift(@main::ARGV) if $emacs;
  300.  
  301.   #require Term::ReadLine;
  302.  
  303.   if ($^O eq 'MacOS') {
  304.     if ($MacPerl::Version =~ /MPW/) {
  305.       $console = "Dev:Console";
  306.     } else {
  307.       $console = "Dev:Console:Perl Debug";    # Separate window for application
  308.     }
  309.   } elsif (-e "/dev/tty") {
  310.     $console = "/dev/tty";
  311.   } elsif (-e "con" or $^O eq 'MSWin32') {
  312.     $console = "con";
  313.   } else {
  314.     $console = "sys\$command";
  315.   }
  316.  
  317.   # Around a bug:
  318.   if (defined $ENV{OS2_SHELL} and ($emacs or $ENV{WINDOWID})) { # In OS/2
  319.     $console = undef;
  320.   }
  321.  
  322.   $console = $tty if defined $tty;
  323.  
  324.   if (defined $console) {
  325.     open(IN,"+<$console") || open(IN,"<$console") || open(IN,"<&STDIN");
  326.     open(OUT,"+>$console") || open(OUT,">$console") || open(OUT,">&STDERR")
  327.       || open(OUT,">&STDOUT");    # so we don't dongle stdout
  328.   } else {
  329.     open(IN,"<&STDIN");
  330.     open(OUT,">&STDERR") || open(OUT,">&STDOUT"); # so we don't dongle stdout
  331.     $console = 'STDIN/OUT';
  332.   }
  333.   # so open("|more") can read from STDOUT and so we don't dingle stdin
  334.   $IN = \*IN;
  335.  
  336.   $OUT = \*OUT;
  337.   select($OUT);
  338.   $| = 1;            # for DB::OUT
  339.   select(STDOUT);
  340.  
  341.   $LINEINFO = $OUT unless defined $LINEINFO;
  342.   $lineinfo = $console unless defined $lineinfo;
  343.  
  344.   $| = 1;            # for real STDOUT
  345.  
  346.   $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/;
  347.   unless ($runnonstop) {
  348.     print $OUT "\nLoading DB routines from $header\n";
  349.     print $OUT ("Emacs support ",
  350.         $emacs ? "enabled" : "available",
  351.         ".\n");
  352.     print $OUT "\nEnter h or `h h' for help.\n\n";
  353.   }
  354. }
  355.  
  356. @ARGS = @ARGV;
  357. for (@args) {
  358.     s/\'/\\\'/g;
  359.     s/(.*)/'$1'/ unless /^-?[\d.]+$/;
  360. }
  361.  
  362. if (defined &afterinit) {    # May be defined in $rcfile
  363.   &afterinit();
  364. }
  365.  
  366. $I_m_init = 1;
  367.  
  368. ############################################################ Subroutines
  369.  
  370. sub DB {
  371.     # _After_ the perl program is compiled, $single is set to 1:
  372.     if ($single and not $second_time++) {
  373.       if ($runnonstop) {    # Disable until signal
  374.     for ($i=0; $i <= $#stack; ) {
  375.         $stack[$i++] &= ~1;
  376.     }
  377.     $single = 0;
  378.     # return;            # Would not print trace!
  379.       }
  380.     }
  381.     $runnonstop = 0 if $single or $signal; # Disable it if interactive.
  382.     &save;
  383.     ($package, $filename, $line) = caller;
  384.     $filename_ini = $filename;
  385.     $usercontext = '($@, $!, $,, $/, $\, $^W) = @saved;' .
  386.       "package $package;";    # this won't let them modify, alas
  387.     local(*dbline) = $main::{'_<' . $filename};
  388.     $max = $#dbline;
  389.     if (($stop,$action) = split(/\0/,$dbline{$line})) {
  390.     if ($stop eq '1') {
  391.         $signal |= 1;
  392.     } elsif ($stop) {
  393.         $evalarg = "\$DB::signal |= do {$stop;}"; &eval;
  394.         $dbline{$line} =~ s/;9($|\0)/$1/;
  395.     }
  396.     }
  397.     my $was_signal = $signal;
  398.     $signal = 0;
  399.     if ($single || $trace || $was_signal) {
  400.     $term || &setterm;
  401.     if ($emacs) {
  402.         $position = "\032\032$filename:$line:0\n";
  403.         print $LINEINFO $position;
  404.     } else {
  405.         $sub =~ s/\'/::/;
  406.         $prefix = $sub =~ /::/ ? "" : "${'package'}::";
  407.         $prefix .= "$sub($filename:";
  408.         $after = ($dbline[$line] =~ /\n$/ ? '' : "\n");
  409.         if (length($prefix) > 30) {
  410.             $position = "$prefix$line):\n$line:\t$dbline[$line]$after";
  411.         $prefix = "";
  412.         $infix = ":\t";
  413.         } else {
  414.         $infix = "):\t";
  415.         $position = "$prefix$line$infix$dbline[$line]$after";
  416.         }
  417.         if ($frame) {
  418.         print $LINEINFO ' ' x $#stack, "$line:\t$dbline[$line]$after";
  419.         } else {
  420.         print $LINEINFO $position;
  421.         }
  422.         for ($i = $line + 1; $i <= $max && $dbline[$i] == 0; ++$i) { #{ vi
  423.         last if $dbline[$i] =~ /^\s*[\;\}\#\n]/;
  424.         last if $signal;
  425.         $after = ($dbline[$i] =~ /\n$/ ? '' : "\n");
  426.         $incr_pos = "$prefix$i$infix$dbline[$i]$after";
  427.         $position .= $incr_pos;
  428.         if ($frame) {
  429.             print $LINEINFO ' ' x $#stack, "$i:\t$dbline[$i]$after";
  430.         } else {
  431.             print $LINEINFO $incr_pos;
  432.         }
  433.         }
  434.     }
  435.     }
  436.     $evalarg = $action, &eval if $action;
  437.     if ($single || $was_signal) {
  438.     local $level = $level + 1;
  439.     foreach $evalarg (@$pre) {
  440.       &eval;
  441.     }
  442.     print $OUT $#stack . " levels deep in subroutine calls!\n"
  443.       if $single & 4;
  444.     $start = $line;
  445.     $incr = -1;        # for backward motion.
  446.     @typeahead = @$pretype, @typeahead;
  447.       CMD:
  448.     while (($term || &setterm),
  449.            defined ($cmd=&readline("  DB" . ('<' x $level) .
  450.                        ($#hist+1) . ('>' x $level) .
  451.                        " "))) {
  452.         $single = 0;
  453.         $signal = 0;
  454.         $cmd =~ s/\\$/\n/ && do {
  455.             $cmd .= &readline("  cont: ");
  456.             redo CMD;
  457.         };
  458.         $cmd =~ /^$/ && ($cmd = $laststep);
  459.         push(@hist,$cmd) if length($cmd) > 1;
  460.           PIPE: {
  461.             ($i) = split(/\s+/,$cmd);
  462.             eval "\$cmd =~ $alias{$i}", print $OUT $@ if $alias{$i};
  463.             $cmd =~ /^q$/ && ($exiting = 1) && exit 0;
  464.             $cmd =~ /^h$/ && do {
  465.             print $OUT $help;
  466.             next CMD; };
  467.             $cmd =~ /^h\s+h$/ && do {
  468.             print $OUT $summary;
  469.             next CMD; };
  470.             $cmd =~ /^h\s+(\S)$/ && do {
  471.             my $asked = "\Q$1";
  472.             if ($help =~ /^$asked/m) {
  473.               while ($help =~ /^($asked([\s\S]*?)\n)(\Z|[^\s$asked])/mg) {
  474.                 print $OUT $1;
  475.               }
  476.             } else {
  477.                 print $OUT "`$asked' is not a debugger command.\n";
  478.             }
  479.             next CMD; };
  480.             $cmd =~ /^t$/ && do {
  481.             $trace = !$trace;
  482.             print $OUT "Trace = ".($trace?"on":"off")."\n";
  483.             next CMD; };
  484.             $cmd =~ /^S(\s+(!)?(.+))?$/ && do {
  485.             $Srev = defined $2; $Spatt = $3; $Snocheck = ! defined $1;
  486.             foreach $subname (sort(keys %sub)) {
  487.                 if ($Snocheck or $Srev^($subname =~ /$Spatt/)) {
  488.                 print $OUT $subname,"\n";
  489.                 }
  490.             }
  491.             next CMD; };
  492.             $cmd =~ /^v$/ && do {
  493.             list_versions(); next CMD};
  494.             $cmd =~ s/^X\b/V $package/;
  495.             $cmd =~ /^V$/ && do {
  496.             $cmd = "V $package"; };
  497.             $cmd =~ /^V\b\s*(\S+)\s*(.*)/ && do {
  498.             local ($savout) = select($OUT);
  499.             $packname = $1;
  500.             @vars = split(' ',$2);
  501.             do 'dumpvar.pl' unless defined &main::dumpvar;
  502.             if (defined &main::dumpvar) {
  503.                 local $frame = 0;
  504.                 local $doret = -2;
  505.                 &main::dumpvar($packname,@vars);
  506.             } else {
  507.                 print $OUT "dumpvar.pl not available.\n";
  508.             }
  509.             select ($savout);
  510.             next CMD; };
  511.             $cmd =~ s/^x\b/ / && do { # So that will be evaled
  512.             $onetimeDump = 'dump'; };
  513.             $cmd =~ s/^m\s+([\w:]+)\s*$/ / && do {
  514.             methods($1); next CMD};
  515.             $cmd =~ s/^m\b/ / && do { # So this will be evaled
  516.             $onetimeDump = 'methods'; };
  517.             $cmd =~ /^f\b\s*(.*)/ && do {
  518.             $file = $1;
  519.             $file =~ s/\s+$//;
  520.             if (!$file) {
  521.                 print $OUT "The old f command is now the r command.\n";
  522.                 print $OUT "The new f command switches filenames.\n";
  523.                 next CMD;
  524.             }
  525.             if (!defined $main::{'_<' . $file}) {
  526.                 if (($try) = grep(m#^_<.*$file#, keys %main::)) {{
  527.                           $try = substr($try,2);
  528.                           print $OUT "Choosing $try matching `$file':\n";
  529.                           $file = $try;
  530.                       }}
  531.             }
  532.             if (!defined $main::{'_<' . $file}) {
  533.                 print $OUT "No file matching `$file' is loaded.\n";
  534.                 next CMD;
  535.             } elsif ($file ne $filename) {
  536.                 *dbline = $main::{'_<' . $file};
  537.                 $max = $#dbline;
  538.                 $filename = $file;
  539.                 $start = 1;
  540.                 $cmd = "l";
  541.               } else {
  542.                 print $OUT "Already in $file.\n";
  543.                 next CMD;
  544.               }
  545.               };
  546.             $cmd =~ s/^l\s+-\s*$/-/;
  547.             $cmd =~ /^l\b\s*([\':A-Za-z_][\':\w]*)/ && do {
  548.             $subname = $1;
  549.             $subname =~ s/\'/::/;
  550.             $subname = $package."::".$subname 
  551.               unless $subname =~ /::/;
  552.             $subname = "main".$subname if substr($subname,0,2) eq "::";
  553.             @pieces = split(/:/,find_sub($subname));
  554.             $subrange = pop @pieces;
  555.             $file = join(':', @pieces);
  556.             if ($file ne $filename) {
  557.                 *dbline = $main::{'_<' . $file};
  558.                 $max = $#dbline;
  559.                 $filename = $file;
  560.             }
  561.             if ($subrange) {
  562.                 if (eval($subrange) < -$window) {
  563.                 $subrange =~ s/-.*/+/;
  564.                 }
  565.                 $cmd = "l $subrange";
  566.             } else {
  567.                 print $OUT "Subroutine $subname not found.\n";
  568.                 next CMD;
  569.             } };
  570.             $cmd =~ /^\.$/ && do {
  571.             $incr = -1;        # for backward motion.
  572.             $start = $line;
  573.             $filename = $filename_ini;
  574.             *dbline = $main::{'_<' . $filename};
  575.             $max = $#dbline;
  576.             print $LINEINFO $position;
  577.             next CMD };
  578.             $cmd =~ /^w\b\s*(\d*)$/ && do {
  579.             $incr = $window - 1;
  580.             $start = $1 if $1;
  581.             $start -= $preview;
  582.             #print $OUT 'l ' . $start . '-' . ($start + $incr);
  583.             $cmd = 'l ' . $start . '-' . ($start + $incr); };
  584.             $cmd =~ /^-$/ && do {
  585.             $start -= $incr + $window + 1;
  586.             $start = 1 if $start <= 0;
  587.             $incr = $window - 1;
  588.             $cmd = 'l ' . ($start) . '+'; };
  589.             $cmd =~ /^l$/ && do {
  590.             $incr = $window - 1;
  591.             $cmd = 'l ' . $start . '-' . ($start + $incr); };
  592.             $cmd =~ /^l\b\s*(\d*)\+(\d*)$/ && do {
  593.             $start = $1 if $1;
  594.             $incr = $2;
  595.             $incr = $window - 1 unless $incr;
  596.             $cmd = 'l ' . $start . '-' . ($start + $incr); };
  597.             $cmd =~ /^l\b\s*((-?[\d\$\.]+)([-,]([\d\$\.]+))?)?/ && do {
  598.             $end = (!defined $2) ? $max : ($4 ? $4 : $2);
  599.             $end = $max if $end > $max;
  600.             $i = $2;
  601.             $i = $line if $i eq '.';
  602.             $i = 1 if $i < 1;
  603.             $incr = $end - $i;
  604.             if ($emacs) {
  605.                 print $OUT "\032\032$filename:$i:0\n";
  606.                 $i = $end;
  607.             } else {
  608.                 for (; $i <= $end; $i++) {
  609.                     ($stop,$action) = split(/\0/, $dbline{$i});
  610.                     $arrow = ($i==$line 
  611.                       and $filename eq $filename_ini) 
  612.                   ?  '==>' 
  613.                     : ($dbline[$i]+0 ? ':' : ' ') ;
  614.                 $arrow .= 'b' if $stop;
  615.                 $arrow .= 'a' if $action;
  616.                 print $OUT "$i$arrow\t", $dbline[$i];
  617.                 last if $signal;
  618.                 }
  619.             }
  620.             $start = $i; # remember in case they want more
  621.             $start = $max if $start > $max;
  622.             next CMD; };
  623.             $cmd =~ /^D$/ && do {
  624.               print $OUT "Deleting all breakpoints...\n";
  625.               my $file;
  626.               for $file (keys %had_breakpoints) {
  627.             local *dbline = $main::{'_<' . $file};
  628.             my $max = $#dbline;
  629.             my $was;
  630.             
  631.             for ($i = 1; $i <= $max ; $i++) {
  632.                 if (defined $dbline{$i}) {
  633.                 $dbline{$i} =~ s/^[^\0]+//;
  634.                 if ($dbline{$i} =~ s/^\0?$//) {
  635.                     delete $dbline{$i};
  636.                 }
  637.                 }
  638.             }
  639.               }
  640.               undef %postponed;
  641.               undef %postponed_file;
  642.               undef %break_on_load;
  643.               undef %had_breakpoints;
  644.               next CMD; };
  645.             $cmd =~ /^L$/ && do {
  646.               my $file;
  647.               for $file (keys %had_breakpoints) {
  648.             local *dbline = $main::{'_<' . $file};
  649.             my $max = $#dbline;
  650.             my $was;
  651.             
  652.             for ($i = 1; $i <= $max; $i++) {
  653.                 if (defined $dbline{$i}) {
  654.                     print "$file:\n" unless $was++;
  655.                 print $OUT " $i:\t", $dbline[$i];
  656.                 ($stop,$action) = split(/\0/, $dbline{$i});
  657.                 print $OUT "   break if (", $stop, ")\n"
  658.                   if $stop;
  659.                 print $OUT "   action:  ", $action, "\n"
  660.                   if $action;
  661.                 last if $signal;
  662.                 }
  663.             }
  664.               }
  665.               if (%postponed) {
  666.             print $OUT "Postponed breakpoints in subroutines:\n";
  667.             my $subname;
  668.             for $subname (keys %postponed) {
  669.               print $OUT " $subname\t$postponed{$subname}\n";
  670.               last if $signal;
  671.             }
  672.               }
  673.               my @have = map { # Combined keys
  674.             keys %{$postponed_file{$_}}
  675.               } keys %postponed_file;
  676.               if (@have) {
  677.             print $OUT "Postponed breakpoints in files:\n";
  678.             my ($file, $line);
  679.             for $file (keys %postponed_file) {
  680.               my $db = $postponed_file{$file};
  681.               print $OUT " $file:\n";
  682.               for $line (sort {$a <=> $b} keys %$db) {
  683.                 print $OUT "  $line:\n";
  684.                 my ($stop,$action) = split(/\0/, $$db{$line});
  685.                 print $OUT "    break if (", $stop, ")\n"
  686.                   if $stop;
  687.                 print $OUT "    action:  ", $action, "\n"
  688.                   if $action;
  689.                 last if $signal;
  690.               }
  691.               last if $signal;
  692.             }
  693.               }
  694.               if (%break_on_load) {
  695.             print $OUT "Breakpoints on load:\n";
  696.             my $file;
  697.             for $file (keys %break_on_load) {
  698.               print $OUT " $file\n";
  699.               last if $signal;
  700.             }
  701.               }
  702.               next CMD; };
  703.             $cmd =~ /^b\b\s*load\b\s*(.*)/ && do {
  704.             my $file = $1; $file =~ s/\s+$//;
  705.             {
  706.               $break_on_load{$file} = 1;
  707.               $break_on_load{$::INC{$file}} = 1 if $::INC{$file};
  708.               $file .= '.pm', redo unless $file =~ /\./;
  709.             }
  710.             $had_breakpoints{$file} = 1;
  711.             print $OUT "Will stop on load of `@{[join '\', `', sort keys %break_on_load]}'.\n";
  712.             next CMD; };
  713.             $cmd =~ /^b\b\s*(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/ && do {
  714.             my $cond = $3 || '1';
  715.             my ($subname, $break) = ($2, $1 eq 'postpone');
  716.             $subname =~ s/\'/::/;
  717.             $subname = "${'package'}::" . $subname
  718.               unless $subname =~ /::/;
  719.             $subname = "main".$subname if substr($subname,0,2) eq "::";
  720.             $postponed{$subname} = $break 
  721.               ? "break +0 if $cond" : "compile";
  722.             next CMD; };
  723.             $cmd =~ /^b\b\s*([':A-Za-z_][':\w]*)\s*(.*)/ && do {
  724.             $subname = $1;
  725.             $cond = $2 || '1';
  726.             $subname =~ s/\'/::/;
  727.             $subname = "${'package'}::" . $subname
  728.               unless $subname =~ /::/;
  729.             $subname = "main".$subname if substr($subname,0,2) eq "::";
  730.             # Filename below can contain ':'
  731.             ($file,$i) = (find_sub($subname) =~ /^(.*):(.*)$/);
  732.             $i += 0;
  733.             if ($i) {
  734.                 $filename = $file;
  735.                 *dbline = $main::{'_<' . $filename};
  736.                 $had_breakpoints{$filename} = 1;
  737.                 $max = $#dbline;
  738.                 ++$i while $dbline[$i] == 0 && $i < $max;
  739.                 $dbline{$i} =~ s/^[^\0]*/$cond/;
  740.             } else {
  741.                 print $OUT "Subroutine $subname not found.\n";
  742.             }
  743.             next CMD; };
  744.             $cmd =~ /^b\b\s*(\d*)\s*(.*)/ && do {
  745.             $i = ($1?$1:$line);
  746.             $cond = $2 || '1';
  747.             if ($dbline[$i] == 0) {
  748.                 print $OUT "Line $i not breakable.\n";
  749.             } else {
  750.                 $had_breakpoints{$filename} = 1;
  751.                 $dbline{$i} =~ s/^[^\0]*/$cond/;
  752.             }
  753.             next CMD; };
  754.             $cmd =~ /^d\b\s*(\d+)?/ && do {
  755.             $i = ($1?$1:$line);
  756.             $dbline{$i} =~ s/^[^\0]*//;
  757.             delete $dbline{$i} if $dbline{$i} eq '';
  758.             next CMD; };
  759.             $cmd =~ /^A$/ && do {
  760.               my $file;
  761.               for $file (keys %had_breakpoints) {
  762.             local *dbline = $main::{'_<' . $file};
  763.             my $max = $#dbline;
  764.             my $was;
  765.             
  766.             for ($i = 1; $i <= $max ; $i++) {
  767.                 if (defined $dbline{$i}) {
  768.                 $dbline{$i} =~ s/\0[^\0]*//;
  769.                 delete $dbline{$i} if $dbline{$i} eq '';
  770.                 }
  771.             }
  772.               }
  773.               next CMD; };
  774.             $cmd =~ /^O\s*$/ && do {
  775.             for (@options) {
  776.                 &dump_option($_);
  777.             }
  778.             next CMD; };
  779.             $cmd =~ /^O\s*(\S.*)/ && do {
  780.             parse_options($1);
  781.             next CMD; };
  782.             $cmd =~ /^\<\<\s*(.*)/ && do { # \<\< for CPerl sake: not HERE
  783.             push @$pre, action($1);
  784.             next CMD; };
  785.             $cmd =~ /^>>\s*(.*)/ && do {
  786.             push @$post, action($1);
  787.             next CMD; };
  788.             $cmd =~ /^<\s*(.*)/ && do {
  789.                 $pre = [], next CMD unless $1;
  790.             $pre = [action($1)];
  791.             next CMD; };
  792.             $cmd =~ /^>\s*(.*)/ && do {
  793.                 $post = [], next CMD unless $1;
  794.             $post = [action($1)];
  795.             next CMD; };
  796.             $cmd =~ /^\{\{\s*(.*)/ && do {
  797.             push @$pretype, $1;
  798.             next CMD; };
  799.             $cmd =~ /^\{\s*(.*)/ && do {
  800.                 $pretype = [], next CMD unless $1;
  801.             $pretype = [$1];
  802.             next CMD; };
  803.             $cmd =~ /^a\b\s*(\d+)(\s+(.*))?/ && do {
  804.             $i = $1; $j = $3;
  805.             if ($dbline[$i] == 0) {
  806.                 print $OUT "Line $i may not have an action.\n";
  807.             } else {
  808.                 $dbline{$i} =~ s/\0[^\0]*//;
  809.                 $dbline{$i} .= "\0" . action($j);
  810.             }
  811.             next CMD; };
  812.             $cmd =~ /^n$/ && do {
  813.                 end_report(), next CMD if $finished and $level <= 1;
  814.             $single = 2;
  815.             $laststep = $cmd;
  816.             last CMD; };
  817.             $cmd =~ /^s$/ && do {
  818.                 end_report(), next CMD if $finished and $level <= 1;
  819.             $single = 1;
  820.             $laststep = $cmd;
  821.             last CMD; };
  822.             $cmd =~ /^c\b\s*([\w:]*)\s*$/ && do {
  823.                 end_report(), next CMD if $finished and $level <= 1;
  824.             $i = $1;
  825.             if ($i =~ /\D/) { # subroutine name
  826.                 ($file,$i) = (find_sub($i) =~ /^(.*):(.*)$/);
  827.                 $i += 0;
  828.                 if ($i) {
  829.                     $filename = $file;
  830.                 *dbline = $main::{'_<' . $filename};
  831.                 $had_breakpoints{$filename}++;
  832.                 $max = $#dbline;
  833.                 ++$i while $dbline[$i] == 0 && $i < $max;
  834.                 } else {
  835.                 print $OUT "Subroutine $subname not found.\n";
  836.                 next CMD; 
  837.                 }
  838.             }
  839.             if ($i) {
  840.                 if ($dbline[$i] == 0) {
  841.                 print $OUT "Line $i not breakable.\n";
  842.                 next CMD;
  843.                 }
  844.                 $dbline{$i} =~ s/($|\0)/;9$1/; # add one-time-only b.p.
  845.             }
  846.             for ($i=0; $i <= $#stack; ) {
  847.                 $stack[$i++] &= ~1;
  848.             }
  849.             last CMD; };
  850.             $cmd =~ /^r$/ && do {
  851.                 end_report(), next CMD if $finished and $level <= 1;
  852.             $stack[$#stack] |= 1;
  853.             $doret = $option{PrintRet} ? $#stack - 1 : -2;
  854.             last CMD; };
  855.             $cmd =~ /^R$/ && do {
  856.                 print $OUT "Warning: some settings and command-line options may be lost!\n";
  857.             my (@script, @flags, $cl);
  858.             push @flags, '-w' if $ini_warn;
  859.             # Put all the old includes at the start to get
  860.             # the same debugger.
  861.             for (@ini_INC) {
  862.               push @flags, '-I', $_;
  863.             }
  864.             # Arrange for setting the old INC:
  865.             set_list("PERLDB_INC", @ini_INC);
  866.             if ($0 eq '-e') {
  867.               for (1..$#{'::_<-e'}) { # The first line is PERL5DB
  868.                 chomp ($cl =  $ {'::_<-e'}[$_]);
  869.                 push @script, '-e', $cl;
  870.               }
  871.             } else {
  872.               @script = $0;
  873.             }
  874.             set_list("PERLDB_HIST", 
  875.                  $term->Features->{getHistory} 
  876.                  ? $term->GetHistory : @hist);
  877.             my @had_breakpoints = keys %had_breakpoints;
  878.             set_list("PERLDB_VISITED", @had_breakpoints);
  879.             set_list("PERLDB_OPT", %option);
  880.             set_list("PERLDB_ON_LOAD", %break_on_load);
  881.             my @hard;
  882.             for (0 .. $#had_breakpoints) {
  883.               my $file = $had_breakpoints[$_];
  884.               *dbline = $main::{'_<' . $file};
  885.               next unless %dbline or $postponed_file{$file};
  886.               (push @hard, $file), next 
  887.                 if $file =~ /^\(eval \d+\)$/;
  888.               my @add;
  889.               @add = %{$postponed_file{$file}}
  890.                 if $postponed_file{$file};
  891.               set_list("PERLDB_FILE_$_", %dbline, @add);
  892.             }
  893.             for (@hard) { # Yes, really-really...
  894.               # Find the subroutines in this eval
  895.               *dbline = $main::{'_<' . $_};
  896.               my ($quoted, $sub, %subs, $line) = quotemeta $_;
  897.               for $sub (keys %sub) {
  898.                 next unless $sub{$sub} =~ /^$quoted:(\d+)-(\d+)$/;
  899.                 $subs{$sub} = [$1, $2];
  900.               }
  901.               unless (%subs) {
  902.                 print $OUT
  903.                   "No subroutines in $_, ignoring breakpoints.\n";
  904.                 next;
  905.               }
  906.             LINES: for $line (keys %dbline) {
  907.                 # One breakpoint per sub only:
  908.                 my ($offset, $sub, $found);
  909.               SUBS: for $sub (keys %subs) {
  910.                   if ($subs{$sub}->[1] >= $line # Not after the subroutine
  911.                   and (not defined $offset # Not caught
  912.                        or $offset < 0 )) { # or badly caught
  913.                 $found = $sub;
  914.                 $offset = $line - $subs{$sub}->[0];
  915.                 $offset = "+$offset", last SUBS if $offset >= 0;
  916.                   }
  917.                 }
  918.                 if (defined $offset) {
  919.                   $postponed{$found} =
  920.                 "break $offset if $dbline{$line}";
  921.                 } else {
  922.                   print $OUT "Breakpoint in $_:$line ignored: after all the subroutines.\n";
  923.                 }
  924.               }
  925.             }
  926.             set_list("PERLDB_POSTPONE", %postponed);
  927.             set_list("PERLDB_PRETYPE", @$pretype);
  928.             set_list("PERLDB_PRE", @$pre);
  929.             set_list("PERLDB_POST", @$post);
  930.             set_list("PERLDB_TYPEAHEAD", @typeahead);
  931.             $ENV{PERLDB_RESTART} = 1;
  932.             #print "$^X, '-d', @flags, @script, ($emacs ? '-emacs' : ()), @ARGS";
  933.             exec $^X, '-d', @flags, @script, ($emacs ? '-emacs' : ()), @ARGS;
  934.             print $OUT "exec failed: $!\n";
  935.             last CMD; };
  936.             $cmd =~ /^T$/ && do {
  937.             print_trace($OUT, 1); # skip DB
  938.             next CMD; };
  939.             $cmd =~ /^\/(.*)$/ && do {
  940.             $inpat = $1;
  941.             $inpat =~ s:([^\\])/$:$1:;
  942.             if ($inpat ne "") {
  943.                 eval '$inpat =~ m'."\a$inpat\a";    
  944.                 if ($@ ne "") {
  945.                 print $OUT "$@";
  946.                 next CMD;
  947.                 }
  948.                 $pat = $inpat;
  949.             }
  950.             $end = $start;
  951.             $incr = -1;
  952.             eval '
  953.                 for (;;) {
  954.                 ++$start;
  955.                 $start = 1 if ($start > $max);
  956.                 last if ($start == $end);
  957.                 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
  958.                     if ($emacs) {
  959.                     print $OUT "\032\032$filename:$start:0\n";
  960.                     } else {
  961.                     print $OUT "$start:\t", $dbline[$start], "\n";
  962.                     }
  963.                     last;
  964.                 }
  965.                 } ';
  966.             print $OUT "/$pat/: not found\n" if ($start == $end);
  967.             next CMD; };
  968.             $cmd =~ /^\?(.*)$/ && do {
  969.             $inpat = $1;
  970.             $inpat =~ s:([^\\])\?$:$1:;
  971.             if ($inpat ne "") {
  972.                 eval '$inpat =~ m'."\a$inpat\a";    
  973.                 if ($@ ne "") {
  974.                 print $OUT "$@";
  975.                 next CMD;
  976.                 }
  977.                 $pat = $inpat;
  978.             }
  979.             $end = $start;
  980.             $incr = -1;
  981.             eval '
  982.                 for (;;) {
  983.                 --$start;
  984.                 $start = $max if ($start <= 0);
  985.                 last if ($start == $end);
  986.                 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
  987.                     if ($emacs) {
  988.                     print $OUT "\032\032$filename:$start:0\n";
  989.                     } else {
  990.                     print $OUT "$start:\t", $dbline[$start], "\n";
  991.                     }
  992.                     last;
  993.                 }
  994.                 } ';
  995.             print $OUT "?$pat?: not found\n" if ($start == $end);
  996.             next CMD; };
  997.             $cmd =~ /^$rc+\s*(-)?(\d+)?$/ && do {
  998.             pop(@hist) if length($cmd) > 1;
  999.             $i = $1 ? ($#hist-($2?$2:1)) : ($2?$2:$#hist);
  1000.             $cmd = $hist[$i] . "\n";
  1001.             print $OUT $cmd;
  1002.             redo CMD; };
  1003.             $cmd =~ /^$sh$sh\s*([\x00-\xff]*)/ && do {
  1004.             &system($1);
  1005.             next CMD; };
  1006.             $cmd =~ /^$rc([^$rc].*)$/ && do {
  1007.             $pat = "^$1";
  1008.             pop(@hist) if length($cmd) > 1;
  1009.             for ($i = $#hist; $i; --$i) {
  1010.                 last if $hist[$i] =~ /$pat/;
  1011.             }
  1012.             if (!$i) {
  1013.                 print $OUT "No such command!\n\n";
  1014.                 next CMD;
  1015.             }
  1016.             $cmd = $hist[$i] . "\n";
  1017.             print $OUT $cmd;
  1018.             redo CMD; };
  1019.             $cmd =~ /^$sh$/ && do {
  1020.             &system($ENV{SHELL}||"/bin/sh");
  1021.             next CMD; };
  1022.             $cmd =~ /^$sh\s*([\x00-\xff]*)/ && do {
  1023.             &system($ENV{SHELL}||"/bin/sh","-c",$1);
  1024.             next CMD; };
  1025.             $cmd =~ /^H\b\s*(-(\d+))?/ && do {
  1026.             $end = $2?($#hist-$2):0;
  1027.             $hist = 0 if $hist < 0;
  1028.             for ($i=$#hist; $i>$end; $i--) {
  1029.                 print $OUT "$i: ",$hist[$i],"\n"
  1030.                   unless $hist[$i] =~ /^.?$/;
  1031.             };
  1032.             next CMD; };
  1033.             $cmd =~ s/^p$/print {\$DB::OUT} \$_/;
  1034.             $cmd =~ s/^p\b/print {\$DB::OUT} /;
  1035.             $cmd =~ /^=/ && do {
  1036.             if (local($k,$v) = ($cmd =~ /^=\s*(\S+)\s+(.*)/)) {
  1037.                 $alias{$k}="s~$k~$v~";
  1038.                 print $OUT "$k = $v\n";
  1039.             } elsif ($cmd =~ /^=\s*$/) {
  1040.                 foreach $k (sort keys(%alias)) {
  1041.                 if (($v = $alias{$k}) =~ s~^s\~$k\~(.*)\~$~$1~) {
  1042.                     print $OUT "$k = $v\n";
  1043.                 } else {
  1044.                     print $OUT "$k\t$alias{$k}\n";
  1045.                 };
  1046.                 };
  1047.             };
  1048.             next CMD; };
  1049.             $cmd =~ /^\|\|?\s*[^|]/ && do {
  1050.             if ($pager =~ /^\|/) {
  1051.                 open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
  1052.                 open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
  1053.             } else {
  1054.                 open(SAVEOUT,">&OUT") || &warn("Can't save DB::OUT");
  1055.             }
  1056.             unless ($piped=open(OUT,$pager)) {
  1057.                 &warn("Can't pipe output to `$pager'");
  1058.                 if ($pager =~ /^\|/) {
  1059.                 open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
  1060.                 open(STDOUT,">&SAVEOUT")
  1061.                   || &warn("Can't restore STDOUT");
  1062.                 close(SAVEOUT);
  1063.                 } else {
  1064.                 open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
  1065.                 }
  1066.                 next CMD;
  1067.             }
  1068.             $SIG{PIPE}= \&DB::catch if $pager =~ /^\|/
  1069.               && "" eq $SIG{PIPE}  ||  "DEFAULT" eq $SIG{PIPE};
  1070.             $selected= select(OUT);
  1071.             $|= 1;
  1072.             select( $selected ), $selected= "" unless $cmd =~ /^\|\|/;
  1073.             $cmd =~ s/^\|+\s*//;
  1074.             redo PIPE; };
  1075.             # XXX Local variants do not work!
  1076.             $cmd =~ s/^t\s/\$DB::trace = 1;\n/;
  1077.             $cmd =~ s/^s\s/\$DB::single = 1;\n/ && do {$laststep = 's'};
  1078.             $cmd =~ s/^n\s/\$DB::single = 2;\n/ && do {$laststep = 'n'};
  1079.         }        # PIPE:
  1080.         $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd"; &eval;
  1081.         if ($onetimeDump) {
  1082.         $onetimeDump = undef;
  1083.         } else {
  1084.         print $OUT "\n";
  1085.         }
  1086.     } continue {        # CMD:
  1087.         if ($piped) {
  1088.         if ($pager =~ /^\|/) {
  1089.             $?= 0;  close(OUT) || &warn("Can't close DB::OUT");
  1090.             &warn( "Pager `$pager' failed: ",
  1091.               ($?>>8) > 128 ? ($?>>8)-256 : ($?>>8),
  1092.               ( $? & 128 ) ? " (core dumped)" : "",
  1093.               ( $? & 127 ) ? " (SIG ".($?&127).")" : "", "\n" ) if $?;
  1094.             open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
  1095.             open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
  1096.             $SIG{PIPE}= "DEFAULT" if $SIG{PIPE} eq \&DB::catch;
  1097.             # Will stop ignoring SIGPIPE if done like nohup(1)
  1098.             # does SIGINT but Perl doesn't give us a choice.
  1099.         } else {
  1100.             open(OUT,">&SAVEOUT") || &warn("Can't restore DB::OUT");
  1101.         }
  1102.         close(SAVEOUT);
  1103.         select($selected), $selected= "" unless $selected eq "";
  1104.         $piped= "";
  1105.         }
  1106.     }            # CMD:
  1107.     $exiting = 1 unless defined $cmd;
  1108.     foreach $evalarg (@$post) {
  1109.       &eval;
  1110.     }
  1111.     }                # if ($single || $signal)
  1112.     ($@, $!, $,, $/, $\, $^W) = @saved;
  1113.     ();
  1114. }
  1115.  
  1116. # The following code may be executed now:
  1117. # BEGIN {warn 4}
  1118.  
  1119. sub sub {
  1120.     my ($al, $ret, @ret) = "";
  1121.     if (length($sub) > 10 && substr($sub, -10, 10) eq '::AUTOLOAD') {
  1122.     $al = " for $$sub";
  1123.     }
  1124.     push(@stack, $single);
  1125.     $single &= 1;
  1126.     $single |= 4 if $#stack == $deep;
  1127.     ($frame & 4 
  1128.      ? ( (print $LINEINFO ' ' x ($#stack - 1), "in  "), 
  1129.      # Why -1? But it works! :-(
  1130.      print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1131.      : print $LINEINFO ' ' x ($#stack - 1), "entering $sub$al\n") if $frame;
  1132.     if (wantarray) {
  1133.     @ret = &$sub;
  1134.     $single |= pop(@stack);
  1135.     ($frame & 4 
  1136.      ? ( (print $LINEINFO ' ' x $#stack, "out "), 
  1137.          print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1138.      : print $LINEINFO ' ' x $#stack, "exited $sub$al\n") if $frame & 2;
  1139.     print ($OUT ($frame & 16 ? ' ' x $#stack : ""),
  1140.             "list context return from $sub:\n"), dumpit( \@ret ),
  1141.       $doret = -2 if $doret eq $#stack or $frame & 16;
  1142.     @ret;
  1143.     } else {
  1144.     $ret = &$sub;
  1145.     $single |= pop(@stack);
  1146.     ($frame & 4 
  1147.      ? ( (print $LINEINFO ' ' x $#stack, "out "), 
  1148.           print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1149.      : print $LINEINFO ' ' x $#stack, "exited $sub$al\n") if $frame & 2;
  1150.     print ($OUT ($frame & 16 ? ' ' x $#stack : ""),
  1151.             "scalar context return from $sub: "), dumpit( $ret ),
  1152.       $doret = -2 if $doret eq $#stack or $frame & 16;
  1153.     $ret;
  1154.     }
  1155. }
  1156.  
  1157. sub save {
  1158.     @saved = ($@, $!, $,, $/, $\, $^W);
  1159.     $, = ""; $/ = "\n"; $\ = ""; $^W = 0;
  1160. }
  1161.  
  1162. # The following takes its argument via $evalarg to preserve current @_
  1163.  
  1164. sub eval {
  1165.     my @res;
  1166.     {
  1167.     local (@stack) = @stack; # guard against recursive debugging
  1168.     my $otrace = $trace;
  1169.     my $osingle = $single;
  1170.     my $od = $^D;
  1171.     @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug
  1172.     $trace = $otrace;
  1173.     $single = $osingle;
  1174.     $^D = $od;
  1175.     }
  1176.     my $at = $@;
  1177.     local $saved[0];        # Preserve the old value of $@
  1178.     eval "&DB::save";
  1179.     if ($at) {
  1180.     print $OUT $at;
  1181.     } elsif ($onetimeDump eq 'dump') {
  1182.     dumpit(\@res);
  1183.     } elsif ($onetimeDump eq 'methods') {
  1184.     methods($res[0]);
  1185.     }
  1186. }
  1187.  
  1188. sub postponed_sub {
  1189.   my $subname = shift;
  1190.   if ($postponed{$subname} =~ s/^break\s([+-]?\d+)\s+if\s//) {
  1191.     my $offset = $1 || 0;
  1192.     # Filename below can contain ':'
  1193.     my ($file,$i) = (find_sub($subname) =~ /^(.*):(\d+)-.*$/);
  1194.     $i += $offset;
  1195.     if ($i) {
  1196.       local *dbline = $main::{'_<' . $file};
  1197.       local $^W = 0;        # != 0 is magical below
  1198.       $had_breakpoints{$file}++;
  1199.       my $max = $#dbline;
  1200.       ++$i until $dbline[$i] != 0 or $i >= $max;
  1201.       $dbline{$i} = delete $postponed{$subname};
  1202.     } else {
  1203.       print $OUT "Subroutine $subname not found.\n";
  1204.     }
  1205.     return;
  1206.   }
  1207.   elsif ($postponed{$subname} eq 'compile') { $signal = 1 }
  1208.   #print $OUT "In postponed_sub for `$subname'.\n";
  1209. }
  1210.  
  1211. sub postponed {
  1212.   return &postponed_sub
  1213.     unless ref \$_[0] eq 'GLOB'; # A subroutine is compiled.
  1214.   # Cannot be done before the file is compiled
  1215.   local *dbline = shift;
  1216.   my $filename = $dbline;
  1217.   $filename =~ s/^_<//;
  1218.   $signal = 1, print $OUT "'$filename' loaded...\n"
  1219.     if $break_on_load{$filename};
  1220.   print $LINEINFO ' ' x $#stack, "Package $filename.\n" if $frame;
  1221.   return unless $postponed_file{$filename};
  1222.   $had_breakpoints{$filename}++;
  1223.   #%dbline = %{$postponed_file{$filename}}; # Cannot be done: unsufficient magic
  1224.   my $key;
  1225.   for $key (keys %{$postponed_file{$filename}}) {
  1226.     $dbline{$key} = $ {$postponed_file{$filename}}{$key};
  1227.   }
  1228.   delete $postponed_file{$filename};
  1229. }
  1230.  
  1231. sub dumpit {
  1232.     local ($savout) = select($OUT);
  1233.     my $osingle = $single;
  1234.     my $otrace = $trace;
  1235.     $single = $trace = 0;
  1236.     local $frame = 0;
  1237.     local $doret = -2;
  1238.     unless (defined &main::dumpValue) {
  1239.     do 'dumpvar.pl';
  1240.     }
  1241.     if (defined &main::dumpValue) {
  1242.     &main::dumpValue(shift);
  1243.     } else {
  1244.     print $OUT "dumpvar.pl not available.\n";
  1245.     }
  1246.     $single = $osingle;
  1247.     $trace = $otrace;
  1248.     select ($savout);    
  1249. }
  1250.  
  1251. # Tied method do not create a context, so may get wrong message:
  1252.  
  1253. sub print_trace {
  1254.   my $fh = shift;
  1255.   my @sub = dump_trace($_[0] + 1, $_[1]);
  1256.   my $short = $_[2];        # Print short report, next one for sub name
  1257.   my $s;
  1258.   for ($i=0; $i <= $#sub; $i++) {
  1259.     last if $signal;
  1260.     local $" = ', ';
  1261.     my $args = defined $sub[$i]{args} 
  1262.     ? "(@{ $sub[$i]{args} })"
  1263.       : '' ;
  1264.     $args = (substr $args, 0, $maxtrace - 3) . '...' 
  1265.       if length $args > $maxtrace;
  1266.     my $file = $sub[$i]{file};
  1267.     $file = $file eq '-e' ? $file : "file `$file'" unless $short;
  1268.     $s = $sub[$i]{sub};
  1269.     $s = (substr $s, 0, $maxtrace - 3) . '...' if length $s > $maxtrace;    
  1270.     if ($short) {
  1271.       my $sub = @_ >= 4 ? $_[3] : $s;
  1272.       print $fh "$sub[$i]{context}=$sub$args from $file:$sub[$i]{line}\n";
  1273.     } else {
  1274.       print $fh "$sub[$i]{context} = $s$args" .
  1275.     " called from $file" . 
  1276.       " line $sub[$i]{line}\n";
  1277.     }
  1278.   }
  1279. }
  1280.  
  1281. sub dump_trace {
  1282.   my $skip = shift;
  1283.   my $count = shift || 1e9;
  1284.   $skip++;
  1285.   $count += $skip;
  1286.   my ($p,$file,$line,$sub,$h,$args,$e,$r,@a,@sub,$context);
  1287.   my $nothard = not $frame & 8;
  1288.   local $frame = 0;        # Do not want to trace this.
  1289.   my $otrace = $trace;
  1290.   $trace = 0;
  1291.   for ($i = $skip; 
  1292.        $i < $count and ($p,$file,$line,$sub,$h,$context,$e,$r) = caller($i); 
  1293.        $i++) {
  1294.     @a = ();
  1295.     for $arg (@args) {
  1296.       my $type;
  1297.       if (not defined $arg) {
  1298.     push @a, "undef";
  1299.       } elsif ($nothard and tied $arg) {
  1300.     push @a, "tied";
  1301.       } elsif ($nothard and $type = ref $arg) {
  1302.     push @a, "ref($type)";
  1303.       } else {
  1304.     local $_ = "$arg";    # Safe to stringify now - should not call f().
  1305.     s/([\'\\])/\\$1/g;
  1306.     s/(.*)/'$1'/s
  1307.       unless /^(?: -?[\d.]+ | \*[\w:]* )$/x;
  1308.     s/([\200-\377])/sprintf("M-%c",ord($1)&0177)/eg;
  1309.     s/([\0-\37\177])/sprintf("^%c",ord($1)^64)/eg;
  1310.     push(@a, $_);
  1311.       }
  1312.     }
  1313.     $context = $context ? '@' : "\$";
  1314.     $args = $h ? [@a] : undef;
  1315.     $e =~ s/\n\s*\;\s*\Z// if $e;
  1316.     $e =~ s/([\\\'])/\\$1/g if $e;
  1317.     if ($r) {
  1318.       $sub = "require '$e'";
  1319.     } elsif (defined $r) {
  1320.       $sub = "eval '$e'";
  1321.     } elsif ($sub eq '(eval)') {
  1322.       $sub = "eval {...}";
  1323.     }
  1324.     push(@sub, {context => $context, sub => $sub, args => $args,
  1325.         file => $file, line => $line});
  1326.     last if $signal;
  1327.   }
  1328.   $trace = $otrace;
  1329.   @sub;
  1330. }
  1331.  
  1332. sub action {
  1333.     my $action = shift;
  1334.     while ($action =~ s/\\$//) {
  1335.     #print $OUT "+ ";
  1336.     #$action .= "\n";
  1337.     $action .= &gets;
  1338.     }
  1339.     $action;
  1340. }
  1341.  
  1342. sub gets {
  1343.     local($.);
  1344.     #<IN>;
  1345.     &readline("cont: ");
  1346. }
  1347.  
  1348. sub system {
  1349.     # We save, change, then restore STDIN and STDOUT to avoid fork() since
  1350.     # many non-Unix systems can do system() but have problems with fork().
  1351.     open(SAVEIN,"<&STDIN") || &warn("Can't save STDIN");
  1352.     open(SAVEOUT,">&OUT") || &warn("Can't save STDOUT");
  1353.     open(STDIN,"<&IN") || &warn("Can't redirect STDIN");
  1354.     open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
  1355.     system(@_);
  1356.     open(STDIN,"<&SAVEIN") || &warn("Can't restore STDIN");
  1357.     open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
  1358.     close(SAVEIN); close(SAVEOUT);
  1359.     &warn( "(Command returned ", ($?>>8) > 128 ? ($?>>8)-256 : ($?>>8), ")",
  1360.       ( $? & 128 ) ? " (core dumped)" : "",
  1361.       ( $? & 127 ) ? " (SIG ".($?&127).")" : "", "\n" ) if $?;
  1362.     $?;
  1363. }
  1364.  
  1365. sub setterm {
  1366.     local $frame = 0;
  1367.     local $doret = -2;
  1368.     local @stack = @stack;        # Prevent growth by failing `use'.
  1369.     eval { require Term::ReadLine } or die $@;
  1370.     if ($notty) {
  1371.     if ($tty) {
  1372.         open(IN,"<$tty") or die "Cannot open TTY `$TTY' for read: $!";
  1373.         open(OUT,">$tty") or die "Cannot open TTY `$TTY' for write: $!";
  1374.         $IN = \*IN;
  1375.         $OUT = \*OUT;
  1376.         my $sel = select($OUT);
  1377.         $| = 1;
  1378.         select($sel);
  1379.     } else {
  1380.         eval "require Term::Rendezvous;" or die $@;
  1381.         my $rv = $ENV{PERLDB_NOTTY} || "/tmp/perldbtty$$";
  1382.         my $term_rv = new Term::Rendezvous $rv;
  1383.         $IN = $term_rv->IN;
  1384.         $OUT = $term_rv->OUT;
  1385.     }
  1386.     }
  1387.     if (!$rl) {
  1388.     $term = new Term::ReadLine::Stub 'perldb', $IN, $OUT;
  1389.     } else {
  1390.     $term = new Term::ReadLine 'perldb', $IN, $OUT;
  1391.  
  1392.     $rl_attribs = $term->Attribs;
  1393.     $rl_attribs->{basic_word_break_characters} .= '-:+/*,[])}' 
  1394.       if defined $rl_attribs->{basic_word_break_characters} 
  1395.         and index($rl_attribs->{basic_word_break_characters}, ":") == -1;
  1396.     $rl_attribs->{special_prefixes} = '$@&%';
  1397.     $rl_attribs->{completer_word_break_characters} .= '$@&%';
  1398.     $rl_attribs->{completion_function} = \&db_complete; 
  1399.     }
  1400.     $LINEINFO = $OUT unless defined $LINEINFO;
  1401.     $lineinfo = $console unless defined $lineinfo;
  1402.     $term->MinLine(2);
  1403.     if ($term->Features->{setHistory} and "@hist" ne "?") {
  1404.       $term->SetHistory(@hist);
  1405.     }
  1406.     ornaments($ornaments) if defined $ornaments;
  1407. }
  1408.  
  1409. sub readline {
  1410.   if (@typeahead) {
  1411.     my $left = @typeahead;
  1412.     my $got = shift @typeahead;
  1413.     print $OUT "auto(-$left)", shift, $got, "\n";
  1414.     $term->AddHistory($got) 
  1415.       if length($got) > 1 and defined $term->Features->{addHistory};
  1416.     return $got;
  1417.   }
  1418.   local $frame = 0;
  1419.   local $doret = -2;
  1420.   $term->readline(@_);
  1421. }
  1422.  
  1423. sub dump_option {
  1424.     my ($opt, $val)= @_;
  1425.     $val = option_val($opt,'N/A');
  1426.     $val =~ s/([\\\'])/\\$1/g;
  1427.     printf $OUT "%20s = '%s'\n", $opt, $val;
  1428. }
  1429.  
  1430. sub option_val {
  1431.     my ($opt, $default)= @_;
  1432.     my $val;
  1433.     if (defined $optionVars{$opt}
  1434.     and defined $ {$optionVars{$opt}}) {
  1435.     $val = $ {$optionVars{$opt}};
  1436.     } elsif (defined $optionAction{$opt}
  1437.     and defined &{$optionAction{$opt}}) {
  1438.     $val = &{$optionAction{$opt}}();
  1439.     } elsif (defined $optionAction{$opt}
  1440.          and not defined $option{$opt}
  1441.          or defined $optionVars{$opt}
  1442.          and not defined $ {$optionVars{$opt}}) {
  1443.     $val = $default;
  1444.     } else {
  1445.     $val = $option{$opt};
  1446.     }
  1447.     $val
  1448. }
  1449.  
  1450. sub parse_options {
  1451.     local($_)= @_;
  1452.     while ($_ ne "") {
  1453.     s/^(\w+)(\s*$|\W)// or print($OUT "Invalid option `$_'\n"), last;
  1454.     my ($opt,$sep) = ($1,$2);
  1455.     my $val;
  1456.     if ("?" eq $sep) {
  1457.         print($OUT "Option query `$opt?' followed by non-space `$_'\n"), last
  1458.           if /^\S/;
  1459.         #&dump_option($opt);
  1460.     } elsif ($sep !~ /\S/) {
  1461.         $val = "1";
  1462.     } elsif ($sep eq "=") {
  1463.         s/^(\S*)($|\s+)//;
  1464.         $val = $1;
  1465.     } else { #{ to "let some poor schmuck bounce on the % key in B<vi>."
  1466.         my ($end) = "\\" . substr( ")]>}$sep", index("([<{",$sep), 1 ); #}
  1467.         s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)// or
  1468.           print($OUT "Unclosed option value `$opt$sep$_'\n"), last;
  1469.         $val = $1;
  1470.         $val =~ s/\\([\\$end])/$1/g;
  1471.     }
  1472.     my ($option);
  1473.     my $matches =
  1474.       grep(  /^\Q$opt/ && ($option = $_),  @options  );
  1475.     $matches =  grep(  /^\Q$opt/i && ($option = $_),  @options  )
  1476.       unless $matches;
  1477.     print $OUT "Unknown option `$opt'\n" unless $matches;
  1478.     print $OUT "Ambiguous option `$opt'\n" if $matches > 1;
  1479.     $option{$option} = $val if $matches == 1 and defined $val;
  1480.     eval "local \$frame = 0; local \$doret = -2; 
  1481.           require '$optionRequire{$option}'"
  1482.       if $matches == 1 and defined $optionRequire{$option} and defined $val;
  1483.     $ {$optionVars{$option}} = $val 
  1484.       if $matches == 1
  1485.         and defined $optionVars{$option} and defined $val;
  1486.     & {$optionAction{$option}} ($val) 
  1487.       if $matches == 1
  1488.         and defined $optionAction{$option}
  1489.           and defined &{$optionAction{$option}} and defined $val;
  1490.     &dump_option($option) if $matches == 1 && $OUT ne \*STDERR; # Not $rcfile
  1491.         s/^\s+//;
  1492.     }
  1493. }
  1494.  
  1495. sub set_list {
  1496.   my ($stem,@list) = @_;
  1497.   my $val;
  1498.   $ENV{"$ {stem}_n"} = @list;
  1499.   for $i (0 .. $#list) {
  1500.     $val = $list[$i];
  1501.     $val =~ s/\\/\\\\/g;
  1502.     $val =~ s/([\0-\37\177\200-\377])/"\\0x" . unpack('H2',$1)/eg;
  1503.     $ENV{"$ {stem}_$i"} = $val;
  1504.   }
  1505. }
  1506.  
  1507. sub get_list {
  1508.   my $stem = shift;
  1509.   my @list;
  1510.   my $n = delete $ENV{"$ {stem}_n"};
  1511.   my $val;
  1512.   for $i (0 .. $n - 1) {
  1513.     $val = delete $ENV{"$ {stem}_$i"};
  1514.     $val =~ s/\\((\\)|0x(..))/ $2 ? $2 : pack('H2', $3) /ge;
  1515.     push @list, $val;
  1516.   }
  1517.   @list;
  1518. }
  1519.  
  1520. sub catch {
  1521.     $signal = 1;
  1522.     return;            # Put nothing on the stack - malloc/free land!
  1523. }
  1524.  
  1525. sub warn {
  1526.     my($msg)= join("",@_);
  1527.     $msg .= ": $!\n" unless $msg =~ /\n$/;
  1528.     print $OUT $msg;
  1529. }
  1530.  
  1531. sub TTY {
  1532.     if ($term) {
  1533.     &warn("Too late to set TTY, enabled on next `R'!\n") if @_;
  1534.     } 
  1535.     $tty = shift if @_;
  1536.     $tty or $console;
  1537. }
  1538.  
  1539. sub noTTY {
  1540.     if ($term) {
  1541.     &warn("Too late to set noTTY, enabled on next `R'!\n") if @_;
  1542.     }
  1543.     $notty = shift if @_;
  1544.     $notty;
  1545. }
  1546.  
  1547. sub ReadLine {
  1548.     if ($term) {
  1549.     &warn("Too late to set ReadLine, enabled on next `R'!\n") if @_;
  1550.     }
  1551.     $rl = shift if @_;
  1552.     $rl;
  1553. }
  1554.  
  1555. sub tkRunning {
  1556.     if ($ {$term->Features}{tkRunning}) {
  1557.         return $term->tkRunning(@_);
  1558.     } else {
  1559.     print $OUT "tkRunning not supported by current ReadLine package.\n";
  1560.     0;
  1561.     }
  1562. }
  1563.  
  1564. sub NonStop {
  1565.     if ($term) {
  1566.     &warn("Too late to set up NonStop mode, enabled on next `R'!\n") if @_;
  1567.     }
  1568.     $runnonstop = shift if @_;
  1569.     $runnonstop;
  1570. }
  1571.  
  1572. sub pager {
  1573.     if (@_) {
  1574.     $pager = shift;
  1575.     $pager="|".$pager unless $pager =~ /^(\+?\>|\|)/;
  1576.     }
  1577.     $pager;
  1578. }
  1579.  
  1580. sub shellBang {
  1581.     if (@_) {
  1582.     $sh = quotemeta shift;
  1583.     $sh .= "\\b" if $sh =~ /\w$/;
  1584.     }
  1585.     $psh = $sh;
  1586.     $psh =~ s/\\b$//;
  1587.     $psh =~ s/\\(.)/$1/g;
  1588.     &sethelp;
  1589.     $psh;
  1590. }
  1591.  
  1592. sub ornaments {
  1593.   if (defined $term) {
  1594.     local ($warnLevel,$dieLevel) = (0, 1);
  1595.     return '' unless $term->Features->{ornaments};
  1596.     eval { $term->ornaments(@_) } || '';
  1597.   } else {
  1598.     $ornaments = shift;
  1599.   }
  1600. }
  1601.  
  1602. sub recallCommand {
  1603.     if (@_) {
  1604.     $rc = quotemeta shift;
  1605.     $rc .= "\\b" if $rc =~ /\w$/;
  1606.     }
  1607.     $prc = $rc;
  1608.     $prc =~ s/\\b$//;
  1609.     $prc =~ s/\\(.)/$1/g;
  1610.     &sethelp;
  1611.     $prc;
  1612. }
  1613.  
  1614. sub LineInfo {
  1615.     return $lineinfo unless @_;
  1616.     $lineinfo = shift;
  1617.     my $stream = ($lineinfo =~ /^(\+?\>|\|)/) ? $lineinfo : ">$lineinfo";
  1618.     $emacs = ($stream =~ /^\|/);
  1619.     open(LINEINFO, "$stream") || &warn("Cannot open `$stream' for write");
  1620.     $LINEINFO = \*LINEINFO;
  1621.     my $save = select($LINEINFO);
  1622.     $| = 1;
  1623.     select($save);
  1624.     $lineinfo;
  1625. }
  1626.  
  1627. sub list_versions {
  1628.   my %version;
  1629.   my $file;
  1630.   for (keys %INC) {
  1631.     $file = $_;
  1632.     s,\.p[lm]$,,i ;
  1633.     s,/,::,g ;
  1634.     s/^perl5db$/DB/;
  1635.     s/^Term::ReadLine::readline$/readline/;
  1636.     if (defined $ { $_ . '::VERSION' }) {
  1637.       $version{$file} = "$ { $_ . '::VERSION' } from ";
  1638.     } 
  1639.     $version{$file} .= $INC{$file};
  1640.   }
  1641.   do 'dumpvar.pl' unless defined &main::dumpValue;
  1642.   if (defined &main::dumpValue) {
  1643.     local $frame = 0;
  1644.     &main::dumpValue(\%version);
  1645.   } else {
  1646.     print $OUT "dumpvar.pl not available.\n";
  1647.   }
  1648. }
  1649.  
  1650. sub sethelp {
  1651.     $help = "
  1652. T        Stack trace.
  1653. s [expr]    Single step [in expr].
  1654. n [expr]    Next, steps over subroutine calls [in expr].
  1655. <CR>        Repeat last n or s command.
  1656. r        Return from current subroutine.
  1657. c [line|sub]    Continue; optionally inserts a one-time-only breakpoint
  1658.         at the specified position.
  1659. l min+incr    List incr+1 lines starting at min.
  1660. l min-max    List lines min through max.
  1661. l line        List single line.
  1662. l subname    List first window of lines from subroutine.
  1663. l        List next window of lines.
  1664. -        List previous window of lines.
  1665. w [line]    List window around line.
  1666. .        Return to the executed line.
  1667. f filename    Switch to viewing filename. Must be loaded.
  1668. /pattern/    Search forwards for pattern; final / is optional.
  1669. ?pattern?    Search backwards for pattern; final ? is optional.
  1670. L        List all breakpoints and actions.
  1671. S [[!]pattern]    List subroutine names [not] matching pattern.
  1672. t        Toggle trace mode.
  1673. t expr        Trace through execution of expr.
  1674. b [line] [condition]
  1675.         Set breakpoint; line defaults to the current execution line;
  1676.         condition breaks if it evaluates to true, defaults to '1'.
  1677. b subname [condition]
  1678.         Set breakpoint at first line of subroutine.
  1679. b load filename Set breakpoint on `require'ing the given file.
  1680. b postpone subname [condition]
  1681.         Set breakpoint at first line of subroutine after 
  1682.         it is compiled.
  1683. b compile subname
  1684.         Stop after the subroutine is compiled.
  1685. d [line]    Delete the breakpoint for line.
  1686. D        Delete all breakpoints.
  1687. a [line] command
  1688.         Set an action to be done before the line is executed.
  1689.         Sequence is: check for breakpoint, print line if necessary,
  1690.         do action, prompt user if breakpoint or step, evaluate line.
  1691. A        Delete all actions.
  1692. V [pkg [vars]]    List some (default all) variables in package (default current).
  1693.         Use ~pattern and !pattern for positive and negative regexps.
  1694. X [vars]    Same as \"V currentpackage [vars]\".
  1695. x expr        Evals expression in array context, dumps the result.
  1696. m expr        Evals expression in array context, prints methods callable
  1697.         on the first element of the result.
  1698. m class        Prints methods callable via the given class.
  1699. O [opt[=val]] [opt\"val\"] [opt?]...
  1700.         Set or query values of options.  val defaults to 1.  opt can
  1701.         be abbreviated.  Several options can be listed.
  1702.     recallCommand, ShellBang:    chars used to recall command or spawn shell;
  1703.     pager:            program for output of \"|cmd\";
  1704.     tkRunning:            run Tk while prompting (with ReadLine);
  1705.     signalLevel warnLevel dieLevel:    level of verbosity;
  1706.     inhibit_exit        Allows stepping off the end of the script.
  1707.   The following options affect what happens with V, X, and x commands:
  1708.     arrayDepth, hashDepth:    print only first N elements ('' for all);
  1709.     compactDump, veryCompact:    change style of array and hash dump;
  1710.     globPrint:            whether to print contents of globs;
  1711.     DumpDBFiles:        dump arrays holding debugged files;
  1712.     DumpPackages:        dump symbol tables of packages;
  1713.     quote, HighBit, undefPrint:    change style of string dump;
  1714.   Option PrintRet affects printing of return value after r command,
  1715.          frame    affects printing messages on entry and exit from subroutines.
  1716.          AutoTrace affects printing messages on every possible breaking point.
  1717.      maxTraceLen gives maximal length of evals/args listed in stack trace.
  1718.      ornaments affects screen appearance of the command line.
  1719.         During startup options are initialized from \$ENV{PERLDB_OPTS}.
  1720.         You can put additional initialization options TTY, noTTY,
  1721.         ReadLine, and NonStop there (or use `R' after you set them).
  1722. < command    Define Perl command to run before each prompt.
  1723. << command    Add to the list of Perl commands to run before each prompt.
  1724. > command    Define Perl command to run after each prompt.
  1725. >> command    Add to the list of Perl commands to run after each prompt.
  1726. \{ commandline    Define debugger command to run before each prompt.
  1727. \{{ commandline    Add to the list of debugger commands to run before each prompt.
  1728. $prc number    Redo a previous command (default previous command).
  1729. $prc -number    Redo number'th-to-last command.
  1730. $prc pattern    Redo last command that started with pattern.
  1731.         See 'O recallCommand' too.
  1732. $psh$psh cmd      Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
  1733.   . ( $rc eq $sh ? "" : "
  1734. $psh [cmd]     Run cmd in subshell (forces \"\$SHELL -c 'cmd'\")." ) . "
  1735.         See 'O shellBang' too.
  1736. H -number    Display last number commands (default all).
  1737. p expr        Same as \"print {DB::OUT} expr\" in current package.
  1738. |dbcmd        Run debugger command, piping DB::OUT to current pager.
  1739. ||dbcmd        Same as |dbcmd but DB::OUT is temporarilly select()ed as well.
  1740. \= [alias value]    Define a command alias, or list current aliases.
  1741. command        Execute as a perl statement in current package.
  1742. v        Show versions of loaded modules.
  1743. R        Pure-man-restart of debugger, some of debugger state
  1744.         and command-line options may be lost.
  1745.         Currently the following setting are preserved: 
  1746.         history, breakpoints and actions, debugger Options 
  1747.         and the following command-line options: -w, -I, -e.
  1748. h [db_command]    Get help [on a specific debugger command], enter |h to page.
  1749. h h        Summary of debugger commands.
  1750. q or ^D        Quit. Set \$DB::finished to 0 to debug global destruction.
  1751.  
  1752. ";
  1753.     $summary = <<"END_SUM";
  1754. List/search source lines:               Control script execution:
  1755.   l [ln|sub]  List source code            T           Stack trace
  1756.   - or .      List previous/current line  s [expr]    Single step [in expr]
  1757.   w [line]    List around line            n [expr]    Next, steps over subs
  1758.   f filename  View source in file         <CR>        Repeat last n or s
  1759.   /pattern/ ?patt?   Search forw/backw    r           Return from subroutine
  1760.   v          Show versions of modules    c [ln|sub]  Continue until position
  1761. Debugger controls:                        L           List break pts & actions
  1762.   O [...]     Set debugger options        t [expr]    Toggle trace [trace expr]
  1763.   <[<] or {[{] [cmd]   Do before prompt   b [ln/event] [c]     Set breakpoint
  1764.   >[>] [cmd]  Do after prompt             b sub [c]   Set breakpoint for sub
  1765.   $prc [N|pat]   Redo a previous command     d [line]    Delete a breakpoint
  1766.   H [-num]    Display last num commands   D           Delete all breakpoints
  1767.   = [a val]   Define/list an alias        a [ln] cmd  Do cmd before line
  1768.   h [db_cmd]  Get help on command         A           Delete all actions
  1769.   |[|]dbcmd   Send output to pager        $psh\[$psh\] syscmd Run cmd in a subprocess
  1770.   q or ^D     Quit              R          Attempt a restart
  1771. Data Examination:          expr     Execute perl code, also see: s,n,t expr
  1772.   x|m expr    Evals expr in array context, dumps the result or lists methods.
  1773.   p expr    Print expression (uses script's current package).
  1774.   S [[!]pat]    List subroutine names [not] matching pattern
  1775.   V [Pk [Vars]]    List Variables in Package.  Vars can be ~pattern or !pattern.
  1776.   X [Vars]    Same as \"V current_package [Vars]\".
  1777. END_SUM
  1778.                 # ')}}; # Fix balance of Emacs parsing
  1779. }
  1780.  
  1781. sub diesignal {
  1782.     local $frame = 0;
  1783.     local $doret = -2;
  1784.     $SIG{'ABRT'} = 'DEFAULT';
  1785.     kill 'ABRT', $$ if $panic++;
  1786.     if (defined &Carp::longmess) {
  1787.     local $SIG{__WARN__} = '';
  1788.     local $Carp::CarpLevel = 2;        # mydie + confess
  1789.     &warn(Carp::longmess("Signal @_"));
  1790.     }
  1791.     else {
  1792.     print $DB::OUT "Got signal @_\n";
  1793.     }
  1794.     kill 'ABRT', $$;
  1795. }
  1796.  
  1797. sub dbwarn { 
  1798.   local $frame = 0;
  1799.   local $doret = -2;
  1800.   local $SIG{__WARN__} = '';
  1801.   local $SIG{__DIE__} = '';
  1802.   eval { require Carp };    # If error/warning during compilation,
  1803.                                 # require may be broken.
  1804.   warn(@_, "\nPossible unrecoverable error"), warn("\nTry to decrease warnLevel `O'ption!\n"), return
  1805.     unless defined &Carp::longmess;
  1806.   #&warn("Entering dbwarn\n");
  1807.   my ($mysingle,$mytrace) = ($single,$trace);
  1808.   $single = 0; $trace = 0;
  1809.   my $mess = Carp::longmess(@_);
  1810.   ($single,$trace) = ($mysingle,$mytrace);
  1811.   #&warn("Warning in dbwarn\n");
  1812.   &warn($mess); 
  1813.   #&warn("Exiting dbwarn\n");
  1814. }
  1815.  
  1816. sub dbdie {
  1817.   local $frame = 0;
  1818.   local $doret = -2;
  1819.   local $SIG{__DIE__} = '';
  1820.   local $SIG{__WARN__} = '';
  1821.   my $i = 0; my $ineval = 0; my $sub;
  1822.   #&warn("Entering dbdie\n");
  1823.   if ($dieLevel != 2) {
  1824.     while ((undef,undef,undef,$sub) = caller(++$i)) {
  1825.       $ineval = 1, last if $sub eq '(eval)';
  1826.     }
  1827.     {
  1828.       local $SIG{__WARN__} = \&dbwarn;
  1829.       &warn(@_) if $dieLevel > 2; # Ineval is false during destruction?
  1830.     }
  1831.     #&warn("dieing quietly in dbdie\n") if $ineval and $dieLevel < 2;
  1832.     die @_ if $ineval and $dieLevel < 2;
  1833.   }
  1834.   eval { require Carp };    # If error/warning during compilation,
  1835.                                 # require may be broken.
  1836.   die(@_, "\nUnrecoverable error") unless defined &Carp::longmess;
  1837.   # We do not want to debug this chunk (automatic disabling works
  1838.   # inside DB::DB, but not in Carp).
  1839.   my ($mysingle,$mytrace) = ($single,$trace);
  1840.   $single = 0; $trace = 0;
  1841.   my $mess = Carp::longmess(@_);
  1842.   ($single,$trace) = ($mysingle,$mytrace);
  1843.   #&warn("dieing loudly in dbdie\n");
  1844.   die $mess;
  1845. }
  1846.  
  1847. sub warnLevel {
  1848.   if (@_) {
  1849.     $prevwarn = $SIG{__WARN__} unless $warnLevel;
  1850.     $warnLevel = shift;
  1851.     if ($warnLevel) {
  1852.       $SIG{__WARN__} = \&DB::dbwarn;
  1853.     } else {
  1854.       $SIG{__WARN__} = $prevwarn;
  1855.     }
  1856.   }
  1857.   $warnLevel;
  1858. }
  1859.  
  1860. sub dieLevel {
  1861.   if (@_) {
  1862.     $prevdie = $SIG{__DIE__} unless $dieLevel;
  1863.     $dieLevel = shift;
  1864.     if ($dieLevel) {
  1865.       $SIG{__DIE__} = \&DB::dbdie; # if $dieLevel < 2;
  1866.       #$SIG{__DIE__} = \&DB::diehard if $dieLevel >= 2;
  1867.       print $OUT "Stack dump during die enabled", 
  1868.         ( $dieLevel == 1 ? " outside of evals" : ""), ".\n"
  1869.       if $I_m_init;
  1870.       print $OUT "Dump printed too.\n" if $dieLevel > 2;
  1871.     } else {
  1872.       $SIG{__DIE__} = $prevdie;
  1873.       print $OUT "Default die handler restored.\n";
  1874.     }
  1875.   }
  1876.   $dieLevel;
  1877. }
  1878.  
  1879. sub signalLevel {
  1880.   if (@_) {
  1881.     $prevsegv = $SIG{SEGV} unless $signalLevel;
  1882.     $prevbus = $SIG{BUS} unless $signalLevel;
  1883.     $signalLevel = shift;
  1884.     if ($signalLevel) {
  1885.       $SIG{SEGV} = \&DB::diesignal;
  1886.       $SIG{BUS} = \&DB::diesignal;
  1887.     } else {
  1888.       $SIG{SEGV} = $prevsegv;
  1889.       $SIG{BUS} = $prevbus;
  1890.     }
  1891.   }
  1892.   $signalLevel;
  1893. }
  1894.  
  1895. sub find_sub {
  1896.   my $subr = shift;
  1897.   return unless defined &$subr;
  1898.   $sub{$subr} or do {
  1899.     $subr = \&$subr;        # Hard reference
  1900.     my $s;
  1901.     for (keys %sub) {
  1902.       $s = $_, last if $subr eq \&$_;
  1903.     }
  1904.     $sub{$s} if $s;
  1905.   }
  1906. }
  1907.  
  1908. sub methods {
  1909.   my $class = shift;
  1910.   $class = ref $class if ref $class;
  1911.   local %seen;
  1912.   local %packs;
  1913.   methods_via($class, '', 1);
  1914.   methods_via('UNIVERSAL', 'UNIVERSAL', 0);
  1915. }
  1916.  
  1917. sub methods_via {
  1918.   my $class = shift;
  1919.   return if $packs{$class}++;
  1920.   my $prefix = shift;
  1921.   my $prepend = $prefix ? "via $prefix: " : '';
  1922.   my $name;
  1923.   for $name (grep {defined &{$ {"$ {class}::"}{$_}}} 
  1924.          sort keys %{"$ {class}::"}) {
  1925.     next if $seen{ $name }++;
  1926.     print $DB::OUT "$prepend$name\n";
  1927.   }
  1928.   return unless shift;        # Recurse?
  1929.   for $name (@{"$ {class}::ISA"}) {
  1930.     $prepend = $prefix ? $prefix . " -> $name" : $name;
  1931.     methods_via($name, $prepend, 1);
  1932.   }
  1933. }
  1934.  
  1935. # The following BEGIN is very handy if debugger goes havoc, debugging debugger?
  1936.  
  1937. BEGIN {            # This does not compile, alas.
  1938.   $IN = \*STDIN;        # For bugs before DB::OUT has been opened
  1939.   $OUT = \*STDERR;        # For errors before DB::OUT has been opened
  1940.   $sh = '!';
  1941.   $rc = ',';
  1942.   @hist = ('?');
  1943.   $deep = 100;            # warning if stack gets this deep
  1944.   $window = 10;
  1945.   $preview = 3;
  1946.   $sub = '';
  1947.   $SIG{INT} = \&DB::catch;
  1948.   # This may be enabled to debug debugger:
  1949.   #$warnLevel = 1 unless defined $warnLevel;
  1950.   #$dieLevel = 1 unless defined $dieLevel;
  1951.   #$signalLevel = 1 unless defined $signalLevel;
  1952.  
  1953.   $db_stop = 0;            # Compiler warning
  1954.   $db_stop = 1 << 30;
  1955.   $level = 0;            # Level of recursive debugging
  1956.   # @stack and $doret are needed in sub sub, which is called for DB::postponed.
  1957.   # Triggers bug (?) in perl is we postpone this until runtime:
  1958.   @postponed = @stack = (0);
  1959.   $doret = -2;
  1960.   $frame = 0;
  1961. }
  1962.  
  1963. BEGIN {$^W = $ini_warn;}    # Switch warnings back
  1964.  
  1965. #use Carp;            # This did break, left for debuggin
  1966.  
  1967. sub db_complete {
  1968.   # Specific code for b c l V m f O, &blah, $blah, @blah, %blah
  1969.   my($text, $line, $start) = @_;
  1970.   my ($itext, $search, $prefix, $pack) =
  1971.     ($text, "^\Q$ {'package'}::\E([^:]+)\$");
  1972.   
  1973.   return sort grep /^\Q$text/, (keys %sub), qw(postpone load compile), # subroutines
  1974.                                (map { /$search/ ? ($1) : () } keys %sub)
  1975.     if (substr $line, 0, $start) =~ /^\|*[blc]\s+((postpone|compile)\s+)?$/;
  1976.   return sort grep /^\Q$text/, values %INC # files
  1977.     if (substr $line, 0, $start) =~ /^\|*b\s+load\s+$/;
  1978.   return sort map {($_, db_complete($_ . "::", "V ", 2))}
  1979.     grep /^\Q$text/, map { /^(.*)::$/ ? ($1) : ()} keys %:: # top-packages
  1980.       if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/ and $text =~ /^\w*$/;
  1981.   return sort map {($_, db_complete($_ . "::", "V ", 2))}
  1982.     grep !/^main::/,
  1983.       grep /^\Q$text/, map { /^(.*)::$/ ? ($prefix . "::$1") : ()} keys %{$prefix . '::'}
  1984.                  # packages
  1985.     if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/ 
  1986.       and $text =~ /^(.*[^:])::?(\w*)$/  and $prefix = $1;
  1987.   if ( $line =~ /^\|*f\s+(.*)/ ) { # Loaded files
  1988.     # We may want to complete to (eval 9), so $text may be wrong
  1989.     $prefix = length($1) - length($text);
  1990.     $text = $1;
  1991.     return sort 
  1992.     map {substr $_, 2 + $prefix} grep /^_<\Q$text/, (keys %main::), $0
  1993.   }
  1994.   if ((substr $text, 0, 1) eq '&') { # subroutines
  1995.     $text = substr $text, 1;
  1996.     $prefix = "&";
  1997.     return sort map "$prefix$_", 
  1998.                grep /^\Q$text/, 
  1999.                  (keys %sub),
  2000.                  (map { /$search/ ? ($1) : () } 
  2001.             keys %sub);
  2002.   }
  2003.   if ($text =~ /^[\$@%](.*)::(.*)/) { # symbols in a package
  2004.     $pack = ($1 eq 'main' ? '' : $1) . '::';
  2005.     $prefix = (substr $text, 0, 1) . $1 . '::';
  2006.     $text = $2;
  2007.     my @out 
  2008.       = map "$prefix$_", grep /^\Q$text/, grep /^_?[a-zA-Z]/, keys %$pack ;
  2009.     if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
  2010.       return db_complete($out[0], $line, $start);
  2011.     }
  2012.     return sort @out;
  2013.   }
  2014.   if ($text =~ /^[\$@%]/) { # symbols (in $package + packages in main)
  2015.     $pack = ($package eq 'main' ? '' : $package) . '::';
  2016.     $prefix = substr $text, 0, 1;
  2017.     $text = substr $text, 1;
  2018.     my @out = map "$prefix$_", grep /^\Q$text/, 
  2019.        (grep /^_?[a-zA-Z]/, keys %$pack), 
  2020.        ( $pack eq '::' ? () : (grep /::$/, keys %::) ) ;
  2021.     if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
  2022.       return db_complete($out[0], $line, $start);
  2023.     }
  2024.     return sort @out;
  2025.   }
  2026.   if ((substr $line, 0, $start) =~ /^\|*O\b.*\s$/) { # Options after a space
  2027.     my @out = grep /^\Q$text/, @options;
  2028.     my $val = option_val($out[0], undef);
  2029.     my $out = '? ';
  2030.     if (not defined $val or $val =~ /[\n\r]/) {
  2031.       # Can do nothing better
  2032.     } elsif ($val =~ /\s/) {
  2033.       my $found;
  2034.       foreach $l (split //, qq/\"\'\#\|/) {
  2035.     $out = "$l$val$l ", last if (index $val, $l) == -1;
  2036.       }
  2037.     } else {
  2038.       $out = "=$val ";
  2039.     }
  2040.     # Default to value if one completion, to question if many
  2041.     $rl_attribs->{completer_terminator_character} = (@out == 1 ? $out : '? ');
  2042.     return sort @out;
  2043.   }
  2044.   return $term->filename_list($text); # filenames
  2045. }
  2046.  
  2047. sub end_report {
  2048.   print $OUT "Use `q' to quit or `R' to restart.  `h q' for details.\n"
  2049. }
  2050.  
  2051. END {
  2052.   $finished = $inhibit_exit;    # So that some keys may be disabled.
  2053.   # Do not stop in at_exit() and destructors on exit:
  2054.   $DB::single = !$exiting && !$runnonstop;
  2055.   DB::fake::at_exit() unless $exiting or $runnonstop;
  2056. }
  2057.  
  2058. package DB::fake;
  2059.  
  2060. sub at_exit {
  2061.   "Debugged program terminated.  Use `q' to quit or `R' to restart.";
  2062. }
  2063.  
  2064. package DB;            # Do not trace this 1; below!
  2065.  
  2066. 1;
  2067.