home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl560.zip / lib / perl5db.pl < prev    next >
Perl Script  |  2000-03-18  |  85KB  |  2,698 lines

  1. package DB;
  2.  
  3. # Debugger for Perl 5.00x; perl5db.pl patch level:
  4.  
  5. $VERSION = 1.07;
  6. $header = "perl5db.pl version $VERSION";
  7.  
  8. #
  9. # This file is automatically included if you do perl -d.
  10. # It's probably not useful to include this yourself.
  11. #
  12. # Perl supplies the values for %sub.  It effectively inserts
  13. # a &DB'DB(); in front of every place that can have a
  14. # breakpoint. Instead of a subroutine call it calls &DB::sub with
  15. # $DB::sub being the called subroutine. It also inserts a BEGIN
  16. # {require 'perl5db.pl'} before the first line.
  17. #
  18. # After each `require'd file is compiled, but before it is executed, a
  19. # call to DB::postponed($main::{'_<'.$filename}) is emulated. Here the
  20. # $filename is the expanded name of the `require'd file (as found as
  21. # value of %INC).
  22. #
  23. # Additional services from Perl interpreter:
  24. #
  25. # if caller() is called from the package DB, it provides some
  26. # additional data.
  27. #
  28. # The array @{$main::{'_<'.$filename} is the line-by-line contents of
  29. # $filename.
  30. #
  31. # The hash %{'_<'.$filename} contains breakpoints and action (it is
  32. # keyed by line number), and individual entries are settable (as
  33. # opposed to the whole hash). Only true/false is important to the
  34. # interpreter, though the values used by perl5db.pl have the form
  35. # "$break_condition\0$action". Values are magical in numeric context.
  36. #
  37. # The scalar ${'_<'.$filename} contains "_<$filename".
  38. #
  39. # Note that no subroutine call is possible until &DB::sub is defined
  40. # (for subroutines defined outside of the package DB). In fact the same is
  41. # true if $deep is not defined.
  42. #
  43. # $Log:    perldb.pl,v $
  44.  
  45. #
  46. # At start reads $rcfile that may set important options.  This file
  47. # may define a subroutine &afterinit that will be executed after the
  48. # debugger is initialized.
  49. #
  50. # After $rcfile is read reads environment variable PERLDB_OPTS and parses
  51. # it as a rest of `O ...' line in debugger prompt.
  52. #
  53. # The options that can be specified only at startup:
  54. # [To set in $rcfile, call &parse_options("optionName=new_value").]
  55. #
  56. # TTY  - the TTY to use for debugging i/o.
  57. #
  58. # noTTY - if set, goes in NonStop mode.  On interrupt if TTY is not set
  59. # uses the value of noTTY or "/tmp/perldbtty$$" to find TTY using
  60. # Term::Rendezvous.  Current variant is to have the name of TTY in this
  61. # file.
  62. #
  63. # ReadLine - If false, dummy ReadLine is used, so you can debug
  64. # ReadLine applications.
  65. #
  66. # NonStop - if true, no i/o is performed until interrupt.
  67. #
  68. # LineInfo - file or pipe to print line number info to.  If it is a
  69. # pipe, a short "emacs like" message is used.
  70. #
  71. # RemotePort - host:port to connect to on remote host for remote debugging.
  72. #
  73. # Example $rcfile: (delete leading hashes!)
  74. #
  75. # &parse_options("NonStop=1 LineInfo=db.out");
  76. # sub afterinit { $trace = 1; }
  77. #
  78. # The script will run without human intervention, putting trace
  79. # information into db.out.  (If you interrupt it, you would better
  80. # reset LineInfo to something "interactive"!)
  81. #
  82. ##################################################################
  83.  
  84. # Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich)
  85. # Latest version available: ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
  86.  
  87. # modified Perl debugger, to be run from Emacs in perldb-mode
  88. # Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990
  89. # Johan Vromans -- upgrade to 4.0 pl 10
  90. # Ilya Zakharevich -- patches after 5.001 (and some before ;-)
  91.  
  92. # Changelog:
  93.  
  94. # A lot of things changed after 0.94. First of all, core now informs
  95. # debugger about entry into XSUBs, overloaded operators, tied operations,
  96. # BEGIN and END. Handy with `O f=2'.
  97.  
  98. # This can make debugger a little bit too verbose, please be patient
  99. # and report your problems promptly.
  100.  
  101. # Now the option frame has 3 values: 0,1,2.
  102.  
  103. # Note that if DESTROY returns a reference to the object (or object),
  104. # the deletion of data may be postponed until the next function call,
  105. # due to the need to examine the return value.
  106.  
  107. # Changes: 0.95: `v' command shows versions.
  108. # Changes: 0.96: `v' command shows version of readline.
  109. #    primitive completion works (dynamic variables, subs for `b' and `l',
  110. #        options). Can `p %var'
  111. #    Better help (`h <' now works). New commands <<, >>, {, {{.
  112. #    {dump|print}_trace() coded (to be able to do it from <<cmd).
  113. #    `c sub' documented.
  114. #    At last enough magic combined to stop after the end of debuggee.
  115. #    !! should work now (thanks to Emacs bracket matching an extra
  116. #    `]' in a regexp is caught).
  117. #    `L', `D' and `A' span files now (as documented).
  118. #    Breakpoints in `require'd code are possible (used in `R').
  119. #    Some additional words on internal work of debugger.
  120. #    `b load filename' implemented.
  121. #    `b postpone subr' implemented.
  122. #    now only `q' exits debugger (overwriteable on $inhibit_exit).
  123. #    When restarting debugger breakpoints/actions persist.
  124. #     Buglet: When restarting debugger only one breakpoint/action per 
  125. #        autoloaded function persists.
  126. # Changes: 0.97: NonStop will not stop in at_exit().
  127. #    Option AutoTrace implemented.
  128. #    Trace printed differently if frames are printed too.
  129. #    new `inhibitExit' option.
  130. #    printing of a very long statement interruptible.
  131. # Changes: 0.98: New command `m' for printing possible methods
  132. #    'l -' is a synonim for `-'.
  133. #    Cosmetic bugs in printing stack trace.
  134. #    `frame' & 8 to print "expanded args" in stack trace.
  135. #    Can list/break in imported subs.
  136. #    new `maxTraceLen' option.
  137. #    frame & 4 and frame & 8 granted.
  138. #    new command `m'
  139. #    nonstoppable lines do not have `:' near the line number.
  140. #    `b compile subname' implemented.
  141. #    Will not use $` any more.
  142. #    `-' behaves sane now.
  143. # Changes: 0.99: Completion for `f', `m'.
  144. #    `m' will remove duplicate names instead of duplicate functions.
  145. #    `b load' strips trailing whitespace.
  146. #    completion ignores leading `|'; takes into account current package
  147. #    when completing a subroutine name (same for `l').
  148. # Changes: 1.07: Many fixed by tchrist 13-March-2000
  149. #   BUG FIXES:
  150. #   + Added bare mimimal security checks on perldb rc files, plus
  151. #     comments on what else is needed.
  152. #   + Fixed the ornaments that made "|h" completely unusable.
  153. #     They are not used in print_help if they will hurt.  Strip pod
  154. #     if we're paging to less.
  155. #   + Fixed mis-formatting of help messages caused by ornaments
  156. #     to restore Larry's original formatting.  
  157. #   + Fixed many other formatting errors.  The code is still suboptimal, 
  158. #     and needs a lot of work at restructuing. It's also misindented
  159. #     in many places.
  160. #   + Fixed bug where trying to look at an option like your pager
  161. #     shows "1".  
  162. #   + Fixed some $? processing.  Note: if you use csh or tcsh, you will
  163. #     lose.  You should consider shell escapes not using their shell,
  164. #     or else not caring about detailed status.  This should really be
  165. #     unified into one place, too.
  166. #   + Fixed bug where invisible trailing whitespace on commands hoses you,
  167. #     tricking Perl into thinking you wern't calling a debugger command!
  168. #   + Fixed bug where leading whitespace on commands hoses you.  (One
  169. #     suggests a leading semicolon or any other irrelevant non-whitespace
  170. #     to indicate literal Perl code.)
  171. #   + Fixed bugs that ate warnings due to wrong selected handle.
  172. #   + Fixed a precedence bug on signal stuff.
  173. #   + Fixed some unseemly wording.
  174. #   + Fixed bug in help command trying to call perl method code.
  175. #   + Fixed to call dumpvar from exception handler.  SIGPIPE killed us.
  176. #   ENHANCEMENTS:
  177. #   + Added some comments.  This code is still nasty spaghetti.
  178. #   + Added message if you clear your pre/post command stacks which was
  179. #     very easy to do if you just typed a bare >, <, or {.  (A command
  180. #     without an argument should *never* be a destructive action; this
  181. #     API is fundamentally screwed up; likewise option setting, which
  182. #     is equally buggered.)
  183. #   + Added command stack dump on argument of "?" for >, <, or {.
  184. #   + Added a semi-built-in doc viewer command that calls man with the
  185. #     proper %Config::Config path (and thus gets caching, man -k, etc),
  186. #     or else perldoc on obstreperous platforms.
  187. #   + Added to and rearranged the help information.
  188. #   + Detected apparent misuse of { ... } to declare a block; this used
  189. #     to work but now is a command, and mysteriously gave no complaint.
  190.  
  191. ####################################################################
  192.  
  193. # Needed for the statement after exec():
  194.  
  195. BEGIN { $ini_warn = $^W; $^W = 0 } # Switch compilation warnings off until another BEGIN.
  196. local($^W) = 0;            # Switch run-time warnings off during init.
  197. warn (            # Do not ;-)
  198.       $dumpvar::hashDepth,     
  199.       $dumpvar::arrayDepth,    
  200.       $dumpvar::dumpDBFiles,   
  201.       $dumpvar::dumpPackages,  
  202.       $dumpvar::quoteHighBit,  
  203.       $dumpvar::printUndef,    
  204.       $dumpvar::globPrint,     
  205.       $dumpvar::usageOnly,
  206.       @ARGS,
  207.       $Carp::CarpLevel,
  208.       $panic,
  209.       $second_time,
  210.      ) if 0;
  211.  
  212. # Command-line + PERLLIB:
  213. @ini_INC = @INC;
  214.  
  215. # $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?!
  216.  
  217. $trace = $signal = $single = 0;    # Uninitialized warning suppression
  218.                                 # (local $^W cannot help - other packages!).
  219. $inhibit_exit = $option{PrintRet} = 1;
  220.  
  221. @options     = qw(hashDepth arrayDepth DumpDBFiles DumpPackages DumpReused
  222.           compactDump veryCompact quote HighBit undefPrint
  223.           globPrint PrintRet UsageOnly frame AutoTrace
  224.           TTY noTTY ReadLine NonStop LineInfo maxTraceLen
  225.           recallCommand ShellBang pager tkRunning ornaments
  226.           signalLevel warnLevel dieLevel inhibit_exit
  227.           ImmediateStop bareStringify
  228.           RemotePort);
  229.  
  230. %optionVars    = (
  231.          hashDepth    => \$dumpvar::hashDepth,
  232.          arrayDepth    => \$dumpvar::arrayDepth,
  233.          DumpDBFiles    => \$dumpvar::dumpDBFiles,
  234.          DumpPackages    => \$dumpvar::dumpPackages,
  235.          DumpReused    => \$dumpvar::dumpReused,
  236.          HighBit    => \$dumpvar::quoteHighBit,
  237.          undefPrint    => \$dumpvar::printUndef,
  238.          globPrint    => \$dumpvar::globPrint,
  239.          UsageOnly    => \$dumpvar::usageOnly,     
  240.          bareStringify    => \$dumpvar::bareStringify,
  241.          frame          => \$frame,
  242.          AutoTrace      => \$trace,
  243.          inhibit_exit   => \$inhibit_exit,
  244.          maxTraceLen    => \$maxtrace,
  245.          ImmediateStop    => \$ImmediateStop,
  246.          RemotePort    => \$remoteport,
  247. );
  248.  
  249. %optionAction  = (
  250.           compactDump    => \&dumpvar::compactDump,
  251.           veryCompact    => \&dumpvar::veryCompact,
  252.           quote        => \&dumpvar::quote,
  253.           TTY        => \&TTY,
  254.           noTTY        => \&noTTY,
  255.           ReadLine    => \&ReadLine,
  256.           NonStop    => \&NonStop,
  257.           LineInfo    => \&LineInfo,
  258.           recallCommand    => \&recallCommand,
  259.           ShellBang    => \&shellBang,
  260.           pager        => \&pager,
  261.           signalLevel    => \&signalLevel,
  262.           warnLevel    => \&warnLevel,
  263.           dieLevel    => \&dieLevel,
  264.           tkRunning    => \&tkRunning,
  265.           ornaments    => \&ornaments,
  266.           RemotePort    => \&RemotePort,
  267.          );
  268.  
  269. %optionRequire = (
  270.           compactDump    => 'dumpvar.pl',
  271.           veryCompact    => 'dumpvar.pl',
  272.           quote        => 'dumpvar.pl',
  273.          );
  274.  
  275. # These guys may be defined in $ENV{PERL5DB} :
  276. $rl        = 1    unless defined $rl;
  277. $warnLevel    = 0    unless defined $warnLevel;
  278. $dieLevel    = 0    unless defined $dieLevel;
  279. $signalLevel    = 1    unless defined $signalLevel;
  280. $pre        = []    unless defined $pre;
  281. $post        = []    unless defined $post;
  282. $pretype    = []    unless defined $pretype;
  283.  
  284. warnLevel($warnLevel);
  285. dieLevel($dieLevel);
  286. signalLevel($signalLevel);
  287.  
  288. &pager(
  289.     (defined($ENV{PAGER}) 
  290.     ? $ENV{PAGER}
  291.     : ($^O eq 'os2' 
  292.        ? 'cmd /c more' 
  293.        : 'more'))) unless defined $pager;
  294. setman();
  295. &recallCommand("!") unless defined $prc;
  296. &shellBang("!") unless defined $psh;
  297. $maxtrace = 400 unless defined $maxtrace;
  298.  
  299. if (-e "/dev/tty") {  # this is the wrong metric!
  300.   $rcfile=".perldb";
  301. } else {
  302.   $rcfile="perldb.ini";
  303. }
  304.  
  305. # This isn't really safe, because there's a race
  306. # between checking and opening.  The solution is to
  307. # open and fstat the handle, but then you have to read and
  308. # eval the contents.  But then the silly thing gets
  309. # your lexical scope, which is unfortunately at best.
  310. sub safe_do { 
  311.     my $file = shift;
  312.  
  313.     # Just exactly what part of the word "CORE::" don't you understand?
  314.     local $SIG{__WARN__};  
  315.     local $SIG{__DIE__};    
  316.  
  317.     unless (is_safe_file($file)) {
  318.     CORE::warn <<EO_GRIPE;
  319. perldb: Must not source insecure rcfile $file.
  320.         You or the superuser must be the owner, and it must not 
  321.     be writable by anyone but its owner.
  322. EO_GRIPE
  323.     return;
  324.     } 
  325.  
  326.     do $file;
  327.     CORE::warn("perldb: couldn't parse $file: $@") if $@;
  328. }
  329.  
  330.  
  331. # Verifies that owner is either real user or superuser and that no
  332. # one but owner may write to it.  This function is of limited use
  333. # when called on a path instead of upon a handle, because there are
  334. # no guarantees that filename (by dirent) whose file (by ino) is
  335. # eventually accessed is the same as the one tested. 
  336. # Assumes that the file's existence is not in doubt.
  337. sub is_safe_file {
  338.     my $path = shift;
  339.     stat($path) || return;    # mysteriously vaporized
  340.     my($dev,$ino,$mode,$nlink,$uid,$gid) = stat(_);
  341.  
  342.     return 0 if $uid != 0 && $uid != $<;
  343.     return 0 if $mode & 022;
  344.     return 1;
  345. }
  346.  
  347. if (-f $rcfile) {
  348.     safe_do("./$rcfile");
  349. elsif (defined $ENV{HOME} && -f "$ENV{HOME}/$rcfile") {
  350.     safe_do("$ENV{HOME}/$rcfile");
  351. }
  352. elsif (defined $ENV{LOGDIR} && -f "$ENV{LOGDIR}/$rcfile") {
  353.     safe_do("$ENV{LOGDIR}/$rcfile");
  354. }
  355.  
  356. if (defined $ENV{PERLDB_OPTS}) {
  357.   parse_options($ENV{PERLDB_OPTS});
  358. }
  359.  
  360. # Here begin the unreadable code.  It needs fixing.
  361.  
  362. if (exists $ENV{PERLDB_RESTART}) {
  363.   delete $ENV{PERLDB_RESTART};
  364.   # $restart = 1;
  365.   @hist = get_list('PERLDB_HIST');
  366.   %break_on_load = get_list("PERLDB_ON_LOAD");
  367.   %postponed = get_list("PERLDB_POSTPONE");
  368.   my @had_breakpoints= get_list("PERLDB_VISITED");
  369.   for (0 .. $#had_breakpoints) {
  370.     my %pf = get_list("PERLDB_FILE_$_");
  371.     $postponed_file{$had_breakpoints[$_]} = \%pf if %pf;
  372.   }
  373.   my %opt = get_list("PERLDB_OPT");
  374.   my ($opt,$val);
  375.   while (($opt,$val) = each %opt) {
  376.     $val =~ s/[\\\']/\\$1/g;
  377.     parse_options("$opt'$val'");
  378.   }
  379.   @INC = get_list("PERLDB_INC");
  380.   @ini_INC = @INC;
  381.   $pretype = [get_list("PERLDB_PRETYPE")];
  382.   $pre = [get_list("PERLDB_PRE")];
  383.   $post = [get_list("PERLDB_POST")];
  384.   @typeahead = get_list("PERLDB_TYPEAHEAD", @typeahead);
  385. }
  386.  
  387. if ($notty) {
  388.   $runnonstop = 1;
  389. } else {
  390.   # Is Perl being run from a slave editor or graphical debugger?
  391.   $slave_editor = ((defined $main::ARGV[0]) and ($main::ARGV[0] eq '-emacs'));
  392.   $rl = 0, shift(@main::ARGV) if $slave_editor;
  393.  
  394.   #require Term::ReadLine;
  395.  
  396.   if ($^O eq 'cygwin') {
  397.     # /dev/tty is binary. use stdin for textmode
  398.     undef $console;
  399.   } elsif (-e "/dev/tty") {
  400.     $console = "/dev/tty";
  401.   } elsif ($^O eq 'dos' or -e "con" or $^O eq 'MSWin32') {
  402.     $console = "con";
  403.   } else {
  404.     $console = "sys\$command";
  405.   }
  406.  
  407.   if (($^O eq 'MSWin32') and ($slave_editor or defined $ENV{EMACS})) {
  408.     $console = undef;
  409.   }
  410.  
  411.   # Around a bug:
  412.   if (defined $ENV{OS2_SHELL} and ($slave_editor or $ENV{WINDOWID})) { # In OS/2
  413.     $console = undef;
  414.   }
  415.  
  416.   if ($^O eq 'epoc') {
  417.     $console = undef;
  418.   }
  419.  
  420.   $console = $tty if defined $tty;
  421.  
  422.   if (defined $remoteport) {
  423.     require IO::Socket;
  424.     $OUT = new IO::Socket::INET( Timeout  => '10',
  425.                                  PeerAddr => $remoteport,
  426.                                  Proto    => 'tcp',
  427.                                );
  428.     if (!$OUT) { die "Could not create socket to connect to remote host."; }
  429.     $IN = $OUT;
  430.   }
  431.   else {
  432.     if (defined $console) {
  433.       open(IN,"+<$console") || open(IN,"<$console") || open(IN,"<&STDIN");
  434.       open(OUT,"+>$console") || open(OUT,">$console") || open(OUT,">&STDERR")
  435.         || open(OUT,">&STDOUT");    # so we don't dongle stdout
  436.     } else {
  437.       open(IN,"<&STDIN");
  438.       open(OUT,">&STDERR") || open(OUT,">&STDOUT"); # so we don't dongle stdout
  439.       $console = 'STDIN/OUT';
  440.     }
  441.     # so open("|more") can read from STDOUT and so we don't dingle stdin
  442.     $IN = \*IN;
  443.  
  444.     $OUT = \*OUT;
  445.   }
  446.   select($OUT);
  447.   $| = 1;            # for DB::OUT
  448.   select(STDOUT);
  449.  
  450.   $LINEINFO = $OUT unless defined $LINEINFO;
  451.   $lineinfo = $console unless defined $lineinfo;
  452.  
  453.   $| = 1;            # for real STDOUT
  454.  
  455.   $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/;
  456.   unless ($runnonstop) {
  457.     print $OUT "\nLoading DB routines from $header\n";
  458.     print $OUT ("Editor support ",
  459.         $slave_editor ? "enabled" : "available",
  460.         ".\n");
  461.     print $OUT "\nEnter h or `h h' for help, or `$doccmd perldebug' for more help.\n\n";
  462.   }
  463. }
  464.  
  465. @ARGS = @ARGV;
  466. for (@args) {
  467.     s/\'/\\\'/g;
  468.     s/(.*)/'$1'/ unless /^-?[\d.]+$/;
  469. }
  470.  
  471. if (defined &afterinit) {    # May be defined in $rcfile
  472.   &afterinit();
  473. }
  474.  
  475. $I_m_init = 1;
  476.  
  477. ############################################################ Subroutines
  478.  
  479. sub DB {
  480.     # _After_ the perl program is compiled, $single is set to 1:
  481.     if ($single and not $second_time++) {
  482.       if ($runnonstop) {    # Disable until signal
  483.     for ($i=0; $i <= $stack_depth; ) {
  484.         $stack[$i++] &= ~1;
  485.     }
  486.     $single = 0;
  487.     # return;            # Would not print trace!
  488.       } elsif ($ImmediateStop) {
  489.     $ImmediateStop = 0;
  490.     $signal = 1;
  491.       }
  492.     }
  493.     $runnonstop = 0 if $single or $signal; # Disable it if interactive.
  494.     &save;
  495.     ($package, $filename, $line) = caller;
  496.     $filename_ini = $filename;
  497.     $usercontext = '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' .
  498.       "package $package;";    # this won't let them modify, alas
  499.     local(*dbline) = $main::{'_<' . $filename};
  500.     $max = $#dbline;
  501.     if (($stop,$action) = split(/\0/,$dbline{$line})) {
  502.     if ($stop eq '1') {
  503.         $signal |= 1;
  504.     } elsif ($stop) {
  505.         $evalarg = "\$DB::signal |= 1 if do {$stop}"; &eval;
  506.         $dbline{$line} =~ s/;9($|\0)/$1/;
  507.     }
  508.     }
  509.     my $was_signal = $signal;
  510.     if ($trace & 2) {
  511.       for (my $n = 0; $n <= $#to_watch; $n++) {
  512.     $evalarg = $to_watch[$n];
  513.     local $onetimeDump;    # Do not output results
  514.     my ($val) = &eval;    # Fix context (&eval is doing array)?
  515.     $val = ( (defined $val) ? "'$val'" : 'undef' );
  516.     if ($val ne $old_watch[$n]) {
  517.       $signal = 1;
  518.       print $OUT <<EOP;
  519. Watchpoint $n:\t$to_watch[$n] changed:
  520.     old value:\t$old_watch[$n]
  521.     new value:\t$val
  522. EOP
  523.       $old_watch[$n] = $val;
  524.     }
  525.       }
  526.     }
  527.     if ($trace & 4) {        # User-installed watch
  528.       return if watchfunction($package, $filename, $line) 
  529.     and not $single and not $was_signal and not ($trace & ~4);
  530.     }
  531.     $was_signal = $signal;
  532.     $signal = 0;
  533.     if ($single || ($trace & 1) || $was_signal) {
  534.     if ($slave_editor) {
  535.         $position = "\032\032$filename:$line:0\n";
  536.         print $LINEINFO $position;
  537.     } elsif ($package eq 'DB::fake') {
  538.       $term || &setterm;
  539.       print_help(<<EOP);
  540. Debugged program terminated.  Use B<q> to quit or B<R> to restart,
  541.   use B<O> I<inhibit_exit> to avoid stopping after program termination,
  542.   B<h q>, B<h R> or B<h O> to get additional info.  
  543. EOP
  544.       $package = 'main';
  545.       $usercontext = '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' .
  546.         "package $package;";    # this won't let them modify, alas
  547.     } else {
  548.         $sub =~ s/\'/::/;
  549.         $prefix = $sub =~ /::/ ? "" : "${'package'}::";
  550.         $prefix .= "$sub($filename:";
  551.         $after = ($dbline[$line] =~ /\n$/ ? '' : "\n");
  552.         if (length($prefix) > 30) {
  553.             $position = "$prefix$line):\n$line:\t$dbline[$line]$after";
  554.         $prefix = "";
  555.         $infix = ":\t";
  556.         } else {
  557.         $infix = "):\t";
  558.         $position = "$prefix$line$infix$dbline[$line]$after";
  559.         }
  560.         if ($frame) {
  561.         print $LINEINFO ' ' x $stack_depth, "$line:\t$dbline[$line]$after";
  562.         } else {
  563.         print $LINEINFO $position;
  564.         }
  565.         for ($i = $line + 1; $i <= $max && $dbline[$i] == 0; ++$i) { #{ vi
  566.         last if $dbline[$i] =~ /^\s*[\;\}\#\n]/;
  567.         last if $signal;
  568.         $after = ($dbline[$i] =~ /\n$/ ? '' : "\n");
  569.         $incr_pos = "$prefix$i$infix$dbline[$i]$after";
  570.         $position .= $incr_pos;
  571.         if ($frame) {
  572.             print $LINEINFO ' ' x $stack_depth, "$i:\t$dbline[$i]$after";
  573.         } else {
  574.             print $LINEINFO $incr_pos;
  575.         }
  576.         }
  577.     }
  578.     }
  579.     $evalarg = $action, &eval if $action;
  580.     if ($single || $was_signal) {
  581.     local $level = $level + 1;
  582.     foreach $evalarg (@$pre) {
  583.       &eval;
  584.     }
  585.     print $OUT $stack_depth . " levels deep in subroutine calls!\n"
  586.       if $single & 4;
  587.     $start = $line;
  588.     $incr = -1;        # for backward motion.
  589.     @typeahead = (@$pretype, @typeahead);
  590.       CMD:
  591.     while (($term || &setterm),
  592.            ($term_pid == $$ or &resetterm),
  593.            defined ($cmd=&readline("  DB" . ('<' x $level) .
  594.                        ($#hist+1) . ('>' x $level) .
  595.                        " "))) 
  596.         {
  597.         $single = 0;
  598.         $signal = 0;
  599.         $cmd =~ s/\\$/\n/ && do {
  600.             $cmd .= &readline("  cont: ");
  601.             redo CMD;
  602.         };
  603.         $cmd =~ /^$/ && ($cmd = $laststep);
  604.         push(@hist,$cmd) if length($cmd) > 1;
  605.           PIPE: {
  606.             $cmd =~ s/^\s+//s;   # trim annoying leading whitespace
  607.             $cmd =~ s/\s+$//s;   # trim annoying trailing whitespace
  608.             ($i) = split(/\s+/,$cmd);
  609.             if ($alias{$i}) { 
  610.             # squelch the sigmangler
  611.             local $SIG{__DIE__};
  612.             local $SIG{__WARN__};
  613.             eval "\$cmd =~ $alias{$i}";
  614.             if ($@) {
  615.                 print $OUT "Couldn't evaluate `$i' alias: $@";
  616.                 next CMD;
  617.             } 
  618.             }
  619.             $cmd =~ /^q$/ && ($exiting = 1) && exit 0;
  620.             $cmd =~ /^h$/ && do {
  621.             print_help($help);
  622.             next CMD; };
  623.             $cmd =~ /^h\s+h$/ && do {
  624.             print_help($summary);
  625.             next CMD; };
  626.             # support long commands; otherwise bogus errors
  627.             # happen when you ask for h on <CR> for example
  628.             $cmd =~ /^h\s+(\S.*)$/ && do {      
  629.             my $asked = $1;            # for proper errmsg
  630.             my $qasked = quotemeta($asked); # for searching
  631.             # XXX: finds CR but not <CR>
  632.             if ($help =~ /^<?(?:[IB]<)$qasked/m) {
  633.               while ($help =~ /^(<?(?:[IB]<)$qasked([\s\S]*?)\n)(?!\s)/mg) {
  634.                 print_help($1);
  635.               }
  636.             } else {
  637.                 print_help("B<$asked> is not a debugger command.\n");
  638.             }
  639.             next CMD; };
  640.             $cmd =~ /^t$/ && do {
  641.             $trace ^= 1;
  642.             print $OUT "Trace = " .
  643.                 (($trace & 1) ? "on" : "off" ) . "\n";
  644.             next CMD; };
  645.             $cmd =~ /^S(\s+(!)?(.+))?$/ && do {
  646.             $Srev = defined $2; $Spatt = $3; $Snocheck = ! defined $1;
  647.             foreach $subname (sort(keys %sub)) {
  648.                 if ($Snocheck or $Srev^($subname =~ /$Spatt/)) {
  649.                 print $OUT $subname,"\n";
  650.                 }
  651.             }
  652.             next CMD; };
  653.             $cmd =~ /^v$/ && do {
  654.             list_versions(); next CMD};
  655.             $cmd =~ s/^X\b/V $package/;
  656.             $cmd =~ /^V$/ && do {
  657.             $cmd = "V $package"; };
  658.             $cmd =~ /^V\b\s*(\S+)\s*(.*)/ && do {
  659.             local ($savout) = select($OUT);
  660.             $packname = $1;
  661.             @vars = split(' ',$2);
  662.             do 'dumpvar.pl' unless defined &main::dumpvar;
  663.             if (defined &main::dumpvar) {
  664.                 local $frame = 0;
  665.                 local $doret = -2;
  666.                 # must detect sigpipe failures
  667.                 eval { &main::dumpvar($packname,@vars) };
  668.                 if ($@) {
  669.                 die unless $@ =~ /dumpvar print failed/;
  670.                 } 
  671.             } else {
  672.                 print $OUT "dumpvar.pl not available.\n";
  673.             }
  674.             select ($savout);
  675.             next CMD; };
  676.             $cmd =~ s/^x\b/ / && do { # So that will be evaled
  677.             $onetimeDump = 'dump'; };
  678.             $cmd =~ s/^m\s+([\w:]+)\s*$/ / && do {
  679.             methods($1); next CMD};
  680.             $cmd =~ s/^m\b/ / && do { # So this will be evaled
  681.             $onetimeDump = 'methods'; };
  682.             $cmd =~ /^f\b\s*(.*)/ && do {
  683.             $file = $1;
  684.             $file =~ s/\s+$//;
  685.             if (!$file) {
  686.                 print $OUT "The old f command is now the r command.\n";
  687.                 print $OUT "The new f command switches filenames.\n";
  688.                 next CMD;
  689.             }
  690.             if (!defined $main::{'_<' . $file}) {
  691.                 if (($try) = grep(m#^_<.*$file#, keys %main::)) {{
  692.                           $try = substr($try,2);
  693.                           print $OUT "Choosing $try matching `$file':\n";
  694.                           $file = $try;
  695.                       }}
  696.             }
  697.             if (!defined $main::{'_<' . $file}) {
  698.                 print $OUT "No file matching `$file' is loaded.\n";
  699.                 next CMD;
  700.             } elsif ($file ne $filename) {
  701.                 *dbline = $main::{'_<' . $file};
  702.                 $max = $#dbline;
  703.                 $filename = $file;
  704.                 $start = 1;
  705.                 $cmd = "l";
  706.               } else {
  707.                 print $OUT "Already in $file.\n";
  708.                 next CMD;
  709.               }
  710.               };
  711.             $cmd =~ s/^l\s+-\s*$/-/;
  712.             $cmd =~ /^([lb])\b\s*(\$.*)/s && do {
  713.             $evalarg = $2;
  714.             my ($s) = &eval;
  715.             print($OUT "Error: $@\n"), next CMD if $@;
  716.             $s = CvGV_name($s);
  717.             print($OUT "Interpreted as: $1 $s\n");
  718.             $cmd = "$1 $s";
  719.             };
  720.             $cmd =~ /^l\b\s*([\':A-Za-z_][\':\w]*(\[.*\])?)/s && do {
  721.             $subname = $1;
  722.             $subname =~ s/\'/::/;
  723.             $subname = $package."::".$subname 
  724.               unless $subname =~ /::/;
  725.             $subname = "main".$subname if substr($subname,0,2) eq "::";
  726.             @pieces = split(/:/,find_sub($subname) || $sub{$subname});
  727.             $subrange = pop @pieces;
  728.             $file = join(':', @pieces);
  729.             if ($file ne $filename) {
  730.                 print $OUT "Switching to file '$file'.\n"
  731.                 unless $slave_editor;
  732.                 *dbline = $main::{'_<' . $file};
  733.                 $max = $#dbline;
  734.                 $filename = $file;
  735.             }
  736.             if ($subrange) {
  737.                 if (eval($subrange) < -$window) {
  738.                 $subrange =~ s/-.*/+/;
  739.                 }
  740.                 $cmd = "l $subrange";
  741.             } else {
  742.                 print $OUT "Subroutine $subname not found.\n";
  743.                 next CMD;
  744.             } };
  745.             $cmd =~ /^\.$/ && do {
  746.             $incr = -1;        # for backward motion.
  747.             $start = $line;
  748.             $filename = $filename_ini;
  749.             *dbline = $main::{'_<' . $filename};
  750.             $max = $#dbline;
  751.             print $LINEINFO $position;
  752.             next CMD };
  753.             $cmd =~ /^w\b\s*(\d*)$/ && do {
  754.             $incr = $window - 1;
  755.             $start = $1 if $1;
  756.             $start -= $preview;
  757.             #print $OUT 'l ' . $start . '-' . ($start + $incr);
  758.             $cmd = 'l ' . $start . '-' . ($start + $incr); };
  759.             $cmd =~ /^-$/ && do {
  760.             $start -= $incr + $window + 1;
  761.             $start = 1 if $start <= 0;
  762.             $incr = $window - 1;
  763.             $cmd = 'l ' . ($start) . '+'; };
  764.             $cmd =~ /^l$/ && do {
  765.             $incr = $window - 1;
  766.             $cmd = 'l ' . $start . '-' . ($start + $incr); };
  767.             $cmd =~ /^l\b\s*(\d*)\+(\d*)$/ && do {
  768.             $start = $1 if $1;
  769.             $incr = $2;
  770.             $incr = $window - 1 unless $incr;
  771.             $cmd = 'l ' . $start . '-' . ($start + $incr); };
  772.             $cmd =~ /^l\b\s*((-?[\d\$\.]+)([-,]([\d\$\.]+))?)?/ && do {
  773.             $end = (!defined $2) ? $max : ($4 ? $4 : $2);
  774.             $end = $max if $end > $max;
  775.             $i = $2;
  776.             $i = $line if $i eq '.';
  777.             $i = 1 if $i < 1;
  778.             $incr = $end - $i;
  779.             if ($slave_editor) {
  780.                 print $OUT "\032\032$filename:$i:0\n";
  781.                 $i = $end;
  782.             } else {
  783.                 for (; $i <= $end; $i++) {
  784.                     ($stop,$action) = split(/\0/, $dbline{$i});
  785.                     $arrow = ($i==$line 
  786.                       and $filename eq $filename_ini) 
  787.                   ?  '==>' 
  788.                     : ($dbline[$i]+0 ? ':' : ' ') ;
  789.                 $arrow .= 'b' if $stop;
  790.                 $arrow .= 'a' if $action;
  791.                 print $OUT "$i$arrow\t", $dbline[$i];
  792.                 $i++, last if $signal;
  793.                 }
  794.                 print $OUT "\n" unless $dbline[$i-1] =~ /\n$/;
  795.             }
  796.             $start = $i; # remember in case they want more
  797.             $start = $max if $start > $max;
  798.             next CMD; };
  799.             $cmd =~ /^D$/ && do {
  800.               print $OUT "Deleting all breakpoints...\n";
  801.               my $file;
  802.               for $file (keys %had_breakpoints) {
  803.             local *dbline = $main::{'_<' . $file};
  804.             my $max = $#dbline;
  805.             my $was;
  806.             
  807.             for ($i = 1; $i <= $max ; $i++) {
  808.                 if (defined $dbline{$i}) {
  809.                 $dbline{$i} =~ s/^[^\0]+//;
  810.                 if ($dbline{$i} =~ s/^\0?$//) {
  811.                     delete $dbline{$i};
  812.                 }
  813.                 }
  814.             }
  815.             
  816.             if (not $had_breakpoints{$file} &= ~1) {
  817.                 delete $had_breakpoints{$file};
  818.             }
  819.               }
  820.               undef %postponed;
  821.               undef %postponed_file;
  822.               undef %break_on_load;
  823.               next CMD; };
  824.             $cmd =~ /^L$/ && do {
  825.               my $file;
  826.               for $file (keys %had_breakpoints) {
  827.             local *dbline = $main::{'_<' . $file};
  828.             my $max = $#dbline;
  829.             my $was;
  830.             
  831.             for ($i = 1; $i <= $max; $i++) {
  832.                 if (defined $dbline{$i}) {
  833.                     print $OUT "$file:\n" unless $was++;
  834.                 print $OUT " $i:\t", $dbline[$i];
  835.                 ($stop,$action) = split(/\0/, $dbline{$i});
  836.                 print $OUT "   break if (", $stop, ")\n"
  837.                   if $stop;
  838.                 print $OUT "   action:  ", $action, "\n"
  839.                   if $action;
  840.                 last if $signal;
  841.                 }
  842.             }
  843.               }
  844.               if (%postponed) {
  845.             print $OUT "Postponed breakpoints in subroutines:\n";
  846.             my $subname;
  847.             for $subname (keys %postponed) {
  848.               print $OUT " $subname\t$postponed{$subname}\n";
  849.               last if $signal;
  850.             }
  851.               }
  852.               my @have = map { # Combined keys
  853.             keys %{$postponed_file{$_}}
  854.               } keys %postponed_file;
  855.               if (@have) {
  856.             print $OUT "Postponed breakpoints in files:\n";
  857.             my ($file, $line);
  858.             for $file (keys %postponed_file) {
  859.               my $db = $postponed_file{$file};
  860.               print $OUT " $file:\n";
  861.               for $line (sort {$a <=> $b} keys %$db) {
  862.                 print $OUT "  $line:\n";
  863.                 my ($stop,$action) = split(/\0/, $$db{$line});
  864.                 print $OUT "    break if (", $stop, ")\n"
  865.                   if $stop;
  866.                 print $OUT "    action:  ", $action, "\n"
  867.                   if $action;
  868.                 last if $signal;
  869.               }
  870.               last if $signal;
  871.             }
  872.               }
  873.               if (%break_on_load) {
  874.             print $OUT "Breakpoints on load:\n";
  875.             my $file;
  876.             for $file (keys %break_on_load) {
  877.               print $OUT " $file\n";
  878.               last if $signal;
  879.             }
  880.               }
  881.               if ($trace & 2) {
  882.             print $OUT "Watch-expressions:\n";
  883.             my $expr;
  884.             for $expr (@to_watch) {
  885.               print $OUT " $expr\n";
  886.               last if $signal;
  887.             }
  888.               }
  889.               next CMD; };
  890.             $cmd =~ /^b\b\s*load\b\s*(.*)/ && do {
  891.             my $file = $1; $file =~ s/\s+$//;
  892.             {
  893.               $break_on_load{$file} = 1;
  894.               $break_on_load{$::INC{$file}} = 1 if $::INC{$file};
  895.               $file .= '.pm', redo unless $file =~ /\./;
  896.             }
  897.             $had_breakpoints{$file} |= 1;
  898.             print $OUT "Will stop on load of `@{[join '\', `', sort keys %break_on_load]}'.\n";
  899.             next CMD; };
  900.             $cmd =~ /^b\b\s*(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/ && do {
  901.             my $cond = $3 || '1';
  902.             my ($subname, $break) = ($2, $1 eq 'postpone');
  903.             $subname =~ s/\'/::/;
  904.             $subname = "${'package'}::" . $subname
  905.               unless $subname =~ /::/;
  906.             $subname = "main".$subname if substr($subname,0,2) eq "::";
  907.             $postponed{$subname} = $break 
  908.               ? "break +0 if $cond" : "compile";
  909.             next CMD; };
  910.             $cmd =~ /^b\b\s*([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/ && do {
  911.             $subname = $1;
  912.             $cond = $2 || '1';
  913.             $subname =~ s/\'/::/;
  914.             $subname = "${'package'}::" . $subname
  915.               unless $subname =~ /::/;
  916.             $subname = "main".$subname if substr($subname,0,2) eq "::";
  917.             # Filename below can contain ':'
  918.             ($file,$i) = (find_sub($subname) =~ /^(.*):(.*)$/);
  919.             $i += 0;
  920.             if ($i) {
  921.                 local $filename = $file;
  922.                 local *dbline = $main::{'_<' . $filename};
  923.                 $had_breakpoints{$filename} |= 1;
  924.                 $max = $#dbline;
  925.                 ++$i while $dbline[$i] == 0 && $i < $max;
  926.                 $dbline{$i} =~ s/^[^\0]*/$cond/;
  927.             } else {
  928.                 print $OUT "Subroutine $subname not found.\n";
  929.             }
  930.             next CMD; };
  931.             $cmd =~ /^b\b\s*(\d*)\s*(.*)/ && do {
  932.             $i = $1 || $line;
  933.             $cond = $2 || '1';
  934.             if ($dbline[$i] == 0) {
  935.                 print $OUT "Line $i not breakable.\n";
  936.             } else {
  937.                 $had_breakpoints{$filename} |= 1;
  938.                 $dbline{$i} =~ s/^[^\0]*/$cond/;
  939.             }
  940.             next CMD; };
  941.             $cmd =~ /^d\b\s*(\d*)/ && do {
  942.             $i = $1 || $line;
  943.             $dbline{$i} =~ s/^[^\0]*//;
  944.             delete $dbline{$i} if $dbline{$i} eq '';
  945.             next CMD; };
  946.             $cmd =~ /^A$/ && do {
  947.               print $OUT "Deleting all actions...\n";
  948.               my $file;
  949.               for $file (keys %had_breakpoints) {
  950.             local *dbline = $main::{'_<' . $file};
  951.             my $max = $#dbline;
  952.             my $was;
  953.             
  954.             for ($i = 1; $i <= $max ; $i++) {
  955.                 if (defined $dbline{$i}) {
  956.                 $dbline{$i} =~ s/\0[^\0]*//;
  957.                 delete $dbline{$i} if $dbline{$i} eq '';
  958.                 }
  959.             }
  960.             
  961.             unless ($had_breakpoints{$file} &= ~2) {
  962.                 delete $had_breakpoints{$file};
  963.             }
  964.               }
  965.               next CMD; };
  966.             $cmd =~ /^O\s*$/ && do {
  967.             for (@options) {
  968.                 &dump_option($_);
  969.             }
  970.             next CMD; };
  971.             $cmd =~ /^O\s*(\S.*)/ && do {
  972.             parse_options($1);
  973.             next CMD; };
  974.             $cmd =~ /^\<\<\s*(.*)/ && do { # \<\< for CPerl sake: not HERE
  975.             push @$pre, action($1);
  976.             next CMD; };
  977.             $cmd =~ /^>>\s*(.*)/ && do {
  978.             push @$post, action($1);
  979.             next CMD; };
  980.             $cmd =~ /^<\s*(.*)/ && do {
  981.             unless ($1) {
  982.                 print OUT "All < actions cleared.\n";
  983.                 $pre = [];
  984.                 next CMD;
  985.             } 
  986.             if ($1 eq '?') {
  987.                 unless (@$pre) {
  988.                 print OUT "No pre-prompt Perl actions.\n";
  989.                 next CMD;
  990.                 } 
  991.                 print OUT "Perl commands run before each prompt:\n";
  992.                 for my $action ( @$pre ) {
  993.                 print "\t< -- $action\n";
  994.                 } 
  995.                 next CMD;
  996.             } 
  997.             $pre = [action($1)];
  998.             next CMD; };
  999.             $cmd =~ /^>\s*(.*)/ && do {
  1000.             unless ($1) {
  1001.                 print OUT "All > actions cleared.\n";
  1002.                 $post = [];
  1003.                 next CMD;
  1004.             }
  1005.             if ($1 eq '?') {
  1006.                 unless (@$post) {
  1007.                 print OUT "No post-prompt Perl actions.\n";
  1008.                 next CMD;
  1009.                 } 
  1010.                 print OUT "Perl commands run after each prompt:\n";
  1011.                 for my $action ( @$post ) {
  1012.                 print "\t> -- $action\n";
  1013.                 } 
  1014.                 next CMD;
  1015.             } 
  1016.             $post = [action($1)];
  1017.             next CMD; };
  1018.             $cmd =~ /^\{\{\s*(.*)/ && do {
  1019.             if ($cmd =~ /^\{.*\}$/ && unbalanced(substr($cmd,2))) { 
  1020.                 print OUT "{{ is now a debugger command\n",
  1021.                 "use `;{{' if you mean Perl code\n";
  1022.                 $cmd = "h {{";
  1023.                 redo CMD;
  1024.             } 
  1025.             push @$pretype, $1;
  1026.             next CMD; };
  1027.             $cmd =~ /^\{\s*(.*)/ && do {
  1028.             unless ($1) {
  1029.                 print OUT "All { actions cleared.\n";
  1030.                 $pretype = [];
  1031.                 next CMD;
  1032.             }
  1033.             if ($1 eq '?') {
  1034.                 unless (@$pretype) {
  1035.                 print OUT "No pre-prompt debugger actions.\n";
  1036.                 next CMD;
  1037.                 } 
  1038.                 print OUT "Debugger commands run before each prompt:\n";
  1039.                 for my $action ( @$pretype ) {
  1040.                 print "\t{ -- $action\n";
  1041.                 } 
  1042.                 next CMD;
  1043.             } 
  1044.             if ($cmd =~ /^\{.*\}$/ && unbalanced(substr($cmd,1))) { 
  1045.                 print OUT "{ is now a debugger command\n",
  1046.                 "use `;{' if you mean Perl code\n";
  1047.                 $cmd = "h {";
  1048.                 redo CMD;
  1049.             } 
  1050.             $pretype = [$1];
  1051.             next CMD; };
  1052.             $cmd =~ /^a\b\s*(\d*)\s*(.*)/ && do {
  1053.             $i = $1 || $line; $j = $2;
  1054.             if (length $j) {
  1055.                 if ($dbline[$i] == 0) {
  1056.                 print $OUT "Line $i may not have an action.\n";
  1057.                 } else {
  1058.                 $had_breakpoints{$filename} |= 2;
  1059.                 $dbline{$i} =~ s/\0[^\0]*//;
  1060.                 $dbline{$i} .= "\0" . action($j);
  1061.                 }
  1062.             } else {
  1063.                 $dbline{$i} =~ s/\0[^\0]*//;
  1064.                 delete $dbline{$i} if $dbline{$i} eq '';
  1065.             }
  1066.             next CMD; };
  1067.             $cmd =~ /^n$/ && do {
  1068.                 end_report(), next CMD if $finished and $level <= 1;
  1069.             $single = 2;
  1070.             $laststep = $cmd;
  1071.             last CMD; };
  1072.             $cmd =~ /^s$/ && do {
  1073.                 end_report(), next CMD if $finished and $level <= 1;
  1074.             $single = 1;
  1075.             $laststep = $cmd;
  1076.             last CMD; };
  1077.             $cmd =~ /^c\b\s*([\w:]*)\s*$/ && do {
  1078.                 end_report(), next CMD if $finished and $level <= 1;
  1079.             $subname = $i = $1;
  1080.             #  Probably not needed, since we finish an interactive
  1081.             #  sub-session anyway...
  1082.             # local $filename = $filename;
  1083.             # local *dbline = *dbline;    # XXX Would this work?!
  1084.             if ($i =~ /\D/) { # subroutine name
  1085.                 $subname = $package."::".$subname 
  1086.                     unless $subname =~ /::/;
  1087.                 ($file,$i) = (find_sub($subname) =~ /^(.*):(.*)$/);
  1088.                 $i += 0;
  1089.                 if ($i) {
  1090.                     $filename = $file;
  1091.                 *dbline = $main::{'_<' . $filename};
  1092.                 $had_breakpoints{$filename} |= 1;
  1093.                 $max = $#dbline;
  1094.                 ++$i while $dbline[$i] == 0 && $i < $max;
  1095.                 } else {
  1096.                 print $OUT "Subroutine $subname not found.\n";
  1097.                 next CMD; 
  1098.                 }
  1099.             }
  1100.             if ($i) {
  1101.                 if ($dbline[$i] == 0) {
  1102.                 print $OUT "Line $i not breakable.\n";
  1103.                 next CMD;
  1104.                 }
  1105.                 $dbline{$i} =~ s/($|\0)/;9$1/; # add one-time-only b.p.
  1106.             }
  1107.             for ($i=0; $i <= $stack_depth; ) {
  1108.                 $stack[$i++] &= ~1;
  1109.             }
  1110.             last CMD; };
  1111.             $cmd =~ /^r$/ && do {
  1112.                 end_report(), next CMD if $finished and $level <= 1;
  1113.             $stack[$stack_depth] |= 1;
  1114.             $doret = $option{PrintRet} ? $stack_depth - 1 : -2;
  1115.             last CMD; };
  1116.             $cmd =~ /^R$/ && do {
  1117.                 print $OUT "Warning: some settings and command-line options may be lost!\n";
  1118.             my (@script, @flags, $cl);
  1119.             push @flags, '-w' if $ini_warn;
  1120.             # Put all the old includes at the start to get
  1121.             # the same debugger.
  1122.             for (@ini_INC) {
  1123.               push @flags, '-I', $_;
  1124.             }
  1125.             # Arrange for setting the old INC:
  1126.             set_list("PERLDB_INC", @ini_INC);
  1127.             if ($0 eq '-e') {
  1128.               for (1..$#{'::_<-e'}) { # The first line is PERL5DB
  1129.                     chomp ($cl =  ${'::_<-e'}[$_]);
  1130.                 push @script, '-e', $cl;
  1131.               }
  1132.             } else {
  1133.               @script = $0;
  1134.             }
  1135.             set_list("PERLDB_HIST", 
  1136.                  $term->Features->{getHistory} 
  1137.                  ? $term->GetHistory : @hist);
  1138.             my @had_breakpoints = keys %had_breakpoints;
  1139.             set_list("PERLDB_VISITED", @had_breakpoints);
  1140.             set_list("PERLDB_OPT", %option);
  1141.             set_list("PERLDB_ON_LOAD", %break_on_load);
  1142.             my @hard;
  1143.             for (0 .. $#had_breakpoints) {
  1144.               my $file = $had_breakpoints[$_];
  1145.               *dbline = $main::{'_<' . $file};
  1146.               next unless %dbline or $postponed_file{$file};
  1147.               (push @hard, $file), next 
  1148.                 if $file =~ /^\(eval \d+\)$/;
  1149.               my @add;
  1150.               @add = %{$postponed_file{$file}}
  1151.                 if $postponed_file{$file};
  1152.               set_list("PERLDB_FILE_$_", %dbline, @add);
  1153.             }
  1154.             for (@hard) { # Yes, really-really...
  1155.               # Find the subroutines in this eval
  1156.               *dbline = $main::{'_<' . $_};
  1157.               my ($quoted, $sub, %subs, $line) = quotemeta $_;
  1158.               for $sub (keys %sub) {
  1159.                 next unless $sub{$sub} =~ /^$quoted:(\d+)-(\d+)$/;
  1160.                 $subs{$sub} = [$1, $2];
  1161.               }
  1162.               unless (%subs) {
  1163.                 print $OUT
  1164.                   "No subroutines in $_, ignoring breakpoints.\n";
  1165.                 next;
  1166.               }
  1167.             LINES: for $line (keys %dbline) {
  1168.                 # One breakpoint per sub only:
  1169.                 my ($offset, $sub, $found);
  1170.               SUBS: for $sub (keys %subs) {
  1171.                   if ($subs{$sub}->[1] >= $line # Not after the subroutine
  1172.                   and (not defined $offset # Not caught
  1173.                        or $offset < 0 )) { # or badly caught
  1174.                 $found = $sub;
  1175.                 $offset = $line - $subs{$sub}->[0];
  1176.                 $offset = "+$offset", last SUBS if $offset >= 0;
  1177.                   }
  1178.                 }
  1179.                 if (defined $offset) {
  1180.                   $postponed{$found} =
  1181.                 "break $offset if $dbline{$line}";
  1182.                 } else {
  1183.                   print $OUT "Breakpoint in $_:$line ignored: after all the subroutines.\n";
  1184.                 }
  1185.               }
  1186.             }
  1187.             set_list("PERLDB_POSTPONE", %postponed);
  1188.             set_list("PERLDB_PRETYPE", @$pretype);
  1189.             set_list("PERLDB_PRE", @$pre);
  1190.             set_list("PERLDB_POST", @$post);
  1191.             set_list("PERLDB_TYPEAHEAD", @typeahead);
  1192.             $ENV{PERLDB_RESTART} = 1;
  1193.             #print "$^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS";
  1194.             exec $^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS;
  1195.             print $OUT "exec failed: $!\n";
  1196.             last CMD; };
  1197.             $cmd =~ /^T$/ && do {
  1198.             print_trace($OUT, 1); # skip DB
  1199.             next CMD; };
  1200.             $cmd =~ /^W\s*$/ && do {
  1201.             $trace &= ~2;
  1202.             @to_watch = @old_watch = ();
  1203.             next CMD; };
  1204.             $cmd =~ /^W\b\s*(.*)/s && do {
  1205.             push @to_watch, $1;
  1206.             $evalarg = $1;
  1207.             my ($val) = &eval;
  1208.             $val = (defined $val) ? "'$val'" : 'undef' ;
  1209.             push @old_watch, $val;
  1210.             $trace |= 2;
  1211.             next CMD; };
  1212.             $cmd =~ /^\/(.*)$/ && do {
  1213.             $inpat = $1;
  1214.             $inpat =~ s:([^\\])/$:$1:;
  1215.             if ($inpat ne "") {
  1216.                 # squelch the sigmangler
  1217.                 local $SIG{__DIE__};
  1218.                 local $SIG{__WARN__};
  1219.                 eval '$inpat =~ m'."\a$inpat\a";    
  1220.                 if ($@ ne "") {
  1221.                 print $OUT "$@";
  1222.                 next CMD;
  1223.                 }
  1224.                 $pat = $inpat;
  1225.             }
  1226.             $end = $start;
  1227.             $incr = -1;
  1228.             eval '
  1229.                 for (;;) {
  1230.                 ++$start;
  1231.                 $start = 1 if ($start > $max);
  1232.                 last if ($start == $end);
  1233.                 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
  1234.                     if ($slave_editor) {
  1235.                     print $OUT "\032\032$filename:$start:0\n";
  1236.                     } else {
  1237.                     print $OUT "$start:\t", $dbline[$start], "\n";
  1238.                     }
  1239.                     last;
  1240.                 }
  1241.                 } ';
  1242.             print $OUT "/$pat/: not found\n" if ($start == $end);
  1243.             next CMD; };
  1244.             $cmd =~ /^\?(.*)$/ && do {
  1245.             $inpat = $1;
  1246.             $inpat =~ s:([^\\])\?$:$1:;
  1247.             if ($inpat ne "") {
  1248.                 # squelch the sigmangler
  1249.                 local $SIG{__DIE__};
  1250.                 local $SIG{__WARN__};
  1251.                 eval '$inpat =~ m'."\a$inpat\a";    
  1252.                 if ($@ ne "") {
  1253.                 print $OUT $@;
  1254.                 next CMD;
  1255.                 }
  1256.                 $pat = $inpat;
  1257.             }
  1258.             $end = $start;
  1259.             $incr = -1;
  1260.             eval '
  1261.                 for (;;) {
  1262.                 --$start;
  1263.                 $start = $max if ($start <= 0);
  1264.                 last if ($start == $end);
  1265.                 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
  1266.                     if ($slave_editor) {
  1267.                     print $OUT "\032\032$filename:$start:0\n";
  1268.                     } else {
  1269.                     print $OUT "$start:\t", $dbline[$start], "\n";
  1270.                     }
  1271.                     last;
  1272.                 }
  1273.                 } ';
  1274.             print $OUT "?$pat?: not found\n" if ($start == $end);
  1275.             next CMD; };
  1276.             $cmd =~ /^$rc+\s*(-)?(\d+)?$/ && do {
  1277.             pop(@hist) if length($cmd) > 1;
  1278.             $i = $1 ? ($#hist-($2||1)) : ($2||$#hist);
  1279.             $cmd = $hist[$i];
  1280.             print $OUT $cmd, "\n";
  1281.             redo CMD; };
  1282.             $cmd =~ /^$sh$sh\s*([\x00-\xff]*)/ && do {
  1283.             &system($1);
  1284.             next CMD; };
  1285.             $cmd =~ /^$rc([^$rc].*)$/ && do {
  1286.             $pat = "^$1";
  1287.             pop(@hist) if length($cmd) > 1;
  1288.             for ($i = $#hist; $i; --$i) {
  1289.                 last if $hist[$i] =~ /$pat/;
  1290.             }
  1291.             if (!$i) {
  1292.                 print $OUT "No such command!\n\n";
  1293.                 next CMD;
  1294.             }
  1295.             $cmd = $hist[$i];
  1296.             print $OUT $cmd, "\n";
  1297.             redo CMD; };
  1298.             $cmd =~ /^$sh$/ && do {
  1299.             &system($ENV{SHELL}||"/bin/sh");
  1300.             next CMD; };
  1301.             $cmd =~ /^$sh\s*([\x00-\xff]*)/ && do {
  1302.             # XXX: using csh or tcsh destroys sigint retvals!
  1303.             #&system($1);  # use this instead
  1304.             &system($ENV{SHELL}||"/bin/sh","-c",$1);
  1305.             next CMD; };
  1306.             $cmd =~ /^H\b\s*(-(\d+))?/ && do {
  1307.             $end = $2 ? ($#hist-$2) : 0;
  1308.             $hist = 0 if $hist < 0;
  1309.             for ($i=$#hist; $i>$end; $i--) {
  1310.                 print $OUT "$i: ",$hist[$i],"\n"
  1311.                   unless $hist[$i] =~ /^.?$/;
  1312.             };
  1313.             next CMD; };
  1314.             $cmd =~ /^(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?$/ && do {
  1315.             runman($1);
  1316.             next CMD; };
  1317.             $cmd =~ s/^p$/print {\$DB::OUT} \$_/;
  1318.             $cmd =~ s/^p\b/print {\$DB::OUT} /;
  1319.             $cmd =~ s/^=\s*// && do {
  1320.             my @keys;
  1321.             if (length $cmd == 0) {
  1322.                 @keys = sort keys %alias;
  1323.             } 
  1324.                         elsif (my($k,$v) = ($cmd =~ /^(\S+)\s+(\S.*)/)) {
  1325.                 # can't use $_ or kill //g state
  1326.                 for my $x ($k, $v) { $x =~ s/\a/\\a/g }
  1327.                 $alias{$k} = "s\a$k\a$v\a";
  1328.                 # squelch the sigmangler
  1329.                 local $SIG{__DIE__};
  1330.                 local $SIG{__WARN__};
  1331.                 unless (eval "sub { s\a$k\a$v\a }; 1") {
  1332.                 print $OUT "Can't alias $k to $v: $@\n"; 
  1333.                 delete $alias{$k};
  1334.                 next CMD;
  1335.                 } 
  1336.                 @keys = ($k);
  1337.             } 
  1338.             else {
  1339.                 @keys = ($cmd);
  1340.             } 
  1341.             for my $k (@keys) {
  1342.                 if ((my $v = $alias{$k}) =~ ss\a$k\a(.*)\a$1) {
  1343.                 print $OUT "$k\t= $1\n";
  1344.                 } 
  1345.                 elsif (defined $alias{$k}) {
  1346.                     print $OUT "$k\t$alias{$k}\n";
  1347.                 } 
  1348.                 else {
  1349.                 print "No alias for $k\n";
  1350.                 } 
  1351.             }
  1352.             next CMD; };
  1353.             $cmd =~ /^\|\|?\s*[^|]/ && do {
  1354.             if ($pager =~ /^\|/) {
  1355.                 open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
  1356.                 open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
  1357.             } else {
  1358.                 open(SAVEOUT,">&OUT") || &warn("Can't save DB::OUT");
  1359.             }
  1360.             fix_less();
  1361.             unless ($piped=open(OUT,$pager)) {
  1362.                 &warn("Can't pipe output to `$pager'");
  1363.                 if ($pager =~ /^\|/) {
  1364.                 open(OUT,">&STDOUT") # XXX: lost message
  1365.                     || &warn("Can't restore DB::OUT");
  1366.                 open(STDOUT,">&SAVEOUT")
  1367.                   || &warn("Can't restore STDOUT");
  1368.                 close(SAVEOUT);
  1369.                 } else {
  1370.                 open(OUT,">&STDOUT") # XXX: lost message
  1371.                     || &warn("Can't restore DB::OUT");
  1372.                 }
  1373.                 next CMD;
  1374.             }
  1375.             $SIG{PIPE}= \&DB::catch if $pager =~ /^\|/
  1376.                 && ("" eq $SIG{PIPE}  ||  "DEFAULT" eq $SIG{PIPE});
  1377.             $selected= select(OUT);
  1378.             $|= 1;
  1379.             select( $selected ), $selected= "" unless $cmd =~ /^\|\|/;
  1380.             $cmd =~ s/^\|+\s*//;
  1381.             redo PIPE; 
  1382.             };
  1383.             # XXX Local variants do not work!
  1384.             $cmd =~ s/^t\s/\$DB::trace |= 1;\n/;
  1385.             $cmd =~ s/^s\s/\$DB::single = 1;\n/ && do {$laststep = 's'};
  1386.             $cmd =~ s/^n\s/\$DB::single = 2;\n/ && do {$laststep = 'n'};
  1387.         }        # PIPE:
  1388.         $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd"; &eval;
  1389.         if ($onetimeDump) {
  1390.         $onetimeDump = undef;
  1391.         } elsif ($term_pid == $$) {
  1392.         print $OUT "\n";
  1393.         }
  1394.     } continue {        # CMD:
  1395.         if ($piped) {
  1396.         if ($pager =~ /^\|/) {
  1397.             $? = 0;  
  1398.             # we cannot warn here: the handle is missing --tchrist
  1399.             close(OUT) || print SAVEOUT "\nCan't close DB::OUT\n";
  1400.  
  1401.             # most of the $? crud was coping with broken cshisms
  1402.             if ($?) {
  1403.             print SAVEOUT "Pager `$pager' failed: ";
  1404.             if ($? == -1) {
  1405.                 print SAVEOUT "shell returned -1\n";
  1406.             } elsif ($? >> 8) {
  1407.                 print SAVEOUT 
  1408.                   ( $? & 127 ) ? " (SIG#".($?&127).")" : "", 
  1409.                   ( $? & 128 ) ? " -- core dumped" : "", "\n";
  1410.             } else {
  1411.                 print SAVEOUT "status ", ($? >> 8), "\n";
  1412.             } 
  1413.             } 
  1414.  
  1415.             open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
  1416.             open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
  1417.             $SIG{PIPE} = "DEFAULT" if $SIG{PIPE} eq \&DB::catch;
  1418.             # Will stop ignoring SIGPIPE if done like nohup(1)
  1419.             # does SIGINT but Perl doesn't give us a choice.
  1420.         } else {
  1421.             open(OUT,">&SAVEOUT") || &warn("Can't restore DB::OUT");
  1422.         }
  1423.         close(SAVEOUT);
  1424.         select($selected), $selected= "" unless $selected eq "";
  1425.         $piped= "";
  1426.         }
  1427.     }            # CMD:
  1428.     $exiting = 1 unless defined $cmd;
  1429.     foreach $evalarg (@$post) {
  1430.       &eval;
  1431.     }
  1432.     }                # if ($single || $signal)
  1433.     ($@, $!, $^E, $,, $/, $\, $^W) = @saved;
  1434.     ();
  1435. }
  1436.  
  1437. # The following code may be executed now:
  1438. # BEGIN {warn 4}
  1439.  
  1440. sub sub {
  1441.     my ($al, $ret, @ret) = "";
  1442.     if (length($sub) > 10 && substr($sub, -10, 10) eq '::AUTOLOAD') {
  1443.     $al = " for $$sub";
  1444.     }
  1445.     local $stack_depth = $stack_depth + 1; # Protect from non-local exits
  1446.     $#stack = $stack_depth;
  1447.     $stack[-1] = $single;
  1448.     $single &= 1;
  1449.     $single |= 4 if $stack_depth == $deep;
  1450.     ($frame & 4 
  1451.      ? ( (print $LINEINFO ' ' x ($stack_depth - 1), "in  "), 
  1452.      # Why -1? But it works! :-(
  1453.      print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1454.      : print $LINEINFO ' ' x ($stack_depth - 1), "entering $sub$al\n") if $frame;
  1455.     if (wantarray) {
  1456.     @ret = &$sub;
  1457.     $single |= $stack[$stack_depth--];
  1458.     ($frame & 4 
  1459.      ? ( (print $LINEINFO ' ' x $stack_depth, "out "), 
  1460.          print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1461.      : print $LINEINFO ' ' x $stack_depth, "exited $sub$al\n") if $frame & 2;
  1462.     if ($doret eq $stack_depth or $frame & 16) {
  1463.             my $fh = ($doret eq $stack_depth ? $OUT : $LINEINFO);
  1464.         print $fh ' ' x $stack_depth if $frame & 16;
  1465.         print $fh "list context return from $sub:\n"; 
  1466.         dumpit($fh, \@ret );
  1467.         $doret = -2;
  1468.     }
  1469.     @ret;
  1470.     } else {
  1471.         if (defined wantarray) {
  1472.         $ret = &$sub;
  1473.         } else {
  1474.             &$sub; undef $ret;
  1475.         };
  1476.     $single |= $stack[$stack_depth--];
  1477.     ($frame & 4 
  1478.      ? ( (print $LINEINFO ' ' x $stack_depth, "out "), 
  1479.           print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1480.      : print $LINEINFO ' ' x $stack_depth, "exited $sub$al\n") if $frame & 2;
  1481.     if ($doret eq $stack_depth or $frame & 16 and defined wantarray) {
  1482.             my $fh = ($doret eq $stack_depth ? $OUT : $LINEINFO);
  1483.         print $fh (' ' x $stack_depth) if $frame & 16;
  1484.         print $fh (defined wantarray 
  1485.              ? "scalar context return from $sub: " 
  1486.              : "void context return from $sub\n");
  1487.         dumpit( $fh, $ret ) if defined wantarray;
  1488.         $doret = -2;
  1489.     }
  1490.     $ret;
  1491.     }
  1492. }
  1493.  
  1494. sub save {
  1495.     @saved = ($@, $!, $^E, $,, $/, $\, $^W);
  1496.     $, = ""; $/ = "\n"; $\ = ""; $^W = 0;
  1497. }
  1498.  
  1499. # The following takes its argument via $evalarg to preserve current @_
  1500.  
  1501. sub eval {
  1502.     # 'my' would make it visible from user code
  1503.     #    but so does local! --tchrist  
  1504.     local @res;            
  1505.     {
  1506.     local $otrace = $trace;
  1507.     local $osingle = $single;
  1508.     local $od = $^D;
  1509.     @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug
  1510.     $trace = $otrace;
  1511.     $single = $osingle;
  1512.     $^D = $od;
  1513.     }
  1514.     my $at = $@;
  1515.     local $saved[0];        # Preserve the old value of $@
  1516.     eval { &DB::save };
  1517.     if ($at) {
  1518.     print $OUT $at;
  1519.     } elsif ($onetimeDump eq 'dump') {
  1520.     dumpit($OUT, \@res);
  1521.     } elsif ($onetimeDump eq 'methods') {
  1522.     methods($res[0]);
  1523.     }
  1524.     @res;
  1525. }
  1526.  
  1527. sub postponed_sub {
  1528.   my $subname = shift;
  1529.   if ($postponed{$subname} =~ s/^break\s([+-]?\d+)\s+if\s//) {
  1530.     my $offset = $1 || 0;
  1531.     # Filename below can contain ':'
  1532.     my ($file,$i) = (find_sub($subname) =~ /^(.*):(\d+)-.*$/);
  1533.     if ($i) {
  1534.       $i += $offset;
  1535.       local *dbline = $main::{'_<' . $file};
  1536.       local $^W = 0;        # != 0 is magical below
  1537.       $had_breakpoints{$file} |= 1;
  1538.       my $max = $#dbline;
  1539.       ++$i until $dbline[$i] != 0 or $i >= $max;
  1540.       $dbline{$i} = delete $postponed{$subname};
  1541.     } else {
  1542.       print $OUT "Subroutine $subname not found.\n";
  1543.     }
  1544.     return;
  1545.   }
  1546.   elsif ($postponed{$subname} eq 'compile') { $signal = 1 }
  1547.   #print $OUT "In postponed_sub for `$subname'.\n";
  1548. }
  1549.  
  1550. sub postponed {
  1551.   if ($ImmediateStop) {
  1552.     $ImmediateStop = 0;
  1553.     $signal = 1;
  1554.   }
  1555.   return &postponed_sub
  1556.     unless ref \$_[0] eq 'GLOB'; # A subroutine is compiled.
  1557.   # Cannot be done before the file is compiled
  1558.   local *dbline = shift;
  1559.   my $filename = $dbline;
  1560.   $filename =~ s/^_<//;
  1561.   $signal = 1, print $OUT "'$filename' loaded...\n"
  1562.     if $break_on_load{$filename};
  1563.   print $LINEINFO ' ' x $stack_depth, "Package $filename.\n" if $frame;
  1564.   return unless $postponed_file{$filename};
  1565.   $had_breakpoints{$filename} |= 1;
  1566.   #%dbline = %{$postponed_file{$filename}}; # Cannot be done: unsufficient magic
  1567.   my $key;
  1568.   for $key (keys %{$postponed_file{$filename}}) {
  1569.     $dbline{$key} = ${$postponed_file{$filename}}{$key};
  1570.   }
  1571.   delete $postponed_file{$filename};
  1572. }
  1573.  
  1574. sub dumpit {
  1575.     local ($savout) = select(shift);
  1576.     my $osingle = $single;
  1577.     my $otrace = $trace;
  1578.     $single = $trace = 0;
  1579.     local $frame = 0;
  1580.     local $doret = -2;
  1581.     unless (defined &main::dumpValue) {
  1582.     do 'dumpvar.pl';
  1583.     }
  1584.     if (defined &main::dumpValue) {
  1585.     &main::dumpValue(shift);
  1586.     } else {
  1587.     print $OUT "dumpvar.pl not available.\n";
  1588.     }
  1589.     $single = $osingle;
  1590.     $trace = $otrace;
  1591.     select ($savout);    
  1592. }
  1593.  
  1594. # Tied method do not create a context, so may get wrong message:
  1595.  
  1596. sub print_trace {
  1597.   my $fh = shift;
  1598.   my @sub = dump_trace($_[0] + 1, $_[1]);
  1599.   my $short = $_[2];        # Print short report, next one for sub name
  1600.   my $s;
  1601.   for ($i=0; $i <= $#sub; $i++) {
  1602.     last if $signal;
  1603.     local $" = ', ';
  1604.     my $args = defined $sub[$i]{args} 
  1605.     ? "(@{ $sub[$i]{args} })"
  1606.       : '' ;
  1607.     $args = (substr $args, 0, $maxtrace - 3) . '...' 
  1608.       if length $args > $maxtrace;
  1609.     my $file = $sub[$i]{file};
  1610.     $file = $file eq '-e' ? $file : "file `$file'" unless $short;
  1611.     $s = $sub[$i]{sub};
  1612.     $s = (substr $s, 0, $maxtrace - 3) . '...' if length $s > $maxtrace;    
  1613.     if ($short) {
  1614.       my $sub = @_ >= 4 ? $_[3] : $s;
  1615.       print $fh "$sub[$i]{context}=$sub$args from $file:$sub[$i]{line}\n";
  1616.     } else {
  1617.       print $fh "$sub[$i]{context} = $s$args" .
  1618.     " called from $file" . 
  1619.       " line $sub[$i]{line}\n";
  1620.     }
  1621.   }
  1622. }
  1623.  
  1624. sub dump_trace {
  1625.   my $skip = shift;
  1626.   my $count = shift || 1e9;
  1627.   $skip++;
  1628.   $count += $skip;
  1629.   my ($p,$file,$line,$sub,$h,$args,$e,$r,@a,@sub,$context);
  1630.   my $nothard = not $frame & 8;
  1631.   local $frame = 0;        # Do not want to trace this.
  1632.   my $otrace = $trace;
  1633.   $trace = 0;
  1634.   for ($i = $skip; 
  1635.        $i < $count and ($p,$file,$line,$sub,$h,$context,$e,$r) = caller($i); 
  1636.        $i++) {
  1637.     @a = ();
  1638.     for $arg (@args) {
  1639.       my $type;
  1640.       if (not defined $arg) {
  1641.     push @a, "undef";
  1642.       } elsif ($nothard and tied $arg) {
  1643.     push @a, "tied";
  1644.       } elsif ($nothard and $type = ref $arg) {
  1645.     push @a, "ref($type)";
  1646.       } else {
  1647.     local $_ = "$arg";    # Safe to stringify now - should not call f().
  1648.     s/([\'\\])/\\$1/g;
  1649.     s/(.*)/'$1'/s
  1650.       unless /^(?: -?[\d.]+ | \*[\w:]* )$/x;
  1651.     s/([\200-\377])/sprintf("M-%c",ord($1)&0177)/eg;
  1652.     s/([\0-\37\177])/sprintf("^%c",ord($1)^64)/eg;
  1653.     push(@a, $_);
  1654.       }
  1655.     }
  1656.     $context = $context ? '@' : (defined $context ? "\$" : '.');
  1657.     $args = $h ? [@a] : undef;
  1658.     $e =~ s/\n\s*\;\s*\Z// if $e;
  1659.     $e =~ s/([\\\'])/\\$1/g if $e;
  1660.     if ($r) {
  1661.       $sub = "require '$e'";
  1662.     } elsif (defined $r) {
  1663.       $sub = "eval '$e'";
  1664.     } elsif ($sub eq '(eval)') {
  1665.       $sub = "eval {...}";
  1666.     }
  1667.     push(@sub, {context => $context, sub => $sub, args => $args,
  1668.         file => $file, line => $line});
  1669.     last if $signal;
  1670.   }
  1671.   $trace = $otrace;
  1672.   @sub;
  1673. }
  1674.  
  1675. sub action {
  1676.     my $action = shift;
  1677.     while ($action =~ s/\\$//) {
  1678.     #print $OUT "+ ";
  1679.     #$action .= "\n";
  1680.     $action .= &gets;
  1681.     }
  1682.     $action;
  1683. }
  1684.  
  1685. sub unbalanced { 
  1686.     # i hate using globals!
  1687.     $balanced_brace_re ||= qr{ 
  1688.     ^ \{
  1689.           (?:
  1690.          (?> [^{}] + )            # Non-parens without backtracking
  1691.            |
  1692.          (??{ $balanced_brace_re }) # Group with matching parens
  1693.           ) *
  1694.       \} $
  1695.    }x;
  1696.    return $_[0] !~ m/$balanced_brace_re/;
  1697. }
  1698.  
  1699. sub gets {
  1700.     local($.);
  1701.     #<IN>;
  1702.     &readline("cont: ");
  1703. }
  1704.  
  1705. sub system {
  1706.     # We save, change, then restore STDIN and STDOUT to avoid fork() since
  1707.     # some non-Unix systems can do system() but have problems with fork().
  1708.     open(SAVEIN,"<&STDIN") || &warn("Can't save STDIN");
  1709.     open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
  1710.     open(STDIN,"<&IN") || &warn("Can't redirect STDIN");
  1711.     open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
  1712.  
  1713.     # XXX: using csh or tcsh destroys sigint retvals!
  1714.     system(@_);
  1715.     open(STDIN,"<&SAVEIN") || &warn("Can't restore STDIN");
  1716.     open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
  1717.     close(SAVEIN); 
  1718.     close(SAVEOUT);
  1719.  
  1720.  
  1721.     # most of the $? crud was coping with broken cshisms
  1722.     if ($? >> 8) {
  1723.     &warn("(Command exited ", ($? >> 8), ")\n");
  1724.     } elsif ($?) { 
  1725.     &warn( "(Command died of SIG#",  ($? & 127),
  1726.         (($? & 128) ? " -- core dumped" : "") , ")", "\n");
  1727.     } 
  1728.  
  1729.     return $?;
  1730.  
  1731. }
  1732.  
  1733. sub setterm {
  1734.     local $frame = 0;
  1735.     local $doret = -2;
  1736.     eval { require Term::ReadLine } or die $@;
  1737.     if ($notty) {
  1738.     if ($tty) {
  1739.         open(IN,"<$tty") or die "Cannot open TTY `$TTY' for read: $!";
  1740.         open(OUT,">$tty") or die "Cannot open TTY `$TTY' for write: $!";
  1741.         $IN = \*IN;
  1742.         $OUT = \*OUT;
  1743.         my $sel = select($OUT);
  1744.         $| = 1;
  1745.         select($sel);
  1746.     } else {
  1747.         eval "require Term::Rendezvous;" or die;
  1748.         my $rv = $ENV{PERLDB_NOTTY} || "/tmp/perldbtty$$";
  1749.         my $term_rv = new Term::Rendezvous $rv;
  1750.         $IN = $term_rv->IN;
  1751.         $OUT = $term_rv->OUT;
  1752.     }
  1753.     }
  1754.     if (!$rl) {
  1755.     $term = new Term::ReadLine::Stub 'perldb', $IN, $OUT;
  1756.     } else {
  1757.     $term = new Term::ReadLine 'perldb', $IN, $OUT;
  1758.  
  1759.     $rl_attribs = $term->Attribs;
  1760.     $rl_attribs->{basic_word_break_characters} .= '-:+/*,[])}' 
  1761.       if defined $rl_attribs->{basic_word_break_characters} 
  1762.         and index($rl_attribs->{basic_word_break_characters}, ":") == -1;
  1763.     $rl_attribs->{special_prefixes} = '$@&%';
  1764.     $rl_attribs->{completer_word_break_characters} .= '$@&%';
  1765.     $rl_attribs->{completion_function} = \&db_complete; 
  1766.     }
  1767.     $LINEINFO = $OUT unless defined $LINEINFO;
  1768.     $lineinfo = $console unless defined $lineinfo;
  1769.     $term->MinLine(2);
  1770.     if ($term->Features->{setHistory} and "@hist" ne "?") {
  1771.       $term->SetHistory(@hist);
  1772.     }
  1773.     ornaments($ornaments) if defined $ornaments;
  1774.     $term_pid = $$;
  1775. }
  1776.  
  1777. sub resetterm {            # We forked, so we need a different TTY
  1778.     $term_pid = $$;
  1779.     if (defined &get_fork_TTY) {
  1780.       &get_fork_TTY;
  1781.     } elsif (not defined $fork_TTY 
  1782.          and defined $ENV{TERM} and $ENV{TERM} eq 'xterm' 
  1783.          and defined $ENV{WINDOWID} and defined $ENV{DISPLAY}) { 
  1784.         # Possibly _inside_ XTERM
  1785.         open XT, q[3>&1 xterm -title 'Forked Perl debugger' -e sh -c 'tty 1>&3;\
  1786.  sleep 10000000' |];
  1787.         $fork_TTY = <XT>;
  1788.         chomp $fork_TTY;
  1789.     }
  1790.     if (defined $fork_TTY) {
  1791.       TTY($fork_TTY);
  1792.       undef $fork_TTY;
  1793.     } else {
  1794.       print_help(<<EOP);
  1795. I<#########> Forked, but do not know how to change a B<TTY>. I<#########>
  1796.   Define B<\$DB::fork_TTY> 
  1797.        - or a function B<DB::get_fork_TTY()> which will set B<\$DB::fork_TTY>.
  1798.   The value of B<\$DB::fork_TTY> should be the name of I<TTY> to use.
  1799.   On I<UNIX>-like systems one can get the name of a I<TTY> for the given window
  1800.   by typing B<tty>, and disconnect the I<shell> from I<TTY> by B<sleep 1000000>.
  1801. EOP
  1802.     }
  1803. }
  1804.  
  1805. sub readline {
  1806.   if (@typeahead) {
  1807.     my $left = @typeahead;
  1808.     my $got = shift @typeahead;
  1809.     print $OUT "auto(-$left)", shift, $got, "\n";
  1810.     $term->AddHistory($got) 
  1811.       if length($got) > 1 and defined $term->Features->{addHistory};
  1812.     return $got;
  1813.   }
  1814.   local $frame = 0;
  1815.   local $doret = -2;
  1816.   if (ref $OUT and UNIVERSAL::isa($OUT, 'IO::Socket::INET')) {
  1817.     print $OUT @_;
  1818.     my $stuff;
  1819.     $IN->recv( $stuff, 2048 );  # XXX: what's wrong with sysread?
  1820.     $stuff;
  1821.   }
  1822.   else {
  1823.     $term->readline(@_);
  1824.   }
  1825. }
  1826.  
  1827. sub dump_option {
  1828.     my ($opt, $val)= @_;
  1829.     $val = option_val($opt,'N/A');
  1830.     $val =~ s/([\\\'])/\\$1/g;
  1831.     printf $OUT "%20s = '%s'\n", $opt, $val;
  1832. }
  1833.  
  1834. sub option_val {
  1835.     my ($opt, $default)= @_;
  1836.     my $val;
  1837.     if (defined $optionVars{$opt}
  1838.     and defined ${$optionVars{$opt}}) {
  1839.     $val = ${$optionVars{$opt}};
  1840.     } elsif (defined $optionAction{$opt}
  1841.     and defined &{$optionAction{$opt}}) {
  1842.     $val = &{$optionAction{$opt}}();
  1843.     } elsif (defined $optionAction{$opt}
  1844.          and not defined $option{$opt}
  1845.          or defined $optionVars{$opt}
  1846.          and not defined ${$optionVars{$opt}}) {
  1847.     $val = $default;
  1848.     } else {
  1849.     $val = $option{$opt};
  1850.     }
  1851.     $val
  1852. }
  1853.  
  1854. sub parse_options {
  1855.     local($_)= @_;
  1856.     # too dangerous to let intuitive usage overwrite important things
  1857.     # defaultion should never be the default
  1858.     my %opt_needs_val = map { ( $_ => 1 ) } qw{
  1859.         arrayDepth hashDepth LineInfo maxTraceLen ornaments
  1860.         pager quote ReadLine recallCommand RemotePort ShellBang TTY
  1861.     };
  1862.     while (length) {
  1863.     my $val_defaulted;
  1864.     s/^\s+// && next;
  1865.     s/^(\w+)(\W?)// or print($OUT "Invalid option `$_'\n"), last;
  1866.     my ($opt,$sep) = ($1,$2);
  1867.     my $val;
  1868.     if ("?" eq $sep) {
  1869.         print($OUT "Option query `$opt?' followed by non-space `$_'\n"), last
  1870.           if /^\S/;
  1871.         #&dump_option($opt);
  1872.     } elsif ($sep !~ /\S/) {
  1873.         $val_defaulted = 1;
  1874.         $val = "1";  #  this is an evil default; make 'em set it!
  1875.     } elsif ($sep eq "=") {
  1876.  
  1877.             if (s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x) { 
  1878.                 my $quote = $1;
  1879.                 ($val = $2) =~ s/\\([$quote\\])/$1/g;
  1880.         } else { 
  1881.         s/^(\S*)//;
  1882.         $val = $1;
  1883.         print OUT qq(Option better cleared using $opt=""\n)
  1884.             unless length $val;
  1885.         }
  1886.  
  1887.     } else { #{ to "let some poor schmuck bounce on the % key in B<vi>."
  1888.         my ($end) = "\\" . substr( ")]>}$sep", index("([<{",$sep), 1 ); #}
  1889.         s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)// or
  1890.           print($OUT "Unclosed option value `$opt$sep$_'\n"), last;
  1891.         ($val = $1) =~ s/\\([\\$end])/$1/g;
  1892.     }
  1893.  
  1894.     my $option;
  1895.     my $matches = grep( /^\Q$opt/  && ($option = $_),  @options  )
  1896.            || grep( /^\Q$opt/i && ($option = $_),  @options  );
  1897.  
  1898.     print($OUT "Unknown option `$opt'\n"), next     unless $matches;
  1899.     print($OUT "Ambiguous option `$opt'\n"), next     if $matches > 1;
  1900.  
  1901.        if ($opt_needs_val{$option} && $val_defaulted) {
  1902.         print $OUT "Option `$opt' is non-boolean.  Use `O $option=VAL' to set, `O $option?' to query\n";
  1903.         next;
  1904.     } 
  1905.  
  1906.     $option{$option} = $val if defined $val;
  1907.  
  1908.     eval qq{
  1909.         local \$frame = 0; 
  1910.         local \$doret = -2; 
  1911.             require '$optionRequire{$option}';
  1912.         1;
  1913.      } || die  # XXX: shouldn't happen
  1914.         if  defined $optionRequire{$option}        &&
  1915.             defined $val;
  1916.  
  1917.     ${$optionVars{$option}} = $val         
  1918.         if  defined $optionVars{$option}        &&
  1919.         defined $val;
  1920.  
  1921.     &{$optionAction{$option}} ($val)    
  1922.         if defined $optionAction{$option}        &&
  1923.                defined &{$optionAction{$option}}    &&
  1924.                defined $val;
  1925.  
  1926.     # Not $rcfile
  1927.     dump_option($option)     unless $OUT eq \*STDERR; 
  1928.     }
  1929. }
  1930.  
  1931. sub set_list {
  1932.   my ($stem,@list) = @_;
  1933.   my $val;
  1934.   $ENV{"${stem}_n"} = @list;
  1935.   for $i (0 .. $#list) {
  1936.     $val = $list[$i];
  1937.     $val =~ s/\\/\\\\/g;
  1938.     $val =~ s/([\0-\37\177\200-\377])/"\\0x" . unpack('H2',$1)/eg;
  1939.     $ENV{"${stem}_$i"} = $val;
  1940.   }
  1941. }
  1942.  
  1943. sub get_list {
  1944.   my $stem = shift;
  1945.   my @list;
  1946.   my $n = delete $ENV{"${stem}_n"};
  1947.   my $val;
  1948.   for $i (0 .. $n - 1) {
  1949.     $val = delete $ENV{"${stem}_$i"};
  1950.     $val =~ s/\\((\\)|0x(..))/ $2 ? $2 : pack('H2', $3) /ge;
  1951.     push @list, $val;
  1952.   }
  1953.   @list;
  1954. }
  1955.  
  1956. sub catch {
  1957.     $signal = 1;
  1958.     return;            # Put nothing on the stack - malloc/free land!
  1959. }
  1960.  
  1961. sub warn {
  1962.     my($msg)= join("",@_);
  1963.     $msg .= ": $!\n" unless $msg =~ /\n$/;
  1964.     print $OUT $msg;
  1965. }
  1966.  
  1967. sub TTY {
  1968.     if (@_ and $term and $term->Features->{newTTY}) {
  1969.       my ($in, $out) = shift;
  1970.       if ($in =~ /,/) {
  1971.     ($in, $out) = split /,/, $in, 2;
  1972.       } else {
  1973.     $out = $in;
  1974.       }
  1975.       open IN, $in or die "cannot open `$in' for read: $!";
  1976.       open OUT, ">$out" or die "cannot open `$out' for write: $!";
  1977.       $term->newTTY(\*IN, \*OUT);
  1978.       $IN    = \*IN;
  1979.       $OUT    = \*OUT;
  1980.       return $tty = $in;
  1981.     } elsif ($term and @_) {
  1982.     &warn("Too late to set TTY, enabled on next `R'!\n");
  1983.     } 
  1984.     $tty = shift if @_;
  1985.     $tty or $console;
  1986. }
  1987.  
  1988. sub noTTY {
  1989.     if ($term) {
  1990.     &warn("Too late to set noTTY, enabled on next `R'!\n") if @_;
  1991.     }
  1992.     $notty = shift if @_;
  1993.     $notty;
  1994. }
  1995.  
  1996. sub ReadLine {
  1997.     if ($term) {
  1998.     &warn("Too late to set ReadLine, enabled on next `R'!\n") if @_;
  1999.     }
  2000.     $rl = shift if @_;
  2001.     $rl;
  2002. }
  2003.  
  2004. sub RemotePort {
  2005.     if ($term) {
  2006.         &warn("Too late to set RemotePort, enabled on next 'R'!\n") if @_;
  2007.     }
  2008.     $remoteport = shift if @_;
  2009.     $remoteport;
  2010. }
  2011.  
  2012. sub tkRunning {
  2013.     if (${$term->Features}{tkRunning}) {
  2014.         return $term->tkRunning(@_);
  2015.     } else {
  2016.     print $OUT "tkRunning not supported by current ReadLine package.\n";
  2017.     0;
  2018.     }
  2019. }
  2020.  
  2021. sub NonStop {
  2022.     if ($term) {
  2023.     &warn("Too late to set up NonStop mode, enabled on next `R'!\n") if @_;
  2024.     }
  2025.     $runnonstop = shift if @_;
  2026.     $runnonstop;
  2027. }
  2028.  
  2029. sub pager {
  2030.     if (@_) {
  2031.     $pager = shift;
  2032.     $pager="|".$pager unless $pager =~ /^(\+?\>|\|)/;
  2033.     }
  2034.     $pager;
  2035. }
  2036.  
  2037. sub shellBang {
  2038.     if (@_) {
  2039.     $sh = quotemeta shift;
  2040.     $sh .= "\\b" if $sh =~ /\w$/;
  2041.     }
  2042.     $psh = $sh;
  2043.     $psh =~ s/\\b$//;
  2044.     $psh =~ s/\\(.)/$1/g;
  2045.     &sethelp;
  2046.     $psh;
  2047. }
  2048.  
  2049. sub ornaments {
  2050.   if (defined $term) {
  2051.     local ($warnLevel,$dieLevel) = (0, 1);
  2052.     return '' unless $term->Features->{ornaments};
  2053.     eval { $term->ornaments(@_) } || '';
  2054.   } else {
  2055.     $ornaments = shift;
  2056.   }
  2057. }
  2058.  
  2059. sub recallCommand {
  2060.     if (@_) {
  2061.     $rc = quotemeta shift;
  2062.     $rc .= "\\b" if $rc =~ /\w$/;
  2063.     }
  2064.     $prc = $rc;
  2065.     $prc =~ s/\\b$//;
  2066.     $prc =~ s/\\(.)/$1/g;
  2067.     &sethelp;
  2068.     $prc;
  2069. }
  2070.  
  2071. sub LineInfo {
  2072.     return $lineinfo unless @_;
  2073.     $lineinfo = shift;
  2074.     my $stream = ($lineinfo =~ /^(\+?\>|\|)/) ? $lineinfo : ">$lineinfo";
  2075.     $slave_editor = ($stream =~ /^\|/);
  2076.     open(LINEINFO, "$stream") || &warn("Cannot open `$stream' for write");
  2077.     $LINEINFO = \*LINEINFO;
  2078.     my $save = select($LINEINFO);
  2079.     $| = 1;
  2080.     select($save);
  2081.     $lineinfo;
  2082. }
  2083.  
  2084. sub list_versions {
  2085.   my %version;
  2086.   my $file;
  2087.   for (keys %INC) {
  2088.     $file = $_;
  2089.     s,\.p[lm]$,,i ;
  2090.     s,/,::,g ;
  2091.     s/^perl5db$/DB/;
  2092.     s/^Term::ReadLine::readline$/readline/;
  2093.     if (defined ${ $_ . '::VERSION' }) {
  2094.       $version{$file} = "${ $_ . '::VERSION' } from ";
  2095.     } 
  2096.     $version{$file} .= $INC{$file};
  2097.   }
  2098.   dumpit($OUT,\%version);
  2099. }
  2100.  
  2101. sub sethelp {
  2102.     # XXX: make sure these are tabs between the command and explantion,
  2103.     #      or print_help will screw up your formatting if you have
  2104.     #      eeevil ornaments enabled.  This is an insane mess.
  2105.  
  2106.     $help = "
  2107. B<T>        Stack trace.
  2108. B<s> [I<expr>]    Single step [in I<expr>].
  2109. B<n> [I<expr>]    Next, steps over subroutine calls [in I<expr>].
  2110. <B<CR>>        Repeat last B<n> or B<s> command.
  2111. B<r>        Return from current subroutine.
  2112. B<c> [I<line>|I<sub>]    Continue; optionally inserts a one-time-only breakpoint
  2113.         at the specified position.
  2114. B<l> I<min>B<+>I<incr>    List I<incr>+1 lines starting at I<min>.
  2115. B<l> I<min>B<->I<max>    List lines I<min> through I<max>.
  2116. B<l> I<line>        List single I<line>.
  2117. B<l> I<subname>    List first window of lines from subroutine.
  2118. B<l> I<\$var>        List first window of lines from subroutine referenced by I<\$var>.
  2119. B<l>        List next window of lines.
  2120. B<->        List previous window of lines.
  2121. B<w> [I<line>]    List window around I<line>.
  2122. B<.>        Return to the executed line.
  2123. B<f> I<filename>    Switch to viewing I<filename>. File must be already loaded.
  2124.         I<filename> may be either the full name of the file, or a regular
  2125.         expression matching the full file name:
  2126.         B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
  2127.         Evals (with saved bodies) are considered to be filenames:
  2128.         B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
  2129.         (in the order of execution).
  2130. B</>I<pattern>B</>    Search forwards for I<pattern>; final B</> is optional.
  2131. B<?>I<pattern>B<?>    Search backwards for I<pattern>; final B<?> is optional.
  2132. B<L>        List all breakpoints and actions.
  2133. B<S> [[B<!>]I<pattern>]    List subroutine names [not] matching I<pattern>.
  2134. B<t>        Toggle trace mode.
  2135. B<t> I<expr>        Trace through execution of I<expr>.
  2136. B<b> [I<line>] [I<condition>]
  2137.         Set breakpoint; I<line> defaults to the current execution line;
  2138.         I<condition> breaks if it evaluates to true, defaults to '1'.
  2139. B<b> I<subname> [I<condition>]
  2140.         Set breakpoint at first line of subroutine.
  2141. B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
  2142. B<b> B<load> I<filename> Set breakpoint on `require'ing the given file.
  2143. B<b> B<postpone> I<subname> [I<condition>]
  2144.         Set breakpoint at first line of subroutine after 
  2145.         it is compiled.
  2146. B<b> B<compile> I<subname>
  2147.         Stop after the subroutine is compiled.
  2148. B<d> [I<line>]    Delete the breakpoint for I<line>.
  2149. B<D>        Delete all breakpoints.
  2150. B<a> [I<line>] I<command>
  2151.         Set an action to be done before the I<line> is executed;
  2152.         I<line> defaults to the current execution line.
  2153.         Sequence is: check for breakpoint/watchpoint, print line
  2154.         if necessary, do action, prompt user if necessary,
  2155.         execute line.
  2156. B<a> [I<line>]    Delete the action for I<line>.
  2157. B<A>        Delete all actions.
  2158. B<W> I<expr>        Add a global watch-expression.
  2159. B<W>        Delete all watch-expressions.
  2160. B<V> [I<pkg> [I<vars>]]    List some (default all) variables in package (default current).
  2161.         Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
  2162. B<X> [I<vars>]    Same as \"B<V> I<currentpackage> [I<vars>]\".
  2163. B<x> I<expr>        Evals expression in array context, dumps the result.
  2164. B<m> I<expr>        Evals expression in array context, prints methods callable
  2165.         on the first element of the result.
  2166. B<m> I<class>        Prints methods callable via the given class.
  2167.  
  2168. B<<> ?            List Perl commands to run before each prompt.
  2169. B<<> I<expr>        Define Perl command to run before each prompt.
  2170. B<<<> I<expr>        Add to the list of Perl commands to run before each prompt.
  2171. B<>> ?            List Perl commands to run after each prompt.
  2172. B<>> I<expr>        Define Perl command to run after each prompt.
  2173. B<>>B<>> I<expr>        Add to the list of Perl commands to run after each prompt.
  2174. B<{> I<db_command>    Define debugger command to run before each prompt.
  2175. B<{> ?            List debugger commands to run before each prompt.
  2176. B<<> I<expr>        Define Perl command to run before each prompt.
  2177. B<{{> I<db_command>    Add to the list of debugger commands to run before each prompt.
  2178. B<$prc> I<number>    Redo a previous command (default previous command).
  2179. B<$prc> I<-number>    Redo number'th-to-last command.
  2180. B<$prc> I<pattern>    Redo last command that started with I<pattern>.
  2181.         See 'B<O> I<recallCommand>' too.
  2182. B<$psh$psh> I<cmd>      Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
  2183.   . ( $rc eq $sh ? "" : "
  2184. B<$psh> [I<cmd>]     Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")." ) . "
  2185.         See 'B<O> I<shellBang>' too.
  2186. B<H> I<-number>    Display last number commands (default all).
  2187. B<p> I<expr>        Same as \"I<print {DB::OUT} expr>\" in current package.
  2188. B<|>I<dbcmd>        Run debugger command, piping DB::OUT to current pager.
  2189. B<||>I<dbcmd>        Same as B<|>I<dbcmd> but DB::OUT is temporarilly select()ed as well.
  2190. B<\=> [I<alias> I<value>]    Define a command alias, or list current aliases.
  2191. I<command>        Execute as a perl statement in current package.
  2192. B<v>        Show versions of loaded modules.
  2193. B<R>        Pure-man-restart of debugger, some of debugger state
  2194.         and command-line options may be lost.
  2195.         Currently the following setting are preserved: 
  2196.         history, breakpoints and actions, debugger B<O>ptions 
  2197.         and the following command-line options: I<-w>, I<-I>, I<-e>.
  2198.  
  2199. B<O> [I<opt>] ...    Set boolean option to true
  2200. B<O> [I<opt>B<?>]    Query options
  2201. B<O> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ... 
  2202.         Set options.  Use quotes in spaces in value.
  2203.     I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
  2204.     I<pager>            program for output of \"|cmd\";
  2205.     I<tkRunning>            run Tk while prompting (with ReadLine);
  2206.     I<signalLevel> I<warnLevel> I<dieLevel>    level of verbosity;
  2207.     I<inhibit_exit>        Allows stepping off the end of the script.
  2208.     I<ImmediateStop>        Debugger should stop as early as possible.
  2209.     I<RemotePort>            Remote hostname:port for remote debugging
  2210.   The following options affect what happens with B<V>, B<X>, and B<x> commands:
  2211.     I<arrayDepth>, I<hashDepth>     print only first N elements ('' for all);
  2212.     I<compactDump>, I<veryCompact>     change style of array and hash dump;
  2213.     I<globPrint>             whether to print contents of globs;
  2214.     I<DumpDBFiles>         dump arrays holding debugged files;
  2215.     I<DumpPackages>         dump symbol tables of packages;
  2216.     I<DumpReused>             dump contents of \"reused\" addresses;
  2217.     I<quote>, I<HighBit>, I<undefPrint>     change style of string dump;
  2218.     I<bareStringify>         Do not print the overload-stringified value;
  2219.   Other options include:
  2220.     I<PrintRet>        affects printing of return value after B<r> command,
  2221.     I<frame>        affects printing messages on entry and exit from subroutines.
  2222.     I<AutoTrace>    affects printing messages on every possible breaking point.
  2223.     I<maxTraceLen>    gives maximal length of evals/args listed in stack trace.
  2224.     I<ornaments>     affects screen appearance of the command line.
  2225.     During startup options are initialized from \$ENV{PERLDB_OPTS}.
  2226.     You can put additional initialization options I<TTY>, I<noTTY>,
  2227.     I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
  2228.     `B<R>' after you set them).
  2229.  
  2230. B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction.
  2231. B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
  2232. B<h h>        Summary of debugger commands.
  2233. B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the 
  2234.         named Perl I<manpage>, or on B<$doccmd> itself if omitted.
  2235.         Set B<\$DB::doccmd> to change viewer.
  2236.  
  2237. Type `|h' for a paged display if this was too hard to read.
  2238.  
  2239. "; # Fix balance of vi % matching: } }}
  2240.  
  2241.     $summary = <<"END_SUM";
  2242. I<List/search source lines:>               I<Control script execution:>
  2243.   B<l> [I<ln>|I<sub>]  List source code            B<T>           Stack trace
  2244.   B<-> or B<.>      List previous/current line  B<s> [I<expr>]    Single step [in expr]
  2245.   B<w> [I<line>]    List around line            B<n> [I<expr>]    Next, steps over subs
  2246.   B<f> I<filename>  View source in file         <B<CR>/B<Enter>>  Repeat last B<n> or B<s>
  2247.   B</>I<pattern>B</> B<?>I<patt>B<?>   Search forw/backw    B<r>           Return from subroutine
  2248.   B<v>          Show versions of modules    B<c> [I<ln>|I<sub>]  Continue until position
  2249. I<Debugger controls:>                        B<L>           List break/watch/actions
  2250.   B<O> [...]     Set debugger options        B<t> [I<expr>]    Toggle trace [trace expr]
  2251.   B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
  2252.   B<$prc> [I<N>|I<pat>]   Redo a previous command     B<d> [I<ln>] or B<D> Delete a/all breakpoints
  2253.   B<H> [I<-num>]    Display last num commands   B<a> [I<ln>] I<cmd>  Do cmd before line
  2254.   B<=> [I<a> I<val>]   Define/list an alias        B<W> I<expr>      Add a watch expression
  2255.   B<h> [I<db_cmd>]  Get help on command         B<A> or B<W>      Delete all actions/watch
  2256.   B<|>[B<|>]I<db_cmd>  Send output to pager        B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
  2257.   B<q> or B<^D>     Quit              B<R>          Attempt a restart
  2258. I<Data Examination:>          B<expr>     Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
  2259.   B<x>|B<m> I<expr>    Evals expr in array context, dumps the result or lists methods.
  2260.   B<p> I<expr>    Print expression (uses script's current package).
  2261.   B<S> [[B<!>]I<pat>]    List subroutine names [not] matching pattern
  2262.   B<V> [I<Pk> [I<Vars>]]    List Variables in Package.  Vars can be ~pattern or !pattern.
  2263.   B<X> [I<Vars>]    Same as \"B<V> I<current_package> [I<Vars>]\".
  2264. For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
  2265. END_SUM
  2266.                 # ')}}; # Fix balance of vi % matching
  2267. }
  2268.  
  2269. sub print_help {
  2270.     local $_ = shift;
  2271.  
  2272.     # Restore proper alignment destroyed by eeevil I<> and B<>
  2273.     # ornaments: A pox on both their houses!
  2274.     #
  2275.     # A help command will have everything up to and including
  2276.     # the first tab sequence paddeed into a field 16 (or if indented 20)
  2277.     # wide.  If it's wide than that, an extra space will be added.
  2278.     s{
  2279.     ^                 # only matters at start of line
  2280.       ( \040{4} | \t )*    # some subcommands are indented
  2281.       ( < ?         # so <CR> works
  2282.         [BI] < [^\t\n] + )  # find an eeevil ornament
  2283.       ( \t+ )        # original separation, discarded
  2284.       ( .* )        # this will now start (no earlier) than 
  2285.                 # column 16
  2286.     } {
  2287.     my($leadwhite, $command, $midwhite, $text) = ($1, $2, $3, $4);
  2288.     my $clean = $command;
  2289.     $clean =~ s/[BI]<([^>]*)>/$1/g;  
  2290.     # replace with this whole string:
  2291.     (length($leadwhite) ? " " x 4 : "")
  2292.       . $command
  2293.       . ((" " x (16 + (length($leadwhite) ? 4 : 0) - length($clean))) || " ")
  2294.       . $text;
  2295.  
  2296.     }mgex;
  2297.  
  2298.     s{                # handle bold ornaments
  2299.     B < ( [^>] + | > ) >
  2300.     } {
  2301.       $Term::ReadLine::TermCap::rl_term_set[2] 
  2302.     . $1
  2303.     . $Term::ReadLine::TermCap::rl_term_set[3]
  2304.     }gex;
  2305.  
  2306.     s{                # handle italic ornaments
  2307.     I < ( [^>] + | > ) >
  2308.     } {
  2309.       $Term::ReadLine::TermCap::rl_term_set[0] 
  2310.     . $1
  2311.     . $Term::ReadLine::TermCap::rl_term_set[1]
  2312.     }gex;
  2313.  
  2314.     print $OUT $_;
  2315. }
  2316.  
  2317. sub fix_less {
  2318.     return if defined $ENV{LESS} && $ENV{LESS} =~ /r/;
  2319.     my $is_less = $pager =~ /\bless\b/;
  2320.     if ($pager =~ /\bmore\b/) { 
  2321.     my @st_more = stat('/usr/bin/more');
  2322.     my @st_less = stat('/usr/bin/less');
  2323.     $is_less = @st_more    && @st_less 
  2324.         && $st_more[0] == $st_less[0] 
  2325.         && $st_more[1] == $st_less[1];
  2326.     }
  2327.     # changes environment!
  2328.     $ENV{LESS} .= 'r'     if $is_less;
  2329. }
  2330.  
  2331. sub diesignal {
  2332.     local $frame = 0;
  2333.     local $doret = -2;
  2334.     $SIG{'ABRT'} = 'DEFAULT';
  2335.     kill 'ABRT', $$ if $panic++;
  2336.     if (defined &Carp::longmess) {
  2337.     local $SIG{__WARN__} = '';
  2338.     local $Carp::CarpLevel = 2;        # mydie + confess
  2339.     &warn(Carp::longmess("Signal @_"));
  2340.     }
  2341.     else {
  2342.     print $DB::OUT "Got signal @_\n";
  2343.     }
  2344.     kill 'ABRT', $$;
  2345. }
  2346.  
  2347. sub dbwarn { 
  2348.   local $frame = 0;
  2349.   local $doret = -2;
  2350.   local $SIG{__WARN__} = '';
  2351.   local $SIG{__DIE__} = '';
  2352.   eval { require Carp } if defined $^S;    # If error/warning during compilation,
  2353.                                         # require may be broken.
  2354.   warn(@_, "\nCannot print stack trace, load with -MCarp option to see stack"),
  2355.     return unless defined &Carp::longmess;
  2356.   my ($mysingle,$mytrace) = ($single,$trace);
  2357.   $single = 0; $trace = 0;
  2358.   my $mess = Carp::longmess(@_);
  2359.   ($single,$trace) = ($mysingle,$mytrace);
  2360.   &warn($mess); 
  2361. }
  2362.  
  2363. sub dbdie {
  2364.   local $frame = 0;
  2365.   local $doret = -2;
  2366.   local $SIG{__DIE__} = '';
  2367.   local $SIG{__WARN__} = '';
  2368.   my $i = 0; my $ineval = 0; my $sub;
  2369.   if ($dieLevel > 2) {
  2370.       local $SIG{__WARN__} = \&dbwarn;
  2371.       &warn(@_);        # Yell no matter what
  2372.       return;
  2373.   }
  2374.   if ($dieLevel < 2) {
  2375.     die @_ if $^S;        # in eval propagate
  2376.   }
  2377.   eval { require Carp } if defined $^S;    # If error/warning during compilation,
  2378.                                     # require may be broken.
  2379.  
  2380.   die(@_, "\nCannot print stack trace, load with -MCarp option to see stack")
  2381.     unless defined &Carp::longmess;
  2382.  
  2383.   # We do not want to debug this chunk (automatic disabling works
  2384.   # inside DB::DB, but not in Carp).
  2385.   my ($mysingle,$mytrace) = ($single,$trace);
  2386.   $single = 0; $trace = 0;
  2387.   my $mess = Carp::longmess(@_);
  2388.   ($single,$trace) = ($mysingle,$mytrace);
  2389.   die $mess;
  2390. }
  2391.  
  2392. sub warnLevel {
  2393.   if (@_) {
  2394.     $prevwarn = $SIG{__WARN__} unless $warnLevel;
  2395.     $warnLevel = shift;
  2396.     if ($warnLevel) {
  2397.       $SIG{__WARN__} = \&DB::dbwarn;
  2398.     } else {
  2399.       $SIG{__WARN__} = $prevwarn;
  2400.     }
  2401.   }
  2402.   $warnLevel;
  2403. }
  2404.  
  2405. sub dieLevel {
  2406.   if (@_) {
  2407.     $prevdie = $SIG{__DIE__} unless $dieLevel;
  2408.     $dieLevel = shift;
  2409.     if ($dieLevel) {
  2410.       $SIG{__DIE__} = \&DB::dbdie; # if $dieLevel < 2;
  2411.       #$SIG{__DIE__} = \&DB::diehard if $dieLevel >= 2;
  2412.       print $OUT "Stack dump during die enabled", 
  2413.         ( $dieLevel == 1 ? " outside of evals" : ""), ".\n"
  2414.       if $I_m_init;
  2415.       print $OUT "Dump printed too.\n" if $dieLevel > 2;
  2416.     } else {
  2417.       $SIG{__DIE__} = $prevdie;
  2418.       print $OUT "Default die handler restored.\n";
  2419.     }
  2420.   }
  2421.   $dieLevel;
  2422. }
  2423.  
  2424. sub signalLevel {
  2425.   if (@_) {
  2426.     $prevsegv = $SIG{SEGV} unless $signalLevel;
  2427.     $prevbus = $SIG{BUS} unless $signalLevel;
  2428.     $signalLevel = shift;
  2429.     if ($signalLevel) {
  2430.       $SIG{SEGV} = \&DB::diesignal;
  2431.       $SIG{BUS} = \&DB::diesignal;
  2432.     } else {
  2433.       $SIG{SEGV} = $prevsegv;
  2434.       $SIG{BUS} = $prevbus;
  2435.     }
  2436.   }
  2437.   $signalLevel;
  2438. }
  2439.  
  2440. sub CvGV_name {
  2441.   my $in = shift;
  2442.   my $name = CvGV_name_or_bust($in);
  2443.   defined $name ? $name : $in;
  2444. }
  2445.  
  2446. sub CvGV_name_or_bust {
  2447.   my $in = shift;
  2448.   return if $skipCvGV;        # Backdoor to avoid problems if XS broken...
  2449.   $in = \&$in;            # Hard reference...
  2450.   eval {require Devel::Peek; 1} or return;
  2451.   my $gv = Devel::Peek::CvGV($in) or return;
  2452.   *$gv{PACKAGE} . '::' . *$gv{NAME};
  2453. }
  2454.  
  2455. sub find_sub {
  2456.   my $subr = shift;
  2457.   $sub{$subr} or do {
  2458.     return unless defined &$subr;
  2459.     my $name = CvGV_name_or_bust($subr);
  2460.     my $data;
  2461.     $data = $sub{$name} if defined $name;
  2462.     return $data if defined $data;
  2463.  
  2464.     # Old stupid way...
  2465.     $subr = \&$subr;        # Hard reference
  2466.     my $s;
  2467.     for (keys %sub) {
  2468.       $s = $_, last if $subr eq \&$_;
  2469.     }
  2470.     $sub{$s} if $s;
  2471.   }
  2472. }
  2473.  
  2474. sub methods {
  2475.   my $class = shift;
  2476.   $class = ref $class if ref $class;
  2477.   local %seen;
  2478.   local %packs;
  2479.   methods_via($class, '', 1);
  2480.   methods_via('UNIVERSAL', 'UNIVERSAL', 0);
  2481. }
  2482.  
  2483. sub methods_via {
  2484.   my $class = shift;
  2485.   return if $packs{$class}++;
  2486.   my $prefix = shift;
  2487.   my $prepend = $prefix ? "via $prefix: " : '';
  2488.   my $name;
  2489.   for $name (grep {defined &{${"${class}::"}{$_}}} 
  2490.          sort keys %{"${class}::"}) {
  2491.     next if $seen{ $name }++;
  2492.     print $DB::OUT "$prepend$name\n";
  2493.   }
  2494.   return unless shift;        # Recurse?
  2495.   for $name (@{"${class}::ISA"}) {
  2496.     $prepend = $prefix ? $prefix . " -> $name" : $name;
  2497.     methods_via($name, $prepend, 1);
  2498.   }
  2499. }
  2500.  
  2501. sub setman { 
  2502.     $doccmd = $^O !~ /^(?:MSWin32|VMS|os2|dos|amigaos|riscos|MacOS)\z/s
  2503.         ? "man"             # O Happy Day!
  2504.         : "perldoc";        # Alas, poor unfortunates
  2505. }
  2506.  
  2507. sub runman {
  2508.     my $page = shift;
  2509.     unless ($page) {
  2510.     &system("$doccmd $doccmd");
  2511.     return;
  2512.     } 
  2513.     # this way user can override, like with $doccmd="man -Mwhatever"
  2514.     # or even just "man " to disable the path check.
  2515.     unless ($doccmd eq 'man') {
  2516.     &system("$doccmd $page");
  2517.     return;
  2518.     } 
  2519.  
  2520.     $page = 'perl' if lc($page) eq 'help';
  2521.  
  2522.     require Config;
  2523.     my $man1dir = $Config::Config{'man1dir'};
  2524.     my $man3dir = $Config::Config{'man3dir'};
  2525.     for ($man1dir, $man3dir) { s#/[^/]*\z## if /\S/ } 
  2526.     my $manpath = '';
  2527.     $manpath .= "$man1dir:" if $man1dir =~ /\S/;
  2528.     $manpath .= "$man3dir:" if $man3dir =~ /\S/ && $man1dir ne $man3dir;
  2529.     chop $manpath if $manpath;
  2530.     # harmless if missing, I figure
  2531.     my $oldpath = $ENV{MANPATH};
  2532.     $ENV{MANPATH} = $manpath if $manpath;
  2533.     my $nopathopt = $^O =~ /dunno what goes here/;
  2534.     if (system($doccmd, 
  2535.         # I just *know* there are men without -M
  2536.         (($manpath && !$nopathopt) ? ("-M", $manpath) : ()),  
  2537.         split ' ', $page) )
  2538.     {
  2539.     unless ($page =~ /^perl\w/) {
  2540.         if (grep { $page eq $_ } qw{ 
  2541.         5004delta 5005delta amiga api apio book boot bot call compile
  2542.         cygwin data dbmfilter debug debguts delta diag doc dos dsc embed
  2543.         faq faq1 faq2 faq3 faq4 faq5 faq6 faq7 faq8 faq9 filter fork
  2544.         form func guts hack hist hpux intern ipc lexwarn locale lol mod
  2545.         modinstall modlib number obj op opentut os2 os390 pod port 
  2546.         ref reftut run sec style sub syn thrtut tie toc todo toot tootc
  2547.         trap unicode var vms win32 xs xstut
  2548.           }) 
  2549.         {
  2550.         $page =~ s/^/perl/;
  2551.         system($doccmd, 
  2552.             (($manpath && !$nopathopt) ? ("-M", $manpath) : ()),  
  2553.             $page);
  2554.         }
  2555.     }
  2556.     } 
  2557.     if (defined $oldpath) {
  2558.     $ENV{MANPATH} = $manpath;
  2559.     } else {
  2560.     delete $ENV{MANPATH};
  2561.     } 
  2562.  
  2563. # The following BEGIN is very handy if debugger goes havoc, debugging debugger?
  2564.  
  2565. BEGIN {            # This does not compile, alas.
  2566.   $IN = \*STDIN;        # For bugs before DB::OUT has been opened
  2567.   $OUT = \*STDERR;        # For errors before DB::OUT has been opened
  2568.   $sh = '!';
  2569.   $rc = ',';
  2570.   @hist = ('?');
  2571.   $deep = 100;            # warning if stack gets this deep
  2572.   $window = 10;
  2573.   $preview = 3;
  2574.   $sub = '';
  2575.   $SIG{INT} = \&DB::catch;
  2576.   # This may be enabled to debug debugger:
  2577.   #$warnLevel = 1 unless defined $warnLevel;
  2578.   #$dieLevel = 1 unless defined $dieLevel;
  2579.   #$signalLevel = 1 unless defined $signalLevel;
  2580.  
  2581.   $db_stop = 0;            # Compiler warning
  2582.   $db_stop = 1 << 30;
  2583.   $level = 0;            # Level of recursive debugging
  2584.   # @stack and $doret are needed in sub sub, which is called for DB::postponed.
  2585.   # Triggers bug (?) in perl is we postpone this until runtime:
  2586.   @postponed = @stack = (0);
  2587.   $stack_depth = 0;        # Localized $#stack
  2588.   $doret = -2;
  2589.   $frame = 0;
  2590. }
  2591.  
  2592. BEGIN {$^W = $ini_warn;}    # Switch warnings back
  2593.  
  2594. #use Carp;            # This did break, left for debuggin
  2595.  
  2596. sub db_complete {
  2597.   # Specific code for b c l V m f O, &blah, $blah, @blah, %blah
  2598.   my($text, $line, $start) = @_;
  2599.   my ($itext, $search, $prefix, $pack) =
  2600.     ($text, "^\Q${'package'}::\E([^:]+)\$");
  2601.   
  2602.   return sort grep /^\Q$text/, (keys %sub), qw(postpone load compile), # subroutines
  2603.                                (map { /$search/ ? ($1) : () } keys %sub)
  2604.     if (substr $line, 0, $start) =~ /^\|*[blc]\s+((postpone|compile)\s+)?$/;
  2605.   return sort grep /^\Q$text/, values %INC # files
  2606.     if (substr $line, 0, $start) =~ /^\|*b\s+load\s+$/;
  2607.   return sort map {($_, db_complete($_ . "::", "V ", 2))}
  2608.     grep /^\Q$text/, map { /^(.*)::$/ ? ($1) : ()} keys %:: # top-packages
  2609.       if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/ and $text =~ /^\w*$/;
  2610.   return sort map {($_, db_complete($_ . "::", "V ", 2))}
  2611.     grep !/^main::/,
  2612.       grep /^\Q$text/, map { /^(.*)::$/ ? ($prefix . "::$1") : ()} keys %{$prefix . '::'}
  2613.                  # packages
  2614.     if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/ 
  2615.       and $text =~ /^(.*[^:])::?(\w*)$/  and $prefix = $1;
  2616.   if ( $line =~ /^\|*f\s+(.*)/ ) { # Loaded files
  2617.     # We may want to complete to (eval 9), so $text may be wrong
  2618.     $prefix = length($1) - length($text);
  2619.     $text = $1;
  2620.     return sort 
  2621.     map {substr $_, 2 + $prefix} grep /^_<\Q$text/, (keys %main::), $0
  2622.   }
  2623.   if ((substr $text, 0, 1) eq '&') { # subroutines
  2624.     $text = substr $text, 1;
  2625.     $prefix = "&";
  2626.     return sort map "$prefix$_", 
  2627.                grep /^\Q$text/, 
  2628.                  (keys %sub),
  2629.                  (map { /$search/ ? ($1) : () } 
  2630.             keys %sub);
  2631.   }
  2632.   if ($text =~ /^[\$@%](.*)::(.*)/) { # symbols in a package
  2633.     $pack = ($1 eq 'main' ? '' : $1) . '::';
  2634.     $prefix = (substr $text, 0, 1) . $1 . '::';
  2635.     $text = $2;
  2636.     my @out 
  2637.       = map "$prefix$_", grep /^\Q$text/, grep /^_?[a-zA-Z]/, keys %$pack ;
  2638.     if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
  2639.       return db_complete($out[0], $line, $start);
  2640.     }
  2641.     return sort @out;
  2642.   }
  2643.   if ($text =~ /^[\$@%]/) { # symbols (in $package + packages in main)
  2644.     $pack = ($package eq 'main' ? '' : $package) . '::';
  2645.     $prefix = substr $text, 0, 1;
  2646.     $text = substr $text, 1;
  2647.     my @out = map "$prefix$_", grep /^\Q$text/, 
  2648.        (grep /^_?[a-zA-Z]/, keys %$pack), 
  2649.        ( $pack eq '::' ? () : (grep /::$/, keys %::) ) ;
  2650.     if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
  2651.       return db_complete($out[0], $line, $start);
  2652.     }
  2653.     return sort @out;
  2654.   }
  2655.   if ((substr $line, 0, $start) =~ /^\|*O\b.*\s$/) { # Options after a space
  2656.     my @out = grep /^\Q$text/, @options;
  2657.     my $val = option_val($out[0], undef);
  2658.     my $out = '? ';
  2659.     if (not defined $val or $val =~ /[\n\r]/) {
  2660.       # Can do nothing better
  2661.     } elsif ($val =~ /\s/) {
  2662.       my $found;
  2663.       foreach $l (split //, qq/\"\'\#\|/) {
  2664.     $out = "$l$val$l ", last if (index $val, $l) == -1;
  2665.       }
  2666.     } else {
  2667.       $out = "=$val ";
  2668.     }
  2669.     # Default to value if one completion, to question if many
  2670.     $rl_attribs->{completer_terminator_character} = (@out == 1 ? $out : '? ');
  2671.     return sort @out;
  2672.   }
  2673.   return $term->filename_list($text); # filenames
  2674. }
  2675.  
  2676. sub end_report {
  2677.   print $OUT "Use `q' to quit or `R' to restart.  `h q' for details.\n"
  2678. }
  2679.  
  2680. END {
  2681.   $finished = $inhibit_exit;    # So that some keys may be disabled.
  2682.   # Do not stop in at_exit() and destructors on exit:
  2683.   $DB::single = !$exiting && !$runnonstop;
  2684.   DB::fake::at_exit() unless $exiting or $runnonstop;
  2685. }
  2686.  
  2687. package DB::fake;
  2688.  
  2689. sub at_exit {
  2690.   "Debugged program terminated.  Use `q' to quit or `R' to restart.";
  2691. }
  2692.  
  2693. package DB;            # Do not trace this 1; below!
  2694.  
  2695. 1;
  2696.