home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 March / PCWorld_2003-03_cd.bin / Software / Topware / activeperl / ActivePerl / Perl / lib / perl5db.pl < prev    next >
Encoding:
Perl Script  |  2002-06-19  |  118.8 KB  |  3,592 lines

  1. package DB;
  2.  
  3. # Debugger for Perl 5.00x; perl5db.pl patch level:
  4. $VERSION = 1.19;
  5. $header  = "perl5db.pl version $VERSION";
  6.  
  7. # It is crucial that there is no lexicals in scope of `eval ""' down below
  8. sub eval {
  9.     # 'my' would make it visible from user code
  10.     #    but so does local! --tchrist  [... into @DB::res, not @res. IZ]
  11.     local @res;
  12.     {
  13.     local $otrace = $trace;
  14.     local $osingle = $single;
  15.     local $od = $^D;
  16.     { ($evalarg) = $evalarg =~ /(.*)/s; }
  17.     @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug
  18.     $trace = $otrace;
  19.     $single = $osingle;
  20.     $^D = $od;
  21.     }
  22.     my $at = $@;
  23.     local $saved[0];        # Preserve the old value of $@
  24.     eval { &DB::save };
  25.     if ($at) {
  26.     local $\ = '';
  27.     print $OUT $at;
  28.     } elsif ($onetimeDump) {
  29.       if ($onetimeDump eq 'dump')  {
  30.         local $option{dumpDepth} = $onetimedumpDepth 
  31.           if defined $onetimedumpDepth;
  32.     dumpit($OUT, \@res);
  33.       } elsif ($onetimeDump eq 'methods') {
  34.     methods($res[0]) ;
  35.       }
  36.     }
  37.     @res;
  38. }
  39.  
  40. # After this point it is safe to introduce lexicals
  41. # However, one should not overdo it: leave as much control from outside as possible
  42. #
  43. # This file is automatically included if you do perl -d.
  44. # It's probably not useful to include this yourself.
  45. #
  46. # Before venturing further into these twisty passages, it is 
  47. # wise to read the perldebguts man page or risk the ire of dragons.
  48. #
  49. # Perl supplies the values for %sub.  It effectively inserts
  50. # a &DB::DB(); in front of every place that can have a
  51. # breakpoint. Instead of a subroutine call it calls &DB::sub with
  52. # $DB::sub being the called subroutine. It also inserts a BEGIN
  53. # {require 'perl5db.pl'} before the first line.
  54. #
  55. # After each `require'd file is compiled, but before it is executed, a
  56. # call to DB::postponed($main::{'_<'.$filename}) is emulated. Here the
  57. # $filename is the expanded name of the `require'd file (as found as
  58. # value of %INC).
  59. #
  60. # Additional services from Perl interpreter:
  61. #
  62. # if caller() is called from the package DB, it provides some
  63. # additional data.
  64. #
  65. # The array @{$main::{'_<'.$filename}} (herein called @dbline) is the
  66. # line-by-line contents of $filename.
  67. #
  68. # The hash %{'_<'.$filename} (herein called %dbline) contains
  69. # breakpoints and action (it is keyed by line number), and individual
  70. # entries are settable (as opposed to the whole hash). Only true/false
  71. # is important to the interpreter, though the values used by
  72. # perl5db.pl have the form "$break_condition\0$action". Values are
  73. # magical in numeric context.
  74. #
  75. # The scalar ${'_<'.$filename} contains $filename.
  76. #
  77. # Note that no subroutine call is possible until &DB::sub is defined
  78. # (for subroutines defined outside of the package DB). In fact the same is
  79. # true if $deep is not defined.
  80. #
  81. # $Log:    perldb.pl,v $
  82.  
  83. #
  84. # At start reads $rcfile that may set important options.  This file
  85. # may define a subroutine &afterinit that will be executed after the
  86. # debugger is initialized.
  87. #
  88. # After $rcfile is read reads environment variable PERLDB_OPTS and parses
  89. # it as a rest of `O ...' line in debugger prompt.
  90. #
  91. # The options that can be specified only at startup:
  92. # [To set in $rcfile, call &parse_options("optionName=new_value").]
  93. #
  94. # TTY  - the TTY to use for debugging i/o.
  95. #
  96. # noTTY - if set, goes in NonStop mode.  On interrupt if TTY is not set
  97. # uses the value of noTTY or "/tmp/perldbtty$$" to find TTY using
  98. # Term::Rendezvous.  Current variant is to have the name of TTY in this
  99. # file.
  100. #
  101. # ReadLine - If false, dummy ReadLine is used, so you can debug
  102. # ReadLine applications.
  103. #
  104. # NonStop - if true, no i/o is performed until interrupt.
  105. #
  106. # LineInfo - file or pipe to print line number info to.  If it is a
  107. # pipe, a short "emacs like" message is used.
  108. #
  109. # RemotePort - host:port to connect to on remote host for remote debugging.
  110. #
  111. # Example $rcfile: (delete leading hashes!)
  112. #
  113. # &parse_options("NonStop=1 LineInfo=db.out");
  114. # sub afterinit { $trace = 1; }
  115. #
  116. # The script will run without human intervention, putting trace
  117. # information into db.out.  (If you interrupt it, you would better
  118. # reset LineInfo to something "interactive"!)
  119. #
  120. ##################################################################
  121.  
  122. # Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich)
  123.  
  124. # modified Perl debugger, to be run from Emacs in perldb-mode
  125. # Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990
  126. # Johan Vromans -- upgrade to 4.0 pl 10
  127. # Ilya Zakharevich -- patches after 5.001 (and some before ;-)
  128.  
  129. # Changelog:
  130.  
  131. # A lot of things changed after 0.94. First of all, core now informs
  132. # debugger about entry into XSUBs, overloaded operators, tied operations,
  133. # BEGIN and END. Handy with `O f=2'.
  134.  
  135. # This can make debugger a little bit too verbose, please be patient
  136. # and report your problems promptly.
  137.  
  138. # Now the option frame has 3 values: 0,1,2.
  139.  
  140. # Note that if DESTROY returns a reference to the object (or object),
  141. # the deletion of data may be postponed until the next function call,
  142. # due to the need to examine the return value.
  143.  
  144. # Changes: 0.95: `v' command shows versions.
  145. # Changes: 0.96: `v' command shows version of readline.
  146. #    primitive completion works (dynamic variables, subs for `b' and `l',
  147. #        options). Can `p %var'
  148. #    Better help (`h <' now works). New commands <<, >>, {, {{.
  149. #    {dump|print}_trace() coded (to be able to do it from <<cmd).
  150. #    `c sub' documented.
  151. #    At last enough magic combined to stop after the end of debuggee.
  152. #    !! should work now (thanks to Emacs bracket matching an extra
  153. #    `]' in a regexp is caught).
  154. #    `L', `D' and `A' span files now (as documented).
  155. #    Breakpoints in `require'd code are possible (used in `R').
  156. #    Some additional words on internal work of debugger.
  157. #    `b load filename' implemented.
  158. #    `b postpone subr' implemented.
  159. #    now only `q' exits debugger (overwritable on $inhibit_exit).
  160. #    When restarting debugger breakpoints/actions persist.
  161. #     Buglet: When restarting debugger only one breakpoint/action per 
  162. #        autoloaded function persists.
  163. # Changes: 0.97: NonStop will not stop in at_exit().
  164. #    Option AutoTrace implemented.
  165. #    Trace printed differently if frames are printed too.
  166. #    new `inhibitExit' option.
  167. #    printing of a very long statement interruptible.
  168. # Changes: 0.98: New command `m' for printing possible methods
  169. #    'l -' is a synonym for `-'.
  170. #    Cosmetic bugs in printing stack trace.
  171. #    `frame' & 8 to print "expanded args" in stack trace.
  172. #    Can list/break in imported subs.
  173. #    new `maxTraceLen' option.
  174. #    frame & 4 and frame & 8 granted.
  175. #    new command `m'
  176. #    nonstoppable lines do not have `:' near the line number.
  177. #    `b compile subname' implemented.
  178. #    Will not use $` any more.
  179. #    `-' behaves sane now.
  180. # Changes: 0.99: Completion for `f', `m'.
  181. #    `m' will remove duplicate names instead of duplicate functions.
  182. #    `b load' strips trailing whitespace.
  183. #    completion ignores leading `|'; takes into account current package
  184. #    when completing a subroutine name (same for `l').
  185. # Changes: 1.07: Many fixed by tchrist 13-March-2000
  186. #   BUG FIXES:
  187. #   + Added bare minimal security checks on perldb rc files, plus
  188. #     comments on what else is needed.
  189. #   + Fixed the ornaments that made "|h" completely unusable.
  190. #     They are not used in print_help if they will hurt.  Strip pod
  191. #     if we're paging to less.
  192. #   + Fixed mis-formatting of help messages caused by ornaments
  193. #     to restore Larry's original formatting.  
  194. #   + Fixed many other formatting errors.  The code is still suboptimal, 
  195. #     and needs a lot of work at restructuring.  It's also misindented
  196. #     in many places.
  197. #   + Fixed bug where trying to look at an option like your pager
  198. #     shows "1".  
  199. #   + Fixed some $? processing.  Note: if you use csh or tcsh, you will
  200. #     lose.  You should consider shell escapes not using their shell,
  201. #     or else not caring about detailed status.  This should really be
  202. #     unified into one place, too.
  203. #   + Fixed bug where invisible trailing whitespace on commands hoses you,
  204. #     tricking Perl into thinking you weren't calling a debugger command!
  205. #   + Fixed bug where leading whitespace on commands hoses you.  (One
  206. #     suggests a leading semicolon or any other irrelevant non-whitespace
  207. #     to indicate literal Perl code.)
  208. #   + Fixed bugs that ate warnings due to wrong selected handle.
  209. #   + Fixed a precedence bug on signal stuff.
  210. #   + Fixed some unseemly wording.
  211. #   + Fixed bug in help command trying to call perl method code.
  212. #   + Fixed to call dumpvar from exception handler.  SIGPIPE killed us.
  213. #   ENHANCEMENTS:
  214. #   + Added some comments.  This code is still nasty spaghetti.
  215. #   + Added message if you clear your pre/post command stacks which was
  216. #     very easy to do if you just typed a bare >, <, or {.  (A command
  217. #     without an argument should *never* be a destructive action; this
  218. #     API is fundamentally screwed up; likewise option setting, which
  219. #     is equally buggered.)
  220. #   + Added command stack dump on argument of "?" for >, <, or {.
  221. #   + Added a semi-built-in doc viewer command that calls man with the
  222. #     proper %Config::Config path (and thus gets caching, man -k, etc),
  223. #     or else perldoc on obstreperous platforms.
  224. #   + Added to and rearranged the help information.
  225. #   + Detected apparent misuse of { ... } to declare a block; this used
  226. #     to work but now is a command, and mysteriously gave no complaint.
  227. #
  228. # Changes: 1.08: Apr 25, 2001  Jon Eveland <jweveland@yahoo.com>
  229. #   BUG FIX:
  230. #   + This patch to perl5db.pl cleans up formatting issues on the help
  231. #     summary (h h) screen in the debugger.  Mostly columnar alignment
  232. #     issues, plus converted the printed text to use all spaces, since
  233. #     tabs don't seem to help much here.
  234. #
  235. # Changes: 1.09: May 19, 2001  Ilya Zakharevich <ilya@math.ohio-state.edu>
  236. #   0) Minor bugs corrected;
  237. #   a) Support for auto-creation of new TTY window on startup, either
  238. #      unconditionally, or if started as a kid of another debugger session;
  239. #   b) New `O'ption CreateTTY
  240. #       I<CreateTTY>       bits control attempts to create a new TTY on events:
  241. #                          1: on fork()   2: debugger is started inside debugger
  242. #                          4: on startup
  243. #   c) Code to auto-create a new TTY window on OS/2 (currently one
  244. #      extra window per session - need named pipes to have more...);
  245. #   d) Simplified interface for custom createTTY functions (with a backward
  246. #      compatibility hack); now returns the TTY name to use; return of ''
  247. #      means that the function reset the I/O handles itself;
  248. #   d') Better message on the semantic of custom createTTY function;
  249. #   e) Convert the existing code to create a TTY into a custom createTTY
  250. #      function;
  251. #   f) Consistent support for TTY names of the form "TTYin,TTYout";
  252. #   g) Switch line-tracing output too to the created TTY window;
  253. #   h) make `b fork' DWIM with CORE::GLOBAL::fork;
  254. #   i) High-level debugger API cmd_*():
  255. #      cmd_b_load($filenamepart)            # b load filenamepart
  256. #      cmd_b_line($lineno [, $cond])        # b lineno [cond]
  257. #      cmd_b_sub($sub [, $cond])            # b sub [cond]
  258. #      cmd_stop()                           # Control-C
  259. #      cmd_d($lineno)                       # d lineno (B)
  260. #      The cmd_*() API returns FALSE on failure; in this case it outputs
  261. #      the error message to the debugging output.
  262. #   j) Low-level debugger API
  263. #      break_on_load($filename)             # b load filename
  264. #      @files = report_break_on_load()      # List files with load-breakpoints
  265. #      breakable_line_in_filename($name, $from [, $to])
  266. #                                           # First breakable line in the
  267. #                                           # range $from .. $to.  $to defaults
  268. #                                           # to $from, and may be less than $to
  269. #      breakable_line($from [, $to])        # Same for the current file
  270. #      break_on_filename_line($name, $lineno [, $cond])
  271. #                                           # Set breakpoint,$cond defaults to 1
  272. #      break_on_filename_line_range($name, $from, $to [, $cond])
  273. #                                           # As above, on the first
  274. #                                           # breakable line in range
  275. #      break_on_line($lineno [, $cond])     # As above, in the current file
  276. #      break_subroutine($sub [, $cond])     # break on the first breakable line
  277. #      ($name, $from, $to) = subroutine_filename_lines($sub)
  278. #                                           # The range of lines of the text
  279. #      The low-level API returns TRUE on success, and die()s on failure.
  280. #
  281. # Changes: 1.10: May 23, 2001  Daniel Lewart <d-lewart@uiuc.edu>
  282. #   BUG FIXES:
  283. #   + Fixed warnings generated by "perl -dWe 42"
  284. #   + Corrected spelling errors
  285. #   + Squeezed Help (h) output into 80 columns
  286. #
  287. # Changes: 1.11: May 24, 2001  David Dyck <dcd@tc.fluke.com>
  288. #   + Made "x @INC" work like it used to
  289. #
  290. # Changes: 1.12: May 24, 2001  Daniel Lewart <d-lewart@uiuc.edu>
  291. #   + Fixed warnings generated by "O" (Show debugger options)
  292. #   + Fixed warnings generated by "p 42" (Print expression)
  293. # Changes: 1.13: Jun 19, 2001 Scott.L.Miller@compaq.com
  294. #   + Added windowSize option 
  295. # Changes: 1.14: Oct  9, 2001 multiple
  296. #   + Clean up after itself on VMS (Charles Lane in 12385)
  297. #   + Adding "@ file" syntax (Peter Scott in 12014)
  298. #   + Debug reloading selfloaded stuff (Ilya Zakharevich in 11457)
  299. #   + $^S and other debugger fixes (Ilya Zakharevich in 11120)
  300. #   + Forgot a my() declaration (Ilya Zakharevich in 11085)
  301. # Changes: 1.15: Nov  6, 2001 Michael G Schwern <schwern@pobox.com>
  302. #   + Updated 1.14 change log
  303. #   + Added *dbline explainatory comments
  304. #   + Mentioning perldebguts man page
  305. # Changes: 1.16: Feb 15, 2002 Mark-Jason Dominus <mjd@plover.com>
  306. #    + $onetimeDump improvements
  307. # Changes: 1.17: Feb 20, 2002 Richard Foley <richard.foley@rfi.net>
  308. #   Moved some code to cmd_[.]()'s for clarity and ease of handling,
  309. #   rationalised the following commands and added cmd_wrapper() to 
  310. #   enable switching between old and frighteningly consistent new 
  311. #   behaviours for diehards: 'o CommandSet=pre580' (sigh...)
  312. #     a(add),       A(del)            # action expr   (added del by line)
  313. #   + b(add),       B(del)            # break  [line] (was b,D)
  314. #   + w(add),       W(del)            # watch  expr   (was W,W) added del by expr
  315. #   + h(summary), h h(long)           # help (hh)     (was h h,h)
  316. #   + m(methods),   M(modules)        # ...           (was m,v)
  317. #   + o(option)                       # lc            (was O)
  318. #   + v(view code), V(view Variables) # ...           (was w,V)
  319. # Changes: 1.18: Mar 17, 2002 Richard Foley <richard.foley@rfi.net>
  320. #   + fixed missing cmd_O bug
  321. # Changes: 1.19: Mar 29, 2002 Spider Boardman
  322. #   + Added missing local()s -- DB::DB is called recursively.
  323. ####################################################################
  324.  
  325. # Needed for the statement after exec():
  326.  
  327. BEGIN { $ini_warn = $^W; $^W = 0 } # Switch compilation warnings off until another BEGIN.
  328. local($^W) = 0;            # Switch run-time warnings off during init.
  329. warn (            # Do not ;-)
  330.       $dumpvar::hashDepth,     
  331.       $dumpvar::arrayDepth,    
  332.       $dumpvar::dumpDBFiles,   
  333.       $dumpvar::dumpPackages,  
  334.       $dumpvar::quoteHighBit,  
  335.       $dumpvar::printUndef,    
  336.       $dumpvar::globPrint,     
  337.       $dumpvar::usageOnly,
  338.       @ARGS,
  339.       $Carp::CarpLevel,
  340.       $panic,
  341.       $second_time,
  342.      ) if 0;
  343.  
  344. # Command-line + PERLLIB:
  345. @ini_INC = @INC;
  346.  
  347. # $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?!
  348.  
  349. $trace = $signal = $single = 0;    # Uninitialized warning suppression
  350.                                 # (local $^W cannot help - other packages!).
  351. $inhibit_exit = $option{PrintRet} = 1;
  352.  
  353. @options     = qw(hashDepth arrayDepth CommandSet dumpDepth
  354.                   DumpDBFiles DumpPackages DumpReused
  355.           compactDump veryCompact quote HighBit undefPrint
  356.           globPrint PrintRet UsageOnly frame AutoTrace
  357.           TTY noTTY ReadLine NonStop LineInfo maxTraceLen
  358.           recallCommand ShellBang pager tkRunning ornaments
  359.           signalLevel warnLevel dieLevel inhibit_exit
  360.           ImmediateStop bareStringify CreateTTY
  361.           RemotePort windowSize);
  362.  
  363. %optionVars    = (
  364.          hashDepth    => \$dumpvar::hashDepth,
  365.          arrayDepth    => \$dumpvar::arrayDepth,
  366.          CommandSet => \$CommandSet,
  367.          DumpDBFiles    => \$dumpvar::dumpDBFiles,
  368.          DumpPackages    => \$dumpvar::dumpPackages,
  369.          DumpReused    => \$dumpvar::dumpReused,
  370.          HighBit    => \$dumpvar::quoteHighBit,
  371.          undefPrint    => \$dumpvar::printUndef,
  372.          globPrint    => \$dumpvar::globPrint,
  373.          UsageOnly    => \$dumpvar::usageOnly,
  374.          CreateTTY    => \$CreateTTY,
  375.          bareStringify    => \$dumpvar::bareStringify,
  376.          frame          => \$frame,
  377.          AutoTrace      => \$trace,
  378.          inhibit_exit   => \$inhibit_exit,
  379.          maxTraceLen    => \$maxtrace,
  380.          ImmediateStop    => \$ImmediateStop,
  381.          RemotePort    => \$remoteport,
  382.          windowSize    => \$window,
  383. );
  384.  
  385. %optionAction  = (
  386.           compactDump    => \&dumpvar::compactDump,
  387.           veryCompact    => \&dumpvar::veryCompact,
  388.           quote        => \&dumpvar::quote,
  389.           TTY        => \&TTY,
  390.           noTTY        => \&noTTY,
  391.           ReadLine    => \&ReadLine,
  392.           NonStop    => \&NonStop,
  393.           LineInfo    => \&LineInfo,
  394.           recallCommand    => \&recallCommand,
  395.           ShellBang    => \&shellBang,
  396.           pager        => \&pager,
  397.           signalLevel    => \&signalLevel,
  398.           warnLevel    => \&warnLevel,
  399.           dieLevel    => \&dieLevel,
  400.           tkRunning    => \&tkRunning,
  401.           ornaments    => \&ornaments,
  402.           RemotePort    => \&RemotePort,
  403.          );
  404.  
  405. %optionRequire = (
  406.           compactDump    => 'dumpvar.pl',
  407.           veryCompact    => 'dumpvar.pl',
  408.           quote        => 'dumpvar.pl',
  409.          );
  410.  
  411. # These guys may be defined in $ENV{PERL5DB} :
  412. $rl        = 1    unless defined $rl;
  413. $warnLevel    = 1    unless defined $warnLevel;
  414. $dieLevel    = 1    unless defined $dieLevel;
  415. $signalLevel    = 1    unless defined $signalLevel;
  416. $pre        = []    unless defined $pre;
  417. $post        = []    unless defined $post;
  418. $pretype    = []    unless defined $pretype;
  419. $CreateTTY    = 3    unless defined $CreateTTY;
  420. $CommandSet = '580'    unless defined $CommandSet;
  421.  
  422. warnLevel($warnLevel);
  423. dieLevel($dieLevel);
  424. signalLevel($signalLevel);
  425.  
  426. pager(
  427.       defined $ENV{PAGER}              ? $ENV{PAGER} :
  428.       eval { require Config } && 
  429.         defined $Config::Config{pager} ? $Config::Config{pager}
  430.                                        : 'more'
  431.      ) unless defined $pager;
  432. setman();
  433. &recallCommand("!") unless defined $prc;
  434. &shellBang("!") unless defined $psh;
  435. sethelp();
  436. $maxtrace = 400 unless defined $maxtrace;
  437. $ini_pids = $ENV{PERLDB_PIDS};
  438. if (defined $ENV{PERLDB_PIDS}) {
  439.   $pids = "[$ENV{PERLDB_PIDS}]";
  440.   $ENV{PERLDB_PIDS} .= "->$$";
  441.   $term_pid = -1;
  442. } else {
  443.   $ENV{PERLDB_PIDS} = "$$";
  444.   $pids = "{pid=$$}";
  445.   $term_pid = $$;
  446. }
  447. $pidprompt = '';
  448. *emacs = $slave_editor if $slave_editor;    # May be used in afterinit()...
  449.  
  450. if (-e "/dev/tty") {  # this is the wrong metric!
  451.   $rcfile=".perldb";
  452. } else {
  453.   $rcfile="perldb.ini";
  454. }
  455.  
  456. # This isn't really safe, because there's a race
  457. # between checking and opening.  The solution is to
  458. # open and fstat the handle, but then you have to read and
  459. # eval the contents.  But then the silly thing gets
  460. # your lexical scope, which is unfortunately at best.
  461. sub safe_do { 
  462.     my $file = shift;
  463.  
  464.     # Just exactly what part of the word "CORE::" don't you understand?
  465.     local $SIG{__WARN__};  
  466.     local $SIG{__DIE__};    
  467.  
  468.     unless (is_safe_file($file)) {
  469.     CORE::warn <<EO_GRIPE;
  470. perldb: Must not source insecure rcfile $file.
  471.         You or the superuser must be the owner, and it must not 
  472.     be writable by anyone but its owner.
  473. EO_GRIPE
  474.     return;
  475.     } 
  476.  
  477.     do $file;
  478.     CORE::warn("perldb: couldn't parse $file: $@") if $@;
  479. }
  480.  
  481.  
  482. # Verifies that owner is either real user or superuser and that no
  483. # one but owner may write to it.  This function is of limited use
  484. # when called on a path instead of upon a handle, because there are
  485. # no guarantees that filename (by dirent) whose file (by ino) is
  486. # eventually accessed is the same as the one tested. 
  487. # Assumes that the file's existence is not in doubt.
  488. sub is_safe_file {
  489.     my $path = shift;
  490.     stat($path) || return;    # mysteriously vaporized
  491.     my($dev,$ino,$mode,$nlink,$uid,$gid) = stat(_);
  492.  
  493.     return 0 if $uid != 0 && $uid != $<;
  494.     return 0 if $mode & 022;
  495.     return 1;
  496. }
  497.  
  498. if (-f $rcfile) {
  499.     safe_do("./$rcfile");
  500. elsif (defined $ENV{HOME} && -f "$ENV{HOME}/$rcfile") {
  501.     safe_do("$ENV{HOME}/$rcfile");
  502. }
  503. elsif (defined $ENV{LOGDIR} && -f "$ENV{LOGDIR}/$rcfile") {
  504.     safe_do("$ENV{LOGDIR}/$rcfile");
  505. }
  506.  
  507. if (defined $ENV{PERLDB_OPTS}) {
  508.   parse_options($ENV{PERLDB_OPTS});
  509. }
  510.  
  511. if ( not defined &get_fork_TTY and defined $ENV{TERM} and $ENV{TERM} eq 'xterm'
  512.      and defined $ENV{WINDOWID} and defined $ENV{DISPLAY} ) { # _inside_ XTERM?
  513.     *get_fork_TTY = \&xterm_get_fork_TTY;
  514. } elsif ($^O eq 'os2') {
  515.     *get_fork_TTY = \&os2_get_fork_TTY;
  516. }
  517.  
  518. # Here begin the unreadable code.  It needs fixing.
  519.  
  520. if (exists $ENV{PERLDB_RESTART}) {
  521.   delete $ENV{PERLDB_RESTART};
  522.   # $restart = 1;
  523.   @hist = get_list('PERLDB_HIST');
  524.   %break_on_load = get_list("PERLDB_ON_LOAD");
  525.   %postponed = get_list("PERLDB_POSTPONE");
  526.   my @had_breakpoints= get_list("PERLDB_VISITED");
  527.   for (0 .. $#had_breakpoints) {
  528.     my %pf = get_list("PERLDB_FILE_$_");
  529.     $postponed_file{$had_breakpoints[$_]} = \%pf if %pf;
  530.   }
  531.   my %opt = get_list("PERLDB_OPT");
  532.   my ($opt,$val);
  533.   while (($opt,$val) = each %opt) {
  534.     $val =~ s/[\\\']/\\$1/g;
  535.     parse_options("$opt'$val'");
  536.   }
  537.   @INC = get_list("PERLDB_INC");
  538.   @ini_INC = @INC;
  539.   $pretype = [get_list("PERLDB_PRETYPE")];
  540.   $pre = [get_list("PERLDB_PRE")];
  541.   $post = [get_list("PERLDB_POST")];
  542.   @typeahead = get_list("PERLDB_TYPEAHEAD", @typeahead);
  543. }
  544.  
  545. if ($notty) {
  546.   $runnonstop = 1;
  547. } else {
  548.   # Is Perl being run from a slave editor or graphical debugger?
  549.   $slave_editor = ((defined $main::ARGV[0]) and ($main::ARGV[0] eq '-emacs'));
  550.   $rl = 0, shift(@main::ARGV) if $slave_editor;
  551.  
  552.   #require Term::ReadLine;
  553.  
  554.   if ($^O eq 'cygwin') {
  555.     # /dev/tty is binary. use stdin for textmode
  556.     undef $console;
  557.   } elsif (-e "/dev/tty") {
  558.     $console = "/dev/tty";
  559.   } elsif ($^O eq 'dos' or -e "con" or $^O eq 'MSWin32') {
  560.     $console = "con";
  561.   } elsif ($^O eq 'MacOS') {
  562.     if ($MacPerl::Version !~ /MPW/) {
  563.       $console = "Dev:Console:Perl Debug"; # Separate window for application
  564.     } else {
  565.       $console = "Dev:Console";
  566.     }
  567.   } else {
  568.     $console = "sys\$command";
  569.   }
  570.  
  571.   if (($^O eq 'MSWin32') and ($slave_editor or defined $ENV{EMACS})) {
  572.     $console = undef;
  573.   }
  574.  
  575.   if ($^O eq 'NetWare') {
  576.     $console = undef;
  577.   }
  578.  
  579.   # Around a bug:
  580.   if (defined $ENV{OS2_SHELL} and ($slave_editor or $ENV{WINDOWID})) { # In OS/2
  581.     $console = undef;
  582.   }
  583.  
  584.   if ($^O eq 'epoc') {
  585.     $console = undef;
  586.   }
  587.  
  588.   $console = $tty if defined $tty;
  589.  
  590.   if (defined $remoteport) {
  591.     require IO::Socket;
  592.     $OUT = new IO::Socket::INET( Timeout  => '10',
  593.                                  PeerAddr => $remoteport,
  594.                                  Proto    => 'tcp',
  595.                                );
  596.     if (!$OUT) { die "Unable to connect to remote host: $remoteport\n"; }
  597.     $IN = $OUT;
  598.   } else {
  599.     create_IN_OUT(4) if $CreateTTY & 4;
  600.     if ($console) {
  601.       my ($i, $o) = split /,/, $console;
  602.       $o = $i unless defined $o;
  603.       open(IN,"+<$i") || open(IN,"<$i") || open(IN,"<&STDIN");
  604.       open(OUT,"+>$o") || open(OUT,">$o") || open(OUT,">&STDERR")
  605.         || open(OUT,">&STDOUT");    # so we don't dongle stdout
  606.     } elsif (not defined $console) {
  607.       open(IN,"<&STDIN");
  608.       open(OUT,">&STDERR") || open(OUT,">&STDOUT"); # so we don't dongle stdout
  609.       $console = 'STDIN/OUT';
  610.     }
  611.     # so open("|more") can read from STDOUT and so we don't dingle stdin
  612.     $IN = \*IN, $OUT = \*OUT if $console or not defined $console;
  613.   }
  614.   my $previous = select($OUT);
  615.   $| = 1;            # for DB::OUT
  616.   select($previous);
  617.  
  618.   $LINEINFO = $OUT unless defined $LINEINFO;
  619.   $lineinfo = $console unless defined $lineinfo;
  620.  
  621.   $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/;
  622.   unless ($runnonstop) {
  623.     local $\ = '';
  624.     local $, = '';
  625.     if ($term_pid eq '-1') {
  626.       print $OUT "\nDaughter DB session started...\n";
  627.     } else {
  628.       print $OUT "\nLoading DB routines from $header\n";
  629.       print $OUT ("Editor support ",
  630.           $slave_editor ? "enabled" : "available",
  631.           ".\n");
  632.       print $OUT "\nEnter h or `h h' for help, or `$doccmd perldebug' for more help.\n\n";
  633.     }
  634.   }
  635. }
  636.  
  637. @ARGS = @ARGV;
  638. for (@args) {
  639.     s/\'/\\\'/g;
  640.     s/(.*)/'$1'/ unless /^-?[\d.]+$/;
  641. }
  642.  
  643. if (defined &afterinit) {    # May be defined in $rcfile
  644.   &afterinit();
  645. }
  646.  
  647. $I_m_init = 1;
  648.  
  649. ############################################################ Subroutines
  650.  
  651. sub DB {
  652.     # _After_ the perl program is compiled, $single is set to 1:
  653.     if ($single and not $second_time++) {
  654.       if ($runnonstop) {    # Disable until signal
  655.     for ($i=0; $i <= $stack_depth; ) {
  656.         $stack[$i++] &= ~1;
  657.     }
  658.     $single = 0;
  659.     # return;            # Would not print trace!
  660.       } elsif ($ImmediateStop) {
  661.     $ImmediateStop = 0;
  662.     $signal = 1;
  663.       }
  664.     }
  665.     $runnonstop = 0 if $single or $signal; # Disable it if interactive.
  666.     &save;
  667.     local($package, $filename, $line) = caller;
  668.     local $filename_ini = $filename;
  669.     local $usercontext = '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' .
  670.       "package $package;";    # this won't let them modify, alas
  671.     local(*dbline) = $main::{'_<' . $filename};
  672.  
  673.     # we need to check for pseudofiles on Mac OS (these are files
  674.     # not attached to a filename, but instead stored in Dev:Pseudo)
  675.     if ($^O eq 'MacOS' && $#dbline < 0) {
  676.     $filename_ini = $filename = 'Dev:Pseudo';
  677.     *dbline = $main::{'_<' . $filename};
  678.     }
  679.  
  680.     local $max = $#dbline;
  681.     if ($dbline{$line} && (($stop,$action) = split(/\0/,$dbline{$line}))) {
  682.         if ($stop eq '1') {
  683.             $signal |= 1;
  684.         } elsif ($stop) {
  685.             $evalarg = "\$DB::signal |= 1 if do {$stop}"; &eval;
  686.             $dbline{$line} =~ s/;9($|\0)/$1/;
  687.         }
  688.     }
  689.     my $was_signal = $signal;
  690.     if ($trace & 2) {
  691.       for (my $n = 0; $n <= $#to_watch; $n++) {
  692.         $evalarg = $to_watch[$n];
  693.         local $onetimeDump;    # Do not output results
  694.         my ($val) = &eval;    # Fix context (&eval is doing array)?
  695.         $val = ( (defined $val) ? "'$val'" : 'undef' );
  696.         if ($val ne $old_watch[$n]) {
  697.           $signal = 1;
  698.           print $OUT <<EOP;
  699. Watchpoint $n:\t$to_watch[$n] changed:
  700.     old value:\t$old_watch[$n]
  701.     new value:\t$val
  702. EOP
  703.           $old_watch[$n] = $val;
  704.         }
  705.       }
  706.     }
  707.     if ($trace & 4) {        # User-installed watch
  708.       return if watchfunction($package, $filename, $line) 
  709.     and not $single and not $was_signal and not ($trace & ~4);
  710.     }
  711.     $was_signal = $signal;
  712.     $signal = 0;
  713.     if ($single || ($trace & 1) || $was_signal) {
  714.     if ($slave_editor) {
  715.         $position = "\032\032$filename:$line:0\n";
  716.         print_lineinfo($position);
  717.     } elsif ($package eq 'DB::fake') {
  718.       $term || &setterm;
  719.       print_help(<<EOP);
  720. Debugged program terminated.  Use B<q> to quit or B<R> to restart,
  721.   use B<O> I<inhibit_exit> to avoid stopping after program termination,
  722.   B<h q>, B<h R> or B<h O> to get additional info.  
  723. EOP
  724.       $package = 'main';
  725.       $usercontext = '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' .
  726.         "package $package;";    # this won't let them modify, alas
  727.     } else {
  728.         $sub =~ s/\'/::/;
  729.         $prefix = $sub =~ /::/ ? "" : "${'package'}::";
  730.         $prefix .= "$sub($filename:";
  731.         $after = ($dbline[$line] =~ /\n$/ ? '' : "\n");
  732.         if (length($prefix) > 30) {
  733.             $position = "$prefix$line):\n$line:\t$dbline[$line]$after";
  734.             $prefix = "";
  735.             $infix = ":\t";
  736.         } else {
  737.             $infix = "):\t";
  738.             $position = "$prefix$line$infix$dbline[$line]$after";
  739.         }
  740.         if ($frame) {
  741.             print_lineinfo(' ' x $stack_depth, "$line:\t$dbline[$line]$after");
  742.         } else {
  743.             print_lineinfo($position);
  744.         }
  745.         for ($i = $line + 1; $i <= $max && $dbline[$i] == 0; ++$i) { #{ vi
  746.             last if $dbline[$i] =~ /^\s*[\;\}\#\n]/;
  747.             last if $signal;
  748.             $after = ($dbline[$i] =~ /\n$/ ? '' : "\n");
  749.             $incr_pos = "$prefix$i$infix$dbline[$i]$after";
  750.             $position .= $incr_pos;
  751.             if ($frame) {
  752.                 print_lineinfo(' ' x $stack_depth, "$i:\t$dbline[$i]$after");
  753.             } else {
  754.                 print_lineinfo($incr_pos);
  755.             }
  756.         }
  757.     }
  758.     }
  759.     $evalarg = $action, &eval if $action;
  760.     if ($single || $was_signal) {
  761.       local $level = $level + 1;
  762.       foreach $evalarg (@$pre) {
  763.         &eval;
  764.       }
  765.       print $OUT $stack_depth . " levels deep in subroutine calls!\n"
  766.               if $single & 4;
  767.         $start = $line;
  768.         $incr = -1;        # for backward motion.
  769.         @typeahead = (@$pretype, @typeahead);
  770.     CMD:
  771.     while (($term || &setterm),
  772.            ($term_pid == $$ or resetterm(1)),
  773.            defined ($cmd=&readline("$pidprompt  DB" . ('<' x $level) .
  774.                        ($#hist+1) . ('>' x $level) . " "))) 
  775.         {
  776.         $single = 0;
  777.         $signal = 0;
  778.         $cmd =~ s/\\$/\n/ && do {
  779.             $cmd .= &readline("  cont: ");
  780.             redo CMD;
  781.         };
  782.         $cmd =~ /^$/ && ($cmd = $laststep);
  783.         push(@hist,$cmd) if length($cmd) > 1;
  784.           PIPE: {
  785.             $cmd =~ s/^\s+//s;   # trim annoying leading whitespace
  786.             $cmd =~ s/\s+$//s;   # trim annoying trailing whitespace
  787.             ($i) = split(/\s+/,$cmd);
  788.             if ($alias{$i}) { 
  789.                     # squelch the sigmangler
  790.                     local $SIG{__DIE__};
  791.                     local $SIG{__WARN__};
  792.                     eval "\$cmd =~ $alias{$i}";
  793.                     if ($@) {
  794.                                                 local $\ = '';
  795.                         print $OUT "Couldn't evaluate `$i' alias: $@";
  796.                         next CMD;
  797.                     } 
  798.             }
  799.                     $cmd =~ /^q$/ && do {
  800.                         $fall_off_end = 1;
  801.                         clean_ENV();
  802.                         exit $?;
  803.                     };
  804.             $cmd =~ /^t$/ && do {
  805.             $trace ^= 1;
  806.             local $\ = '';
  807.             print $OUT "Trace = " .
  808.                 (($trace & 1) ? "on" : "off" ) . "\n";
  809.             next CMD; };
  810.             $cmd =~ /^S(\s+(!)?(.+))?$/ && do {
  811.             $Srev = defined $2; $Spatt = $3; $Snocheck = ! defined $1;
  812.             local $\ = '';
  813.             local $, = '';
  814.             foreach $subname (sort(keys %sub)) {
  815.                 if ($Snocheck or $Srev^($subname =~ /$Spatt/)) {
  816.                 print $OUT $subname,"\n";
  817.                 }
  818.             }
  819.             next CMD; };
  820.             $cmd =~ s/^X\b/V $package/;
  821.             $cmd =~ /^V$/ && do {
  822.             $cmd = "V $package"; };
  823.             $cmd =~ /^V\b\s*(\S+)\s*(.*)/ && do {
  824.             local ($savout) = select($OUT);
  825.             $packname = $1;
  826.             @vars = split(' ',$2);
  827.             do 'dumpvar.pl' unless defined &main::dumpvar;
  828.             if (defined &main::dumpvar) {
  829.                 local $frame = 0;
  830.                 local $doret = -2;
  831.                 # must detect sigpipe failures
  832.                            eval { &main::dumpvar($packname,
  833.                                                  defined $option{dumpDepth}
  834.                                                   ? $option{dumpDepth} : -1,
  835.                                                  @vars) };
  836.                 if ($@) {
  837.                 die unless $@ =~ /dumpvar print failed/;
  838.                 } 
  839.             } else {
  840.                 print $OUT "dumpvar.pl not available.\n";
  841.             }
  842.             select ($savout);
  843.             next CMD; };
  844.             $cmd =~ s/^x\b/ / && do { # So that will be evaled
  845.             $onetimeDump = 'dump'; 
  846.                         # handle special  "x 3 blah" syntax
  847.                         if ($cmd =~ s/^\s*(\d+)(?=\s)/ /) {
  848.                           $onetimedumpDepth = $1;
  849.                         }
  850.                       };
  851.             $cmd =~ s/^m\s+([\w:]+)\s*$/ / && do {
  852.             methods($1); next CMD};
  853.             $cmd =~ s/^m\b/ / && do { # So this will be evaled
  854.             $onetimeDump = 'methods'; };
  855.             $cmd =~ /^f\b\s*(.*)/ && do {
  856.             $file = $1;
  857.             $file =~ s/\s+$//;
  858.             if (!$file) {
  859.                 print $OUT "The old f command is now the r command.\n"; # hint
  860.                 print $OUT "The new f command switches filenames.\n";
  861.                 next CMD;
  862.             }
  863.             if (!defined $main::{'_<' . $file}) {
  864.                 if (($try) = grep(m#^_<.*$file#, keys %main::)) {{
  865.                           $try = substr($try,2);
  866.                           print $OUT "Choosing $try matching `$file':\n";
  867.                           $file = $try;
  868.                       }}
  869.             }
  870.             if (!defined $main::{'_<' . $file}) {
  871.                 print $OUT "No file matching `$file' is loaded.\n";
  872.                 next CMD;
  873.             } elsif ($file ne $filename) {
  874.                 *dbline = $main::{'_<' . $file};
  875.                 $max = $#dbline;
  876.                 $filename = $file;
  877.                 $start = 1;
  878.                 $cmd = "l";
  879.               } else {
  880.                 print $OUT "Already in $file.\n";
  881.                 next CMD;
  882.               }
  883.               };
  884.             $cmd =~ /^\.$/ && do {
  885.             $incr = -1;        # for backward motion.
  886.             $start = $line;
  887.             $filename = $filename_ini;
  888.             *dbline = $main::{'_<' . $filename};
  889.             $max = $#dbline;
  890.             print_lineinfo($position);
  891.             next CMD };
  892.             $cmd =~ /^-$/ && do {
  893.             $start -= $incr + $window + 1;
  894.             $start = 1 if $start <= 0;
  895.             $incr = $window - 1;
  896.             $cmd = 'l ' . ($start) . '+'; };
  897.             # rjsf ->
  898.           $cmd =~ /^([aAbBhlLMoOvwW])\b\s*(.*)/s && do { 
  899.                 &cmd_wrapper($1, $2, $line); 
  900.                 next CMD; 
  901.             };
  902.             # <- rjsf
  903.           $cmd =~ /^\<\<\s*(.*)/ && do { # \<\< for CPerl sake: not HERE
  904.             push @$pre, action($1);
  905.             next CMD; };
  906.             $cmd =~ /^>>\s*(.*)/ && do {
  907.             push @$post, action($1);
  908.             next CMD; };
  909.             $cmd =~ /^<\s*(.*)/ && do {
  910.             unless ($1) {
  911.                 print $OUT "All < actions cleared.\n";
  912.                 $pre = [];
  913.                 next CMD;
  914.             } 
  915.             if ($1 eq '?') {
  916.                 unless (@$pre) {
  917.                 print $OUT "No pre-prompt Perl actions.\n";
  918.                 next CMD;
  919.                 } 
  920.                 print $OUT "Perl commands run before each prompt:\n";
  921.                 for my $action ( @$pre ) {
  922.                 print $OUT "\t< -- $action\n";
  923.                 } 
  924.                 next CMD;
  925.             } 
  926.             $pre = [action($1)];
  927.             next CMD; };
  928.             $cmd =~ /^>\s*(.*)/ && do {
  929.             unless ($1) {
  930.                 print $OUT "All > actions cleared.\n";
  931.                 $post = [];
  932.                 next CMD;
  933.             }
  934.             if ($1 eq '?') {
  935.                 unless (@$post) {
  936.                 print $OUT "No post-prompt Perl actions.\n";
  937.                 next CMD;
  938.                 } 
  939.                 print $OUT "Perl commands run after each prompt:\n";
  940.                 for my $action ( @$post ) {
  941.                 print $OUT "\t> -- $action\n";
  942.                 } 
  943.                 next CMD;
  944.             } 
  945.             $post = [action($1)];
  946.             next CMD; };
  947.             $cmd =~ /^\{\{\s*(.*)/ && do {
  948.             if ($cmd =~ /^\{.*\}$/ && unbalanced(substr($cmd,2))) { 
  949.                 print $OUT "{{ is now a debugger command\n",
  950.                 "use `;{{' if you mean Perl code\n";
  951.                 $cmd = "h {{";
  952.                 redo CMD;
  953.             } 
  954.             push @$pretype, $1;
  955.             next CMD; };
  956.             $cmd =~ /^\{\s*(.*)/ && do {
  957.             unless ($1) {
  958.                 print $OUT "All { actions cleared.\n";
  959.                 $pretype = [];
  960.                 next CMD;
  961.             }
  962.             if ($1 eq '?') {
  963.                 unless (@$pretype) {
  964.                 print $OUT "No pre-prompt debugger actions.\n";
  965.                 next CMD;
  966.                 } 
  967.                 print $OUT "Debugger commands run before each prompt:\n";
  968.                 for my $action ( @$pretype ) {
  969.                 print $OUT "\t{ -- $action\n";
  970.                 } 
  971.                 next CMD;
  972.             } 
  973.             if ($cmd =~ /^\{.*\}$/ && unbalanced(substr($cmd,1))) { 
  974.                 print $OUT "{ is now a debugger command\n",
  975.                 "use `;{' if you mean Perl code\n";
  976.                 $cmd = "h {";
  977.                 redo CMD;
  978.             } 
  979.             $pretype = [$1];
  980.             next CMD; };
  981.                    $cmd =~ /^y(?:\s+(\d*)\s*(.*))?$/ && do {
  982.                        eval { require PadWalker; PadWalker->VERSION(0.08) }
  983.                          or &warn($@ =~ /locate/
  984.                             ? "PadWalker module not found - please install\n"
  985.                             : $@)
  986.                           and next CMD;
  987.                        do 'dumpvar.pl' unless defined &main::dumpvar;
  988.                        defined &main::dumpvar
  989.                           or print $OUT "dumpvar.pl not available.\n"
  990.                           and next CMD;
  991.                        my @vars = split(' ', $2 || '');
  992.                        my $h = eval { PadWalker::peek_my(($1 || 0) + 1) };
  993.                        $@ and $@ =~ s/ at .*//, &warn($@), next CMD;
  994.                        my $savout = select($OUT);
  995.                        dumpvar::dumplex($_, $h->{$_}, 
  996.                                        defined $option{dumpDepth}
  997.                                        ? $option{dumpDepth} : -1,
  998.                                        @vars)
  999.                            for sort keys %$h;
  1000.                        select($savout);
  1001.                        next CMD; };
  1002.                    $cmd =~ /^n$/ && do {
  1003.                 end_report(), next CMD if $finished and $level <= 1;
  1004.             $single = 2;
  1005.             $laststep = $cmd;
  1006.             last CMD; };
  1007.             $cmd =~ /^s$/ && do {
  1008.                 end_report(), next CMD if $finished and $level <= 1;
  1009.             $single = 1;
  1010.             $laststep = $cmd;
  1011.             last CMD; };
  1012.             $cmd =~ /^c\b\s*([\w:]*)\s*$/ && do {
  1013.                 end_report(), next CMD if $finished and $level <= 1;
  1014.             $subname = $i = $1;
  1015.             #  Probably not needed, since we finish an interactive
  1016.             #  sub-session anyway...
  1017.             # local $filename = $filename;
  1018.             # local *dbline = *dbline;    # XXX Would this work?!
  1019.             if ($subname =~ /\D/) { # subroutine name
  1020.                 $subname = $package."::".$subname 
  1021.                     unless $subname =~ /::/;
  1022.                 ($file,$i) = (find_sub($subname) =~ /^(.*):(.*)$/);
  1023.                 $i += 0;
  1024.                 if ($i) {
  1025.                     $filename = $file;
  1026.                 *dbline = $main::{'_<' . $filename};
  1027.                 $had_breakpoints{$filename} |= 1;
  1028.                 $max = $#dbline;
  1029.                 ++$i while $dbline[$i] == 0 && $i < $max;
  1030.                 } else {
  1031.                 print $OUT "Subroutine $subname not found.\n";
  1032.                 next CMD; 
  1033.                 }
  1034.             }
  1035.             if ($i) {
  1036.                 if ($dbline[$i] == 0) {
  1037.                 print $OUT "Line $i not breakable.\n";
  1038.                 next CMD;
  1039.                 }
  1040.                 $dbline{$i} =~ s/($|\0)/;9$1/; # add one-time-only b.p.
  1041.             }
  1042.             for ($i=0; $i <= $stack_depth; ) {
  1043.                 $stack[$i++] &= ~1;
  1044.             }
  1045.             last CMD; };
  1046.             $cmd =~ /^r$/ && do {
  1047.                 end_report(), next CMD if $finished and $level <= 1;
  1048.             $stack[$stack_depth] |= 1;
  1049.             $doret = $option{PrintRet} ? $stack_depth - 1 : -2;
  1050.             last CMD; };
  1051.             $cmd =~ /^R$/ && do {
  1052.                 print $OUT "Warning: some settings and command-line options may be lost!\n";
  1053.             my (@script, @flags, $cl);
  1054.             push @flags, '-w' if $ini_warn;
  1055.             # Put all the old includes at the start to get
  1056.             # the same debugger.
  1057.             for (@ini_INC) {
  1058.               push @flags, '-I', $_;
  1059.             }
  1060.             push @flags, '-T' if ${^TAINT};
  1061.             # Arrange for setting the old INC:
  1062.             set_list("PERLDB_INC", @ini_INC);
  1063.             if ($0 eq '-e') {
  1064.               for (1..$#{'::_<-e'}) { # The first line is PERL5DB
  1065.                     chomp ($cl =  ${'::_<-e'}[$_]);
  1066.                 push @script, '-e', $cl;
  1067.               }
  1068.             } else {
  1069.               @script = $0;
  1070.             }
  1071.             set_list("PERLDB_HIST", 
  1072.                  $term->Features->{getHistory} 
  1073.                  ? $term->GetHistory : @hist);
  1074.             my @had_breakpoints = keys %had_breakpoints;
  1075.             set_list("PERLDB_VISITED", @had_breakpoints);
  1076.             set_list("PERLDB_OPT", %option);
  1077.             set_list("PERLDB_ON_LOAD", %break_on_load);
  1078.             my @hard;
  1079.             for (0 .. $#had_breakpoints) {
  1080.               my $file = $had_breakpoints[$_];
  1081.               *dbline = $main::{'_<' . $file};
  1082.               next unless %dbline or $postponed_file{$file};
  1083.               (push @hard, $file), next 
  1084.                 if $file =~ /^\(\w*eval/;
  1085.               my @add;
  1086.               @add = %{$postponed_file{$file}}
  1087.                 if $postponed_file{$file};
  1088.               set_list("PERLDB_FILE_$_", %dbline, @add);
  1089.             }
  1090.             for (@hard) { # Yes, really-really...
  1091.               # Find the subroutines in this eval
  1092.               *dbline = $main::{'_<' . $_};
  1093.               my ($quoted, $sub, %subs, $line) = quotemeta $_;
  1094.               for $sub (keys %sub) {
  1095.                 next unless $sub{$sub} =~ /^$quoted:(\d+)-(\d+)$/;
  1096.                 $subs{$sub} = [$1, $2];
  1097.               }
  1098.               unless (%subs) {
  1099.                 print $OUT
  1100.                   "No subroutines in $_, ignoring breakpoints.\n";
  1101.                 next;
  1102.               }
  1103.             LINES: for $line (keys %dbline) {
  1104.                 # One breakpoint per sub only:
  1105.                 my ($offset, $sub, $found);
  1106.               SUBS: for $sub (keys %subs) {
  1107.                   if ($subs{$sub}->[1] >= $line # Not after the subroutine
  1108.                   and (not defined $offset # Not caught
  1109.                        or $offset < 0 )) { # or badly caught
  1110.                 $found = $sub;
  1111.                 $offset = $line - $subs{$sub}->[0];
  1112.                 $offset = "+$offset", last SUBS if $offset >= 0;
  1113.                   }
  1114.                 }
  1115.                 if (defined $offset) {
  1116.                   $postponed{$found} =
  1117.                 "break $offset if $dbline{$line}";
  1118.                 } else {
  1119.                   print $OUT "Breakpoint in $_:$line ignored: after all the subroutines.\n";
  1120.                 }
  1121.               }
  1122.             }
  1123.             set_list("PERLDB_POSTPONE", %postponed);
  1124.             set_list("PERLDB_PRETYPE", @$pretype);
  1125.             set_list("PERLDB_PRE", @$pre);
  1126.             set_list("PERLDB_POST", @$post);
  1127.             set_list("PERLDB_TYPEAHEAD", @typeahead);
  1128.             $ENV{PERLDB_RESTART} = 1;
  1129.             delete $ENV{PERLDB_PIDS}; # Restore ini state
  1130.             $ENV{PERLDB_PIDS} = $ini_pids if defined $ini_pids;
  1131.             #print "$^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS";
  1132.             exec($^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS) ||
  1133.             print $OUT "exec failed: $!\n";
  1134.             last CMD; };
  1135.             $cmd =~ /^T$/ && do {
  1136.             print_trace($OUT, 1); # skip DB
  1137.             next CMD; };
  1138.             $cmd =~ /^w\b\s*(.*)/s && do { &cmd_w($1); next CMD; };
  1139.             $cmd =~ /^W\b\s*(.*)/s && do { &cmd_W($1); next CMD; };
  1140.             $cmd =~ /^\/(.*)$/ && do {
  1141.             $inpat = $1;
  1142.             $inpat =~ s:([^\\])/$:$1:;
  1143.             if ($inpat ne "") {
  1144.                 # squelch the sigmangler
  1145.                 local $SIG{__DIE__};
  1146.                 local $SIG{__WARN__};
  1147.                 eval '$inpat =~ m'."\a$inpat\a";    
  1148.                 if ($@ ne "") {
  1149.                 print $OUT "$@";
  1150.                 next CMD;
  1151.                 }
  1152.                 $pat = $inpat;
  1153.             }
  1154.             $end = $start;
  1155.             $incr = -1;
  1156.             eval '
  1157.                 for (;;) {
  1158.                 ++$start;
  1159.                 $start = 1 if ($start > $max);
  1160.                 last if ($start == $end);
  1161.                 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
  1162.                     if ($slave_editor) {
  1163.                     print $OUT "\032\032$filename:$start:0\n";
  1164.                     } else {
  1165.                     print $OUT "$start:\t", $dbline[$start], "\n";
  1166.                     }
  1167.                     last;
  1168.                 }
  1169.                 } ';
  1170.             print $OUT "/$pat/: not found\n" if ($start == $end);
  1171.             next CMD; };
  1172.             $cmd =~ /^\?(.*)$/ && do {
  1173.             $inpat = $1;
  1174.             $inpat =~ s:([^\\])\?$:$1:;
  1175.             if ($inpat ne "") {
  1176.                 # squelch the sigmangler
  1177.                 local $SIG{__DIE__};
  1178.                 local $SIG{__WARN__};
  1179.                 eval '$inpat =~ m'."\a$inpat\a";    
  1180.                 if ($@ ne "") {
  1181.                 print $OUT $@;
  1182.                 next CMD;
  1183.                 }
  1184.                 $pat = $inpat;
  1185.             }
  1186.             $end = $start;
  1187.             $incr = -1;
  1188.             eval '
  1189.                 for (;;) {
  1190.                 --$start;
  1191.                 $start = $max if ($start <= 0);
  1192.                 last if ($start == $end);
  1193.                 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
  1194.                     if ($slave_editor) {
  1195.                     print $OUT "\032\032$filename:$start:0\n";
  1196.                     } else {
  1197.                     print $OUT "$start:\t", $dbline[$start], "\n";
  1198.                     }
  1199.                     last;
  1200.                 }
  1201.                 } ';
  1202.             print $OUT "?$pat?: not found\n" if ($start == $end);
  1203.             next CMD; };
  1204.             $cmd =~ /^$rc+\s*(-)?(\d+)?$/ && do {
  1205.             pop(@hist) if length($cmd) > 1;
  1206.             $i = $1 ? ($#hist-($2||1)) : ($2||$#hist);
  1207.             $cmd = $hist[$i];
  1208.             print $OUT $cmd, "\n";
  1209.             redo CMD; };
  1210.             $cmd =~ /^$sh$sh\s*([\x00-\xff]*)/ && do {
  1211.             &system($1);
  1212.             next CMD; };
  1213.             $cmd =~ /^$rc([^$rc].*)$/ && do {
  1214.             $pat = "^$1";
  1215.             pop(@hist) if length($cmd) > 1;
  1216.             for ($i = $#hist; $i; --$i) {
  1217.                 last if $hist[$i] =~ /$pat/;
  1218.             }
  1219.             if (!$i) {
  1220.                 print $OUT "No such command!\n\n";
  1221.                 next CMD;
  1222.             }
  1223.             $cmd = $hist[$i];
  1224.             print $OUT $cmd, "\n";
  1225.             redo CMD; };
  1226.             $cmd =~ /^$sh$/ && do {
  1227.             &system($ENV{SHELL}||"/bin/sh");
  1228.             next CMD; };
  1229.             $cmd =~ /^$sh\s*([\x00-\xff]*)/ && do {
  1230.             # XXX: using csh or tcsh destroys sigint retvals!
  1231.             #&system($1);  # use this instead
  1232.             &system($ENV{SHELL}||"/bin/sh","-c",$1);
  1233.             next CMD; };
  1234.             $cmd =~ /^H\b\s*(-(\d+))?/ && do {
  1235.             $end = $2 ? ($#hist-$2) : 0;
  1236.             $hist = 0 if $hist < 0;
  1237.             for ($i=$#hist; $i>$end; $i--) {
  1238.                 print $OUT "$i: ",$hist[$i],"\n"
  1239.                   unless $hist[$i] =~ /^.?$/;
  1240.             };
  1241.             next CMD; };
  1242.             $cmd =~ /^(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?$/ && do {
  1243.             runman($1);
  1244.             next CMD; };
  1245.             $cmd =~ s/^p$/print {\$DB::OUT} \$_/;
  1246.             $cmd =~ s/^p\b/print {\$DB::OUT} /;
  1247.             $cmd =~ s/^=\s*// && do {
  1248.             my @keys;
  1249.             if (length $cmd == 0) {
  1250.                 @keys = sort keys %alias;
  1251.             } elsif (my($k,$v) = ($cmd =~ /^(\S+)\s+(\S.*)/)) {
  1252.                 # can't use $_ or kill //g state
  1253.                 for my $x ($k, $v) { $x =~ s/\a/\\a/g }
  1254.                 $alias{$k} = "s\a$k\a$v\a";
  1255.                 # squelch the sigmangler
  1256.                 local $SIG{__DIE__};
  1257.                 local $SIG{__WARN__};
  1258.                 unless (eval "sub { s\a$k\a$v\a }; 1") {
  1259.                 print $OUT "Can't alias $k to $v: $@\n"; 
  1260.                 delete $alias{$k};
  1261.                 next CMD;
  1262.                 } 
  1263.                 @keys = ($k);
  1264.             } else {
  1265.                 @keys = ($cmd);
  1266.             } 
  1267.             for my $k (@keys) {
  1268.                 if ((my $v = $alias{$k}) =~ ss\a$k\a(.*)\a$1) {
  1269.                 print $OUT "$k\t= $1\n";
  1270.                 } 
  1271.                 elsif (defined $alias{$k}) {
  1272.                     print $OUT "$k\t$alias{$k}\n";
  1273.                 } 
  1274.                 else {
  1275.                 print "No alias for $k\n";
  1276.                 } 
  1277.             }
  1278.             next CMD; };
  1279.                     $cmd =~ /^source\s+(.*\S)/ && do {
  1280.               if (open my $fh, $1) {
  1281.             push @cmdfhs, $fh;
  1282.               } else {
  1283.             &warn("Can't execute `$1': $!\n");
  1284.               }
  1285.               next CMD; };
  1286.             $cmd =~ /^\|\|?\s*[^|]/ && do {
  1287.             if ($pager =~ /^\|/) {
  1288.                 open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
  1289.                 open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
  1290.             } else {
  1291.                 open(SAVEOUT,">&OUT") || &warn("Can't save DB::OUT");
  1292.             }
  1293.             fix_less();
  1294.             unless ($piped=open(OUT,$pager)) {
  1295.                 &warn("Can't pipe output to `$pager'");
  1296.                 if ($pager =~ /^\|/) {
  1297.                 open(OUT,">&STDOUT") # XXX: lost message
  1298.                     || &warn("Can't restore DB::OUT");
  1299.                 open(STDOUT,">&SAVEOUT")
  1300.                   || &warn("Can't restore STDOUT");
  1301.                 close(SAVEOUT);
  1302.                 } else {
  1303.                 open(OUT,">&STDOUT") # XXX: lost message
  1304.                     || &warn("Can't restore DB::OUT");
  1305.                 }
  1306.                 next CMD;
  1307.             }
  1308.             $SIG{PIPE}= \&DB::catch if $pager =~ /^\|/
  1309.                 && ("" eq $SIG{PIPE}  ||  "DEFAULT" eq $SIG{PIPE});
  1310.             $selected= select(OUT);
  1311.             $|= 1;
  1312.             select( $selected ), $selected= "" unless $cmd =~ /^\|\|/;
  1313.             $cmd =~ s/^\|+\s*//;
  1314.             redo PIPE; 
  1315.             };
  1316.             # XXX Local variants do not work!
  1317.             $cmd =~ s/^t\s/\$DB::trace |= 1;\n/;
  1318.             $cmd =~ s/^s\s/\$DB::single = 1;\n/ && do {$laststep = 's'};
  1319.             $cmd =~ s/^n\s/\$DB::single = 2;\n/ && do {$laststep = 'n'};
  1320.         }        # PIPE:
  1321.         $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd"; &eval;
  1322.         if ($onetimeDump) {
  1323.         $onetimeDump = undef;
  1324.                 $onetimedumpDepth = undef;
  1325.         } elsif ($term_pid == $$) {
  1326.         print $OUT "\n";
  1327.         }
  1328.     } continue {        # CMD:
  1329.         if ($piped) {
  1330.         if ($pager =~ /^\|/) {
  1331.             $? = 0;  
  1332.             # we cannot warn here: the handle is missing --tchrist
  1333.             close(OUT) || print SAVEOUT "\nCan't close DB::OUT\n";
  1334.  
  1335.             # most of the $? crud was coping with broken cshisms
  1336.             if ($?) {
  1337.             print SAVEOUT "Pager `$pager' failed: ";
  1338.             if ($? == -1) {
  1339.                 print SAVEOUT "shell returned -1\n";
  1340.             } elsif ($? >> 8) {
  1341.                 print SAVEOUT 
  1342.                   ( $? & 127 ) ? " (SIG#".($?&127).")" : "", 
  1343.                   ( $? & 128 ) ? " -- core dumped" : "", "\n";
  1344.             } else {
  1345.                 print SAVEOUT "status ", ($? >> 8), "\n";
  1346.             } 
  1347.             } 
  1348.  
  1349.             open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
  1350.             open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
  1351.             $SIG{PIPE} = "DEFAULT" if $SIG{PIPE} eq \&DB::catch;
  1352.             # Will stop ignoring SIGPIPE if done like nohup(1)
  1353.             # does SIGINT but Perl doesn't give us a choice.
  1354.         } else {
  1355.             open(OUT,">&SAVEOUT") || &warn("Can't restore DB::OUT");
  1356.         }
  1357.         close(SAVEOUT);
  1358.         select($selected), $selected= "" unless $selected eq "";
  1359.         $piped= "";
  1360.         }
  1361.     }            # CMD:
  1362.     $fall_off_end = 1 unless defined $cmd; # Emulate `q' on EOF
  1363.     foreach $evalarg (@$post) {
  1364.       &eval;
  1365.     }
  1366.     }                # if ($single || $signal)
  1367.     ($@, $!, $^E, $,, $/, $\, $^W) = @saved;
  1368.     ();
  1369. }
  1370.  
  1371. # The following code may be executed now:
  1372. # BEGIN {warn 4}
  1373.  
  1374. sub sub {
  1375.     my ($al, $ret, @ret) = "";
  1376.     if (length($sub) > 10 && substr($sub, -10, 10) eq '::AUTOLOAD') {
  1377.     $al = " for $$sub";
  1378.     }
  1379.     local $stack_depth = $stack_depth + 1; # Protect from non-local exits
  1380.     $#stack = $stack_depth;
  1381.     $stack[-1] = $single;
  1382.     $single &= 1;
  1383.     $single |= 4 if $stack_depth == $deep;
  1384.     ($frame & 4 
  1385.      ? ( print_lineinfo(' ' x ($stack_depth - 1), "in  "),
  1386.      # Why -1? But it works! :-(
  1387.      print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1388.      : print_lineinfo(' ' x ($stack_depth - 1), "entering $sub$al\n")) if $frame;
  1389.     if (wantarray) {
  1390.     @ret = &$sub;
  1391.     $single |= $stack[$stack_depth--];
  1392.     ($frame & 4 
  1393.      ? ( print_lineinfo(' ' x $stack_depth, "out "), 
  1394.          print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1395.      : print_lineinfo(' ' x $stack_depth, "exited $sub$al\n")) if $frame & 2;
  1396.     if ($doret eq $stack_depth or $frame & 16) {
  1397.         local $\ = '';
  1398.             my $fh = ($doret eq $stack_depth ? $OUT : $LINEINFO);
  1399.         print $fh ' ' x $stack_depth if $frame & 16;
  1400.         print $fh "list context return from $sub:\n"; 
  1401.         dumpit($fh, \@ret );
  1402.         $doret = -2;
  1403.     }
  1404.     @ret;
  1405.     } else {
  1406.         if (defined wantarray) {
  1407.         $ret = &$sub;
  1408.         } else {
  1409.             &$sub; undef $ret;
  1410.         };
  1411.     $single |= $stack[$stack_depth--];
  1412.     ($frame & 4 
  1413.      ? (  print_lineinfo(' ' x $stack_depth, "out "),
  1414.           print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1415.      : print_lineinfo(' ' x $stack_depth, "exited $sub$al\n")) if $frame & 2;
  1416.     if ($doret eq $stack_depth or $frame & 16 and defined wantarray) {
  1417.         local $\ = '';
  1418.             my $fh = ($doret eq $stack_depth ? $OUT : $LINEINFO);
  1419.         print $fh (' ' x $stack_depth) if $frame & 16;
  1420.         print $fh (defined wantarray 
  1421.              ? "scalar context return from $sub: " 
  1422.              : "void context return from $sub\n");
  1423.         dumpit( $fh, $ret ) if defined wantarray;
  1424.         $doret = -2;
  1425.     }
  1426.     $ret;
  1427.     }
  1428. }
  1429.  
  1430. ### The API section
  1431.  
  1432. ### Functions with multiple modes of failure die on error, the rest
  1433. ### returns FALSE on error.
  1434. ### User-interface functions cmd_* output error message.
  1435.  
  1436. ### Note all cmd_[a-zA-Z]'s require $line, $dblineno as first arguments
  1437.  
  1438. my %set = ( # 
  1439.     'pre580'    => {
  1440.         'a'    => 'pre580_a', 
  1441.         'A'    => 'pre580_null',
  1442.         'b'    => 'pre580_b', 
  1443.         'B'    => 'pre580_null',
  1444.         'd'    => 'pre580_null',
  1445.         'D'    => 'pre580_D',
  1446.         'h'    => 'pre580_h',
  1447.         'M'    => 'pre580_null',
  1448.         'O'    => 'o',
  1449.         'o'    => 'pre580_null',
  1450.         'v'    => 'M',
  1451.         'w'    => 'v',
  1452.         'W'    => 'pre580_W',
  1453.     },
  1454. );
  1455.  
  1456. sub cmd_wrapper {
  1457.     my $cmd      = shift;
  1458.     my $line     = shift;
  1459.     my $dblineno = shift;
  1460.  
  1461.     # with this level of indirection we can wrap 
  1462.     # to old (pre580) or other command sets easily
  1463.     # 
  1464.     my $call = 'cmd_'.(
  1465.         $set{$CommandSet}{$cmd} || $cmd
  1466.     );
  1467.     # print "cmd_wrapper($cmd): $CommandSet($set{$CommandSet}{$cmd}) => call($call)\n";
  1468.  
  1469.     return &$call($line, $dblineno);
  1470. }
  1471.  
  1472. sub cmd_a {
  1473.     my $line   = shift || ''; # [.|line] expr
  1474.     my $dbline = shift; $line =~ s/^(\.|(?:[^\d]))/$dbline/;
  1475.     if ($line =~ /^\s*(\d*)\s*(\S.+)/) {
  1476.         my ($lineno, $expr) = ($1, $2);
  1477.         if (length $expr) {
  1478.             if ($dbline[$lineno] == 0) {
  1479.                 print $OUT "Line $lineno($dbline[$lineno]) does not have an action?\n";
  1480.             } else {
  1481.                 $had_breakpoints{$filename} |= 2;
  1482.                 $dbline{$lineno} =~ s/\0[^\0]*//;
  1483.                 $dbline{$lineno} .= "\0" . action($expr);
  1484.             }
  1485.         }
  1486.     } else {
  1487.         print $OUT "Adding an action requires an optional lineno and an expression\n"; # hint
  1488.     }
  1489. }
  1490.  
  1491. sub cmd_A {
  1492.     my $line   = shift || '';
  1493.     my $dbline = shift; $line =~ s/^\./$dbline/;
  1494.     if ($line eq '*') {
  1495.         eval { &delete_action(); 1 } or print $OUT $@ and return;
  1496.     } elsif ($line =~ /^(\S.*)/) {
  1497.         eval { &delete_action($1); 1 } or print $OUT $@ and return;
  1498.     } else {
  1499.         print $OUT "Deleting an action requires a line number, or '*' for all\n"; # hint
  1500.     }
  1501. }
  1502.  
  1503. sub delete_action {
  1504.   my $i = shift;
  1505.   if (defined($i)) {
  1506.         die "Line $i has no action .\n" if $dbline[$i] == 0;
  1507.         $dbline{$i} =~ s/\0[^\0]*//; # \^a
  1508.         delete $dbline{$i} if $dbline{$i} eq '';
  1509.     } else {
  1510.         print $OUT "Deleting all actions...\n";
  1511.         for my $file (keys %had_breakpoints) {
  1512.             local *dbline = $main::{'_<' . $file};
  1513.             my $max = $#dbline;
  1514.             my $was;
  1515.             for ($i = 1; $i <= $max ; $i++) {
  1516.                     if (defined $dbline{$i}) {
  1517.                             $dbline{$i} =~ s/\0[^\0]*//;
  1518.                             delete $dbline{$i} if $dbline{$i} eq '';
  1519.                     }
  1520.                 unless ($had_breakpoints{$file} &= ~2) {
  1521.                         delete $had_breakpoints{$file};
  1522.                 }
  1523.             }
  1524.         }
  1525.     }
  1526. }
  1527.  
  1528. sub cmd_b {
  1529.     my $line   = shift; # [.|line] [cond]
  1530.     my $dbline = shift; $line =~ s/^\./$dbline/;
  1531.     if ($line =~ /^\s*$/) {
  1532.         &cmd_b_line($dbline, 1);
  1533.     } elsif ($line =~ /^load\b\s*(.*)/) {
  1534.         my $file = $1; $file =~ s/\s+$//;
  1535.         &cmd_b_load($file);
  1536.     } elsif ($line =~ /^(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/) {
  1537.         my $cond = length $3 ? $3 : '1';
  1538.         my ($subname, $break) = ($2, $1 eq 'postpone');
  1539.         $subname =~ s/\'/::/g;
  1540.         $subname = "${'package'}::" . $subname unless $subname =~ /::/;
  1541.         $subname = "main".$subname if substr($subname,0,2) eq "::";
  1542.         $postponed{$subname} = $break ? "break +0 if $cond" : "compile";
  1543.     } elsif ($line =~ /^([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/) { 
  1544.         $subname = $1;
  1545.         $cond = length $2 ? $2 : '1';
  1546.         &cmd_b_sub($subname, $cond);
  1547.     } elsif ($line =~ /^(\d*)\s*(.*)/) { 
  1548.         $line = $1 || $dbline;
  1549.         $cond = length $2 ? $2 : '1';
  1550.         &cmd_b_line($line, $cond);
  1551.     } else {
  1552.         print "confused by line($line)?\n";
  1553.     }
  1554. }
  1555.  
  1556. sub break_on_load {
  1557.   my $file = shift;
  1558.   $break_on_load{$file} = 1;
  1559.   $had_breakpoints{$file} |= 1;
  1560. }
  1561.  
  1562. sub report_break_on_load {
  1563.   sort keys %break_on_load;
  1564. }
  1565.  
  1566. sub cmd_b_load {
  1567.   my $file = shift;
  1568.   my @files;
  1569.   {
  1570.     push @files, $file;
  1571.     push @files, $::INC{$file} if $::INC{$file};
  1572.     $file .= '.pm', redo unless $file =~ /\./;
  1573.   }
  1574.   break_on_load($_) for @files;
  1575.   @files = report_break_on_load;
  1576.   local $\ = '';
  1577.   local $" = ' ';
  1578.   print $OUT "Will stop on load of `@files'.\n";
  1579. }
  1580.  
  1581. $filename_error = '';
  1582.  
  1583. sub breakable_line {
  1584.   my ($from, $to) = @_;
  1585.   my $i = $from;
  1586.   if (@_ >= 2) {
  1587.     my $delta = $from < $to ? +1 : -1;
  1588.     my $limit = $delta > 0 ? $#dbline : 1;
  1589.     $limit = $to if ($limit - $to) * $delta > 0;
  1590.     $i += $delta while $dbline[$i] == 0 and ($limit - $i) * $delta > 0;
  1591.   }
  1592.   return $i unless $dbline[$i] == 0;
  1593.   my ($pl, $upto) = ('', '');
  1594.   ($pl, $upto) = ('s', "..$to") if @_ >=2 and $from != $to;
  1595.   die "Line$pl $from$upto$filename_error not breakable\n";
  1596. }
  1597.  
  1598. sub breakable_line_in_filename {
  1599.   my ($f) = shift;
  1600.   local *dbline = $main::{'_<' . $f};
  1601.   local $filename_error = " of `$f'";
  1602.   breakable_line(@_);
  1603. }
  1604.  
  1605. sub break_on_line {
  1606.   my ($i, $cond) = @_;
  1607.   $cond = 1 unless @_ >= 2;
  1608.   my $inii = $i;
  1609.   my $after = '';
  1610.   my $pl = '';
  1611.   die "Line $i$filename_error not breakable.\n" if $dbline[$i] == 0;
  1612.   $had_breakpoints{$filename} |= 1;
  1613.   if ($dbline{$i}) { $dbline{$i} =~ s/^[^\0]*/$cond/; }
  1614.   else { $dbline{$i} = $cond; }
  1615. }
  1616.  
  1617. sub cmd_b_line {
  1618.   eval { break_on_line(@_); 1 } or do {
  1619.     local $\ = '';
  1620.     print $OUT $@ and return;
  1621.   };
  1622. }
  1623.  
  1624. sub break_on_filename_line {
  1625.   my ($f, $i, $cond) = @_;
  1626.   $cond = 1 unless @_ >= 3;
  1627.   local *dbline = $main::{'_<' . $f};
  1628.   local $filename_error = " of `$f'";
  1629.   local $filename = $f;
  1630.   break_on_line($i, $cond);
  1631. }
  1632.  
  1633. sub break_on_filename_line_range {
  1634.   my ($f, $from, $to, $cond) = @_;
  1635.   my $i = breakable_line_in_filename($f, $from, $to);
  1636.   $cond = 1 unless @_ >= 3;
  1637.   break_on_filename_line($f,$i,$cond);
  1638. }
  1639.  
  1640. sub subroutine_filename_lines {
  1641.   my ($subname,$cond) = @_;
  1642.   # Filename below can contain ':'
  1643.   find_sub($subname) =~ /^(.*):(\d+)-(\d+)$/;
  1644. }
  1645.  
  1646. sub break_subroutine {
  1647.   my $subname = shift;
  1648.   my ($file,$s,$e) = subroutine_filename_lines($subname) or
  1649.     die "Subroutine $subname not found.\n";
  1650.   $cond = 1 unless @_ >= 2;
  1651.   break_on_filename_line_range($file,$s,$e,@_);
  1652. }
  1653.  
  1654. sub cmd_b_sub {
  1655.   my ($subname,$cond) = @_;
  1656.   $cond = 1 unless @_ >= 2;
  1657.   unless (ref $subname eq 'CODE') {
  1658.     $subname =~ s/\'/::/g;
  1659.     my $s = $subname;
  1660.     $subname = "${'package'}::" . $subname
  1661.       unless $subname =~ /::/;
  1662.     $subname = "CORE::GLOBAL::$s"
  1663.       if not defined &$subname and $s !~ /::/ and defined &{"CORE::GLOBAL::$s"};
  1664.     $subname = "main".$subname if substr($subname,0,2) eq "::";
  1665.   }
  1666.   eval { break_subroutine($subname,$cond); 1 } or do {
  1667.     local $\ = '';
  1668.     print $OUT $@ and return;
  1669.   }
  1670. }
  1671.  
  1672. sub cmd_B {
  1673.     my $line   = ($_[0] =~ /^\./) ? $dbline : shift || ''; 
  1674.     my $dbline = shift; $line =~ s/^\./$dbline/;
  1675.     if ($line eq '*') {
  1676.         eval { &delete_breakpoint(); 1 } or print $OUT $@ and return;
  1677.     } elsif ($line =~ /^(\S.*)/) {
  1678.         eval { &delete_breakpoint($line || $dbline); 1 } or do {
  1679.                     local $\ = '';
  1680.                     print $OUT $@ and return;
  1681.                 };
  1682.     } else {
  1683.         print $OUT "Deleting a breakpoint requires a line number, or '*' for all\n"; # hint
  1684.     }
  1685. }
  1686.  
  1687. sub delete_breakpoint {
  1688.   my $i = shift;
  1689.   if (defined($i)) {
  1690.       die "Line $i not breakable.\n" if $dbline[$i] == 0;
  1691.       $dbline{$i} =~ s/^[^\0]*//;
  1692.       delete $dbline{$i} if $dbline{$i} eq '';
  1693.   } else {
  1694.           print $OUT "Deleting all breakpoints...\n";
  1695.           for my $file (keys %had_breakpoints) {
  1696.                     local *dbline = $main::{'_<' . $file};
  1697.                     my $max = $#dbline;
  1698.                     my $was;
  1699.                     for ($i = 1; $i <= $max ; $i++) {
  1700.                             if (defined $dbline{$i}) {
  1701.                         $dbline{$i} =~ s/^[^\0]+//;
  1702.                         if ($dbline{$i} =~ s/^\0?$//) {
  1703.                                 delete $dbline{$i};
  1704.                         }
  1705.                             }
  1706.                     }
  1707.                     if (not $had_breakpoints{$file} &= ~1) {
  1708.                             delete $had_breakpoints{$file};
  1709.                     }
  1710.           }
  1711.           undef %postponed;
  1712.           undef %postponed_file;
  1713.           undef %break_on_load;
  1714.     }
  1715. }
  1716.  
  1717. sub cmd_stop {            # As on ^C, but not signal-safy.
  1718.   $signal = 1;
  1719. }
  1720.  
  1721. sub cmd_h {
  1722.     my $line   = shift || '';
  1723.     if ($line  =~ /^h\s*/) {
  1724.         print_help($help);
  1725.     } elsif ($line =~ /^(\S.*)$/) { 
  1726.             # support long commands; otherwise bogus errors
  1727.             # happen when you ask for h on <CR> for example
  1728.             my $asked = $1;            # for proper errmsg
  1729.             my $qasked = quotemeta($asked); # for searching
  1730.             # XXX: finds CR but not <CR>
  1731.             if ($help =~ /^<?(?:[IB]<)$qasked/m) {
  1732.               while ($help =~ /^(<?(?:[IB]<)$qasked([\s\S]*?)\n)(?!\s)/mg) {
  1733.                 print_help($1);
  1734.               }
  1735.             } else {
  1736.                 print_help("B<$asked> is not a debugger command.\n");
  1737.             }
  1738.     } else {
  1739.             print_help($summary);
  1740.     }
  1741. }
  1742.  
  1743. sub cmd_l {
  1744.     my $line = shift;
  1745.     $line =~ s/^-\s*$/-/;
  1746.     if ($line =~ /^(\$.*)/s) {
  1747.         $evalarg = $2;
  1748.         my ($s) = &eval;
  1749.         print($OUT "Error: $@\n"), next CMD if $@;
  1750.         $s = CvGV_name($s);
  1751.         print($OUT "Interpreted as: $1 $s\n");
  1752.         $line = "$1 $s";
  1753.         &cmd_l($s);
  1754.     } elsif ($line =~ /^([\':A-Za-z_][\':\w]*(\[.*\])?)/s) { 
  1755.         my $s = $subname = $1;
  1756.         $subname =~ s/\'/::/;
  1757.         $subname = $package."::".$subname 
  1758.         unless $subname =~ /::/;
  1759.         $subname = "CORE::GLOBAL::$s"
  1760.         if not defined &$subname and $s !~ /::/
  1761.              and defined &{"CORE::GLOBAL::$s"};
  1762.         $subname = "main".$subname if substr($subname,0,2) eq "::";
  1763.         @pieces = split(/:/,find_sub($subname) || $sub{$subname});
  1764.         $subrange = pop @pieces;
  1765.         $file = join(':', @pieces);
  1766.         if ($file ne $filename) {
  1767.             print $OUT "Switching to file '$file'.\n"
  1768.         unless $slave_editor;
  1769.             *dbline = $main::{'_<' . $file};
  1770.             $max = $#dbline;
  1771.             $filename = $file;
  1772.         }
  1773.         if ($subrange) {
  1774.             if (eval($subrange) < -$window) {
  1775.         $subrange =~ s/-.*/+/;
  1776.             }
  1777.             $line = $subrange;
  1778.             &cmd_l($subrange);
  1779.         } else {
  1780.             print $OUT "Subroutine $subname not found.\n";
  1781.         }
  1782.     } elsif ($line =~ /^\s*$/) {
  1783.         $incr = $window - 1;
  1784.         $line = $start . '-' . ($start + $incr); 
  1785.         &cmd_l($line);
  1786.     } elsif ($line =~ /^(\d*)\+(\d*)$/) { 
  1787.         $start = $1 if $1;
  1788.         $incr = $2;
  1789.         $incr = $window - 1 unless $incr;
  1790.         $line = $start . '-' . ($start + $incr); 
  1791.         &cmd_l($line);    
  1792.     } elsif ($line =~ /^((-?[\d\$\.]+)([-,]([\d\$\.]+))?)?/) { 
  1793.         $end = (!defined $2) ? $max : ($4 ? $4 : $2);
  1794.         $end = $max if $end > $max;
  1795.         $i = $2;
  1796.         $i = $line if $i eq '.';
  1797.         $i = 1 if $i < 1;
  1798.         $incr = $end - $i;
  1799.         if ($slave_editor) {
  1800.             print $OUT "\032\032$filename:$i:0\n";
  1801.             $i = $end;
  1802.         } else {
  1803.             for (; $i <= $end; $i++) {
  1804.                 my ($stop,$action);
  1805.                 ($stop,$action) = split(/\0/, $dbline{$i}) if
  1806.                         $dbline{$i};
  1807.                             $arrow = ($i==$line 
  1808.                         and $filename eq $filename_ini) 
  1809.                     ?  '==>' 
  1810.                         : ($dbline[$i]+0 ? ':' : ' ') ;
  1811.                 $arrow .= 'b' if $stop;
  1812.                 $arrow .= 'a' if $action;
  1813.                 print $OUT "$i$arrow\t", $dbline[$i];
  1814.                 $i++, last if $signal;
  1815.             }
  1816.             print $OUT "\n" unless $dbline[$i-1] =~ /\n$/;
  1817.         }
  1818.         $start = $i; # remember in case they want more
  1819.         $start = $max if $start > $max;
  1820.     }
  1821. }
  1822.  
  1823. sub cmd_L {
  1824.     my $arg    = shift || 'abw'; $arg = 'abw' unless $CommandSet eq '580'; # sigh...
  1825.     my $action_wanted = ($arg =~ /a/) ? 1 : 0;
  1826.     my $break_wanted  = ($arg =~ /b/) ? 1 : 0;
  1827.     my $watch_wanted  = ($arg =~ /w/) ? 1 : 0;
  1828.  
  1829.     if ($break_wanted or $action_wanted) {
  1830.         for my $file (keys %had_breakpoints) {
  1831.             local *dbline = $main::{'_<' . $file};
  1832.             my $max = $#dbline;
  1833.             my $was;
  1834.             for ($i = 1; $i <= $max; $i++) {
  1835.                 if (defined $dbline{$i}) {
  1836.                     print $OUT "$file:\n" unless $was++;
  1837.                     print $OUT " $i:\t", $dbline[$i];
  1838.                     ($stop,$action) = split(/\0/, $dbline{$i});
  1839.                     print $OUT "   break if (", $stop, ")\n"
  1840.                         if $stop and $break_wanted;
  1841.                     print $OUT "   action:  ", $action, "\n"
  1842.                         if $action and $action_wanted;
  1843.                     last if $signal;
  1844.                 }
  1845.             }
  1846.         }
  1847.     }
  1848.     if (%postponed and $break_wanted) {
  1849.         print $OUT "Postponed breakpoints in subroutines:\n";
  1850.         my $subname;
  1851.         for $subname (keys %postponed) {
  1852.           print $OUT " $subname\t$postponed{$subname}\n";
  1853.           last if $signal;
  1854.         }
  1855.     }
  1856.     my @have = map { # Combined keys
  1857.             keys %{$postponed_file{$_}}
  1858.     } keys %postponed_file;
  1859.     if (@have and ($break_wanted or $action_wanted)) {
  1860.         print $OUT "Postponed breakpoints in files:\n";
  1861.         my ($file, $line);
  1862.         for $file (keys %postponed_file) {
  1863.           my $db = $postponed_file{$file};
  1864.           print $OUT " $file:\n";
  1865.           for $line (sort {$a <=> $b} keys %$db) {
  1866.             print $OUT "  $line:\n";
  1867.             my ($stop,$action) = split(/\0/, $$db{$line});
  1868.             print $OUT "    break if (", $stop, ")\n"
  1869.               if $stop and $break_wanted;
  1870.             print $OUT "    action:  ", $action, "\n"
  1871.               if $action and $action_wanted;
  1872.             last if $signal;
  1873.           }
  1874.           last if $signal;
  1875.         }
  1876.     }
  1877.   if (%break_on_load and $break_wanted) {
  1878.         print $OUT "Breakpoints on load:\n";
  1879.         my $file;
  1880.         for $file (keys %break_on_load) {
  1881.           print $OUT " $file\n";
  1882.           last if $signal;
  1883.         }
  1884.   }
  1885.   if ($watch_wanted) {
  1886.     if ($trace & 2) {
  1887.         print $OUT "Watch-expressions:\n" if @to_watch;
  1888.         for my $expr (@to_watch) {
  1889.             print $OUT " $expr\n";
  1890.             last if $signal;
  1891.         }
  1892.     }
  1893.   }
  1894. }
  1895.  
  1896. sub cmd_M {
  1897.     &list_modules();
  1898. }
  1899.  
  1900. sub cmd_o {
  1901.     my $opt      = shift || ''; # opt[=val]
  1902.     if ($opt =~ /^(\S.*)/) {
  1903.         &parse_options($1);
  1904.     } else {
  1905.         for (@options) {
  1906.             &dump_option($_);
  1907.         }
  1908.     }
  1909. }
  1910.  
  1911. sub cmd_O {
  1912.     print $OUT "The old O command is now the o command.\n";        # hint
  1913.     print $OUT "Use 'h' to get current command help synopsis or\n"; # 
  1914.     print $OUT "use 'o CommandSet=pre580' to revert to old usage\n"; # 
  1915. }
  1916.  
  1917. sub cmd_v {
  1918.     my $line = shift;
  1919.  
  1920.     if ($line =~ /^(\d*)$/) {
  1921.         $incr = $window - 1;
  1922.         $start = $1 if $1;
  1923.         $start -= $preview;
  1924.         $line = $start . '-' . ($start + $incr);
  1925.         &cmd_l($line);
  1926.     }
  1927. }
  1928.  
  1929. sub cmd_w {
  1930.     my $expr     = shift || '';
  1931.     if ($expr =~ /^(\S.*)/) {
  1932.         push @to_watch, $expr;
  1933.         $evalarg = $expr;
  1934.         my ($val) = &eval;
  1935.         $val = (defined $val) ? "'$val'" : 'undef' ;
  1936.         push @old_watch, $val;
  1937.         $trace |= 2;
  1938.     } else {
  1939.         print $OUT "Adding a watch-expression requires an expression\n"; # hint
  1940.     }
  1941. }
  1942.  
  1943. sub cmd_W {
  1944.     my $expr     = shift || '';
  1945.     if ($expr eq '*') {
  1946.         $trace &= ~2;
  1947.         print $OUT "Deleting all watch expressions ...\n";
  1948.         @to_watch = @old_watch = ();
  1949.     } elsif ($expr =~ /^(\S.*)/) {
  1950.         my $i_cnt = 0;
  1951.         foreach (@to_watch) {
  1952.             my $val = $to_watch[$i_cnt];
  1953.             if ($val eq $expr) { # =~ m/^\Q$i$/) {
  1954.                 splice(@to_watch, $i_cnt, 1);
  1955.             }
  1956.             $i_cnt++;
  1957.         }
  1958.     } else {
  1959.         print $OUT "Deleting a watch-expression requires an expression, or '*' for all\n"; # hint
  1960.     }
  1961. }
  1962.  
  1963. ### END of the API section
  1964.  
  1965. sub save {
  1966.     @saved = ($@, $!, $^E, $,, $/, $\, $^W);
  1967.     $, = ""; $/ = "\n"; $\ = ""; $^W = 0;
  1968. }
  1969.  
  1970. sub print_lineinfo {
  1971.   resetterm(1) if $LINEINFO eq $OUT and $term_pid != $$;
  1972.   local $\ = '';
  1973.   local $, = '';
  1974.   print $LINEINFO @_;
  1975. }
  1976.  
  1977. # The following takes its argument via $evalarg to preserve current @_
  1978.  
  1979. sub postponed_sub {
  1980.   my $subname = shift;
  1981.   if ($postponed{$subname} =~ s/^break\s([+-]?\d+)\s+if\s//) {
  1982.     my $offset = $1 || 0;
  1983.     # Filename below can contain ':'
  1984.     my ($file,$i) = (find_sub($subname) =~ /^(.*):(\d+)-.*$/);
  1985.     if ($i) {
  1986.       $i += $offset;
  1987.       local *dbline = $main::{'_<' . $file};
  1988.       local $^W = 0;        # != 0 is magical below
  1989.       $had_breakpoints{$file} |= 1;
  1990.       my $max = $#dbline;
  1991.       ++$i until $dbline[$i] != 0 or $i >= $max;
  1992.       $dbline{$i} = delete $postponed{$subname};
  1993.     } else {
  1994.       local $\ = '';
  1995.       print $OUT "Subroutine $subname not found.\n";
  1996.     }
  1997.     return;
  1998.   }
  1999.   elsif ($postponed{$subname} eq 'compile') { $signal = 1 }
  2000.   #print $OUT "In postponed_sub for `$subname'.\n";
  2001. }
  2002.  
  2003. sub postponed {
  2004.   if ($ImmediateStop) {
  2005.     $ImmediateStop = 0;
  2006.     $signal = 1;
  2007.   }
  2008.   return &postponed_sub
  2009.     unless ref \$_[0] eq 'GLOB'; # A subroutine is compiled.
  2010.   # Cannot be done before the file is compiled
  2011.   local *dbline = shift;
  2012.   my $filename = $dbline;
  2013.   $filename =~ s/^_<//;
  2014.   local $\ = '';
  2015.   $signal = 1, print $OUT "'$filename' loaded...\n"
  2016.     if $break_on_load{$filename};
  2017.   print_lineinfo(' ' x $stack_depth, "Package $filename.\n") if $frame;
  2018.   return unless $postponed_file{$filename};
  2019.   $had_breakpoints{$filename} |= 1;
  2020.   #%dbline = %{$postponed_file{$filename}}; # Cannot be done: unsufficient magic
  2021.   my $key;
  2022.   for $key (keys %{$postponed_file{$filename}}) {
  2023.     $dbline{$key} = ${$postponed_file{$filename}}{$key};
  2024.   }
  2025.   delete $postponed_file{$filename};
  2026. }
  2027.  
  2028. sub dumpit {
  2029.     local ($savout) = select(shift);
  2030.     my $osingle = $single;
  2031.     my $otrace = $trace;
  2032.     $single = $trace = 0;
  2033.     local $frame = 0;
  2034.     local $doret = -2;
  2035.     unless (defined &main::dumpValue) {
  2036.     do 'dumpvar.pl';
  2037.     }
  2038.     if (defined &main::dumpValue) {
  2039.         local $\ = '';
  2040.         local $, = '';
  2041.         local $" = ' ';
  2042.         my $v = shift;
  2043.         my $maxdepth = shift || $option{dumpDepth};
  2044.         $maxdepth = -1 unless defined $maxdepth;   # -1 means infinite depth
  2045.     &main::dumpValue($v, $maxdepth);
  2046.     } else {
  2047.         local $\ = '';
  2048.     print $OUT "dumpvar.pl not available.\n";
  2049.     }
  2050.     $single = $osingle;
  2051.     $trace = $otrace;
  2052.     select ($savout);    
  2053. }
  2054.  
  2055. # Tied method do not create a context, so may get wrong message:
  2056.  
  2057. sub print_trace {
  2058.   local $\ = '';
  2059.   my $fh = shift;
  2060.   resetterm(1) if $fh eq $LINEINFO and $LINEINFO eq $OUT and $term_pid != $$;
  2061.   my @sub = dump_trace($_[0] + 1, $_[1]);
  2062.   my $short = $_[2];        # Print short report, next one for sub name
  2063.   my $s;
  2064.   for ($i=0; $i <= $#sub; $i++) {
  2065.     last if $signal;
  2066.     local $" = ', ';
  2067.     my $args = defined $sub[$i]{args} 
  2068.     ? "(@{ $sub[$i]{args} })"
  2069.       : '' ;
  2070.     $args = (substr $args, 0, $maxtrace - 3) . '...' 
  2071.       if length $args > $maxtrace;
  2072.     my $file = $sub[$i]{file};
  2073.     $file = $file eq '-e' ? $file : "file `$file'" unless $short;
  2074.     $s = $sub[$i]{sub};
  2075.     $s = (substr $s, 0, $maxtrace - 3) . '...' if length $s > $maxtrace;    
  2076.     if ($short) {
  2077.       my $sub = @_ >= 4 ? $_[3] : $s;
  2078.       print $fh "$sub[$i]{context}=$sub$args from $file:$sub[$i]{line}\n";
  2079.     } else {
  2080.       print $fh "$sub[$i]{context} = $s$args" .
  2081.     " called from $file" . 
  2082.       " line $sub[$i]{line}\n";
  2083.     }
  2084.   }
  2085. }
  2086.  
  2087. sub dump_trace {
  2088.   my $skip = shift;
  2089.   my $count = shift || 1e9;
  2090.   $skip++;
  2091.   $count += $skip;
  2092.   my ($p,$file,$line,$sub,$h,$args,$e,$r,@a,@sub,$context);
  2093.   my $nothard = not $frame & 8;
  2094.   local $frame = 0;        # Do not want to trace this.
  2095.   my $otrace = $trace;
  2096.   $trace = 0;
  2097.   for ($i = $skip; 
  2098.        $i < $count and ($p,$file,$line,$sub,$h,$context,$e,$r) = caller($i); 
  2099.        $i++) {
  2100.     @a = ();
  2101.     for $arg (@args) {
  2102.       my $type;
  2103.       if (not defined $arg) {
  2104.     push @a, "undef";
  2105.       } elsif ($nothard and tied $arg) {
  2106.     push @a, "tied";
  2107.       } elsif ($nothard and $type = ref $arg) {
  2108.     push @a, "ref($type)";
  2109.       } else {
  2110.     local $_ = "$arg";    # Safe to stringify now - should not call f().
  2111.     s/([\'\\])/\\$1/g;
  2112.     s/(.*)/'$1'/s
  2113.       unless /^(?: -?[\d.]+ | \*[\w:]* )$/x;
  2114.     s/([\200-\377])/sprintf("M-%c",ord($1)&0177)/eg;
  2115.     s/([\0-\37\177])/sprintf("^%c",ord($1)^64)/eg;
  2116.     push(@a, $_);
  2117.       }
  2118.     }
  2119.     $context = $context ? '@' : (defined $context ? "\$" : '.');
  2120.     $args = $h ? [@a] : undef;
  2121.     $e =~ s/\n\s*\;\s*\Z// if $e;
  2122.     $e =~ s/([\\\'])/\\$1/g if $e;
  2123.     if ($r) {
  2124.       $sub = "require '$e'";
  2125.     } elsif (defined $r) {
  2126.       $sub = "eval '$e'";
  2127.     } elsif ($sub eq '(eval)') {
  2128.       $sub = "eval {...}";
  2129.     }
  2130.     push(@sub, {context => $context, sub => $sub, args => $args,
  2131.         file => $file, line => $line});
  2132.     last if $signal;
  2133.   }
  2134.   $trace = $otrace;
  2135.   @sub;
  2136. }
  2137.  
  2138. sub action {
  2139.     my $action = shift;
  2140.     while ($action =~ s/\\$//) {
  2141.     #print $OUT "+ ";
  2142.     #$action .= "\n";
  2143.     $action .= &gets;
  2144.     }
  2145.     $action;
  2146. }
  2147.  
  2148. sub unbalanced { 
  2149.     # i hate using globals!
  2150.     $balanced_brace_re ||= qr{ 
  2151.     ^ \{
  2152.           (?:
  2153.          (?> [^{}] + )            # Non-parens without backtracking
  2154.            |
  2155.          (??{ $balanced_brace_re }) # Group with matching parens
  2156.           ) *
  2157.       \} $
  2158.    }x;
  2159.    return $_[0] !~ m/$balanced_brace_re/;
  2160. }
  2161.  
  2162. sub gets {
  2163.     &readline("cont: ");
  2164. }
  2165.  
  2166. sub system {
  2167.     # We save, change, then restore STDIN and STDOUT to avoid fork() since
  2168.     # some non-Unix systems can do system() but have problems with fork().
  2169.     open(SAVEIN,"<&STDIN") || &warn("Can't save STDIN");
  2170.     open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
  2171.     open(STDIN,"<&IN") || &warn("Can't redirect STDIN");
  2172.     open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
  2173.  
  2174.     # XXX: using csh or tcsh destroys sigint retvals!
  2175.     system(@_);
  2176.     open(STDIN,"<&SAVEIN") || &warn("Can't restore STDIN");
  2177.     open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
  2178.     close(SAVEIN); 
  2179.     close(SAVEOUT);
  2180.  
  2181.  
  2182.     # most of the $? crud was coping with broken cshisms
  2183.     if ($? >> 8) {
  2184.     &warn("(Command exited ", ($? >> 8), ")\n");
  2185.     } elsif ($?) { 
  2186.     &warn( "(Command died of SIG#",  ($? & 127),
  2187.         (($? & 128) ? " -- core dumped" : "") , ")", "\n");
  2188.     } 
  2189.  
  2190.     return $?;
  2191.  
  2192. }
  2193.  
  2194. sub setterm {
  2195.     local $frame = 0;
  2196.     local $doret = -2;
  2197.     eval { require Term::ReadLine } or die $@;
  2198.     if ($notty) {
  2199.     if ($tty) {
  2200.         my ($i, $o) = split $tty, /,/;
  2201.         $o = $i unless defined $o;
  2202.         open(IN,"<$i") or die "Cannot open TTY `$i' for read: $!";
  2203.         open(OUT,">$o") or die "Cannot open TTY `$o' for write: $!";
  2204.         $IN = \*IN;
  2205.         $OUT = \*OUT;
  2206.         my $sel = select($OUT);
  2207.         $| = 1;
  2208.         select($sel);
  2209.     } else {
  2210.         eval "require Term::Rendezvous;" or die;
  2211.         my $rv = $ENV{PERLDB_NOTTY} || "/tmp/perldbtty$$";
  2212.         my $term_rv = new Term::Rendezvous $rv;
  2213.         $IN = $term_rv->IN;
  2214.         $OUT = $term_rv->OUT;
  2215.     }
  2216.     }
  2217.     if ($term_pid eq '-1') {        # In a TTY with another debugger
  2218.     resetterm(2);
  2219.     }
  2220.     if (!$rl) {
  2221.     $term = new Term::ReadLine::Stub 'perldb', $IN, $OUT;
  2222.     } else {
  2223.     $term = new Term::ReadLine 'perldb', $IN, $OUT;
  2224.  
  2225.     $rl_attribs = $term->Attribs;
  2226.     $rl_attribs->{basic_word_break_characters} .= '-:+/*,[])}' 
  2227.       if defined $rl_attribs->{basic_word_break_characters} 
  2228.         and index($rl_attribs->{basic_word_break_characters}, ":") == -1;
  2229.     $rl_attribs->{special_prefixes} = '$@&%';
  2230.     $rl_attribs->{completer_word_break_characters} .= '$@&%';
  2231.     $rl_attribs->{completion_function} = \&db_complete; 
  2232.     }
  2233.     $LINEINFO = $OUT unless defined $LINEINFO;
  2234.     $lineinfo = $console unless defined $lineinfo;
  2235.     $term->MinLine(2);
  2236.     if ($term->Features->{setHistory} and "@hist" ne "?") {
  2237.       $term->SetHistory(@hist);
  2238.     }
  2239.     ornaments($ornaments) if defined $ornaments;
  2240.     $term_pid = $$;
  2241. }
  2242.  
  2243. # Example get_fork_TTY functions
  2244. sub xterm_get_fork_TTY {
  2245.   (my $name = $0) =~ s,^.*[/\\],,s;
  2246.   open XT, qq[3>&1 xterm -title "Daughter Perl debugger $pids $name" -e sh -c 'tty 1>&3;\
  2247.  sleep 10000000' |];
  2248.   my $tty = <XT>;
  2249.   chomp $tty;
  2250.   $pidprompt = '';        # Shown anyway in titlebar
  2251.   return $tty;
  2252. }
  2253.  
  2254. # This example function resets $IN, $OUT itself
  2255. sub os2_get_fork_TTY {
  2256.   local $^F = 40;            # XXXX Fixme!
  2257.   local $\ = '';
  2258.   my ($in1, $out1, $in2, $out2);
  2259.   # Having -d in PERL5OPT would lead to a disaster...
  2260.   local $ENV{PERL5OPT} = $ENV{PERL5OPT}    if $ENV{PERL5OPT};
  2261.   $ENV{PERL5OPT} =~ s/(?:^|(?<=\s))-d\b//  if $ENV{PERL5OPT};
  2262.   $ENV{PERL5OPT} =~ s/(?:^|(?<=\s))-d\B/-/ if $ENV{PERL5OPT};
  2263.   print $OUT "Making kid PERL5OPT->`$ENV{PERL5OPT}'.\n" if $ENV{PERL5OPT};
  2264.   local $ENV{PERL5LIB} = $ENV{PERL5LIB} ? $ENV{PERL5LIB} : $ENV{PERLLIB};
  2265.   $ENV{PERL5LIB} = '' unless defined $ENV{PERL5LIB};
  2266.   $ENV{PERL5LIB} = join ';', @ini_INC, split /;/, $ENV{PERL5LIB};
  2267.   (my $name = $0) =~ s,^.*[/\\],,s;
  2268.   my @args;
  2269.   if ( pipe $in1, $out1 and pipe $in2, $out2
  2270.        # system P_SESSION will fail if there is another process
  2271.        # in the same session with a "dependent" asynchronous child session.
  2272.        and @args = ($rl, fileno $in1, fileno $out2,
  2273.             "Daughter Perl debugger $pids $name") and
  2274.        (($kpid = CORE::system 4, $^X, '-we', <<'ES', @args) >= 0 # P_SESSION
  2275. END {sleep 5 unless $loaded}
  2276. BEGIN {open STDIN,  '</dev/con' or warn "reopen stdin: $!"}
  2277. use OS2::Process;
  2278.  
  2279. my ($rl, $in) = (shift, shift);        # Read from $in and pass through
  2280. set_title pop;
  2281. system P_NOWAIT, $^X, '-we', <<EOS or die "Cannot start a grandkid";
  2282.   open IN, '<&=$in' or die "open <&=$in: \$!";
  2283.   \$| = 1; print while sysread IN, \$_, 1<<16;
  2284. EOS
  2285.  
  2286. my $out = shift;
  2287. open OUT, ">&=$out" or die "Cannot open &=$out for writing: $!";
  2288. select OUT;    $| = 1;
  2289. require Term::ReadKey if $rl;
  2290. Term::ReadKey::ReadMode(4) if $rl; # Nodelay on kbd.  Pipe is automatically nodelay...
  2291. print while sysread STDIN, $_, 1<<($rl ? 16 : 0);
  2292. ES
  2293.      or warn "system P_SESSION: $!, $^E" and 0)
  2294.     and close $in1 and close $out2 ) {
  2295.       $pidprompt = '';            # Shown anyway in titlebar
  2296.       reset_IN_OUT($in2, $out1);
  2297.       $tty = '*reset*';
  2298.       return '';            # Indicate that reset_IN_OUT is called
  2299.    }
  2300.    return;
  2301. }
  2302.  
  2303. sub create_IN_OUT {    # Create a window with IN/OUT handles redirected there
  2304.     my $in = &get_fork_TTY if defined &get_fork_TTY;
  2305.     $in = $fork_TTY if defined $fork_TTY; # Backward compatibility
  2306.     if (not defined $in) {
  2307.       my $why = shift;
  2308.       print_help(<<EOP) if $why == 1;
  2309. I<#########> Forked, but do not know how to create a new B<TTY>. I<#########>
  2310. EOP
  2311.       print_help(<<EOP) if $why == 2;
  2312. I<#########> Daughter session, do not know how to change a B<TTY>. I<#########>
  2313.   This may be an asynchronous session, so the parent debugger may be active.
  2314. EOP
  2315.       print_help(<<EOP) if $why != 4;
  2316.   Since two debuggers fight for the same TTY, input is severely entangled.
  2317.  
  2318. EOP
  2319.       print_help(<<EOP);
  2320.   I know how to switch the output to a different window in xterms
  2321.   and OS/2 consoles only.  For a manual switch, put the name of the created I<TTY>
  2322.   in B<\$DB::fork_TTY>, or define a function B<DB::get_fork_TTY()> returning this.
  2323.  
  2324.   On I<UNIX>-like systems one can get the name of a I<TTY> for the given window
  2325.   by typing B<tty>, and disconnect the I<shell> from I<TTY> by B<sleep 1000000>.
  2326.  
  2327. EOP
  2328.     } elsif ($in ne '') {
  2329.       TTY($in);
  2330.     } else {
  2331.       $console = '';        # Indicate no need to open-from-the-console 
  2332.     }
  2333.     undef $fork_TTY;
  2334. }
  2335.  
  2336. sub resetterm {            # We forked, so we need a different TTY
  2337.     my $in = shift;
  2338.     my $systemed = $in > 1 ? '-' : '';
  2339.     if ($pids) {
  2340.       $pids =~ s/\]/$systemed->$$]/;
  2341.     } else {
  2342.       $pids = "[$term_pid->$$]";
  2343.     }
  2344.     $pidprompt = $pids;
  2345.     $term_pid = $$;
  2346.     return unless $CreateTTY & $in;
  2347.     create_IN_OUT($in);
  2348. }
  2349.  
  2350. sub readline {
  2351.   local $.;
  2352.   if (@typeahead) {
  2353.     my $left = @typeahead;
  2354.     my $got = shift @typeahead;
  2355.     local $\ = '';
  2356.     print $OUT "auto(-$left)", shift, $got, "\n";
  2357.     $term->AddHistory($got) 
  2358.       if length($got) > 1 and defined $term->Features->{addHistory};
  2359.     return $got;
  2360.   }
  2361.   local $frame = 0;
  2362.   local $doret = -2;
  2363.   while (@cmdfhs) {
  2364.     my $line = CORE::readline($cmdfhs[-1]);
  2365.     defined $line ? (print $OUT ">> $line" and return $line)
  2366.                   : close pop @cmdfhs;
  2367.   }
  2368.   if (ref $OUT and UNIVERSAL::isa($OUT, 'IO::Socket::INET')) {
  2369.     $OUT->write(join('', @_));
  2370.     my $stuff;
  2371.     $IN->recv( $stuff, 2048 );  # XXX: what's wrong with sysread?
  2372.     $stuff;
  2373.   }
  2374.   else {
  2375.     $term->readline(@_);
  2376.   }
  2377. }
  2378.  
  2379. sub dump_option {
  2380.     my ($opt, $val)= @_;
  2381.     $val = option_val($opt,'N/A');
  2382.     $val =~ s/([\\\'])/\\$1/g;
  2383.     printf $OUT "%20s = '%s'\n", $opt, $val;
  2384. }
  2385.  
  2386. sub option_val {
  2387.     my ($opt, $default)= @_;
  2388.     my $val;
  2389.     if (defined $optionVars{$opt}
  2390.     and defined ${$optionVars{$opt}}) {
  2391.     $val = ${$optionVars{$opt}};
  2392.     } elsif (defined $optionAction{$opt}
  2393.     and defined &{$optionAction{$opt}}) {
  2394.     $val = &{$optionAction{$opt}}();
  2395.     } elsif (defined $optionAction{$opt}
  2396.          and not defined $option{$opt}
  2397.          or defined $optionVars{$opt}
  2398.          and not defined ${$optionVars{$opt}}) {
  2399.     $val = $default;
  2400.     } else {
  2401.     $val = $option{$opt};
  2402.     }
  2403.     $val = $default unless defined $val;
  2404.     $val
  2405. }
  2406.  
  2407. sub parse_options {
  2408.     local($_)= @_;
  2409.     local $\ = '';
  2410.     # too dangerous to let intuitive usage overwrite important things
  2411.     # defaultion should never be the default
  2412.     my %opt_needs_val = map { ( $_ => 1 ) } qw{
  2413.         dumpDepth arrayDepth hashDepth LineInfo maxTraceLen ornaments windowSize
  2414.         pager quote ReadLine recallCommand RemotePort ShellBang TTY
  2415.     };
  2416.     while (length) {
  2417.     my $val_defaulted;
  2418.     s/^\s+// && next;
  2419.     s/^(\w+)(\W?)// or print($OUT "Invalid option `$_'\n"), last;
  2420.     my ($opt,$sep) = ($1,$2);
  2421.     my $val;
  2422.     if ("?" eq $sep) {
  2423.         print($OUT "Option query `$opt?' followed by non-space `$_'\n"), last
  2424.           if /^\S/;
  2425.         #&dump_option($opt);
  2426.     } elsif ($sep !~ /\S/) {
  2427.         $val_defaulted = 1;
  2428.         $val = "1";  #  this is an evil default; make 'em set it!
  2429.     } elsif ($sep eq "=") {
  2430.             if (s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x) { 
  2431.                 my $quote = $1;
  2432.                 ($val = $2) =~ s/\\([$quote\\])/$1/g;
  2433.         } else { 
  2434.         s/^(\S*)//;
  2435.         $val = $1;
  2436.         print OUT qq(Option better cleared using $opt=""\n)
  2437.             unless length $val;
  2438.         }
  2439.  
  2440.     } else { #{ to "let some poor schmuck bounce on the % key in B<vi>."
  2441.         my ($end) = "\\" . substr( ")]>}$sep", index("([<{",$sep), 1 ); #}
  2442.         s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)// or
  2443.           print($OUT "Unclosed option value `$opt$sep$_'\n"), last;
  2444.         ($val = $1) =~ s/\\([\\$end])/$1/g;
  2445.     }
  2446.  
  2447.     my $option;
  2448.     my $matches = grep( /^\Q$opt/  && ($option = $_),  @options  )
  2449.            || grep( /^\Q$opt/i && ($option = $_),  @options  );
  2450.  
  2451.     print($OUT "Unknown option `$opt'\n"), next     unless $matches;
  2452.     print($OUT "Ambiguous option `$opt'\n"), next     if $matches > 1;
  2453.  
  2454.        if ($opt_needs_val{$option} && $val_defaulted) {
  2455.              my $cmd = ($CommandSet eq '580') ? 'o' : 'O';
  2456.         print $OUT "Option `$opt' is non-boolean.  Use `$cmd $option=VAL' to set, `$cmd $option?' to query\n";
  2457.         next;
  2458.     } 
  2459.  
  2460.     $option{$option} = $val if defined $val;
  2461.  
  2462.     eval qq{
  2463.         local \$frame = 0; 
  2464.         local \$doret = -2; 
  2465.             require '$optionRequire{$option}';
  2466.         1;
  2467.      } || die  # XXX: shouldn't happen
  2468.         if  defined $optionRequire{$option}        &&
  2469.             defined $val;
  2470.  
  2471.     ${$optionVars{$option}} = $val         
  2472.         if  defined $optionVars{$option}        &&
  2473.         defined $val;
  2474.  
  2475.     &{$optionAction{$option}} ($val)    
  2476.         if defined $optionAction{$option}        &&
  2477.                defined &{$optionAction{$option}}    &&
  2478.                defined $val;
  2479.  
  2480.     # Not $rcfile
  2481.     dump_option($option)     unless $OUT eq \*STDERR; 
  2482.     }
  2483. }
  2484.  
  2485. sub set_list {
  2486.   my ($stem,@list) = @_;
  2487.   my $val;
  2488.   $ENV{"${stem}_n"} = @list;
  2489.   for $i (0 .. $#list) {
  2490.     $val = $list[$i];
  2491.     $val =~ s/\\/\\\\/g;
  2492.     $val =~ s/([\0-\37\177\200-\377])/"\\0x" . unpack('H2',$1)/eg;
  2493.     $ENV{"${stem}_$i"} = $val;
  2494.   }
  2495. }
  2496.  
  2497. sub get_list {
  2498.   my $stem = shift;
  2499.   my @list;
  2500.   my $n = delete $ENV{"${stem}_n"};
  2501.   my $val;
  2502.   for $i (0 .. $n - 1) {
  2503.     $val = delete $ENV{"${stem}_$i"};
  2504.     $val =~ s/\\((\\)|0x(..))/ $2 ? $2 : pack('H2', $3) /ge;
  2505.     push @list, $val;
  2506.   }
  2507.   @list;
  2508. }
  2509.  
  2510. sub catch {
  2511.     $signal = 1;
  2512.     return;            # Put nothing on the stack - malloc/free land!
  2513. }
  2514.  
  2515. sub warn {
  2516.     my($msg)= join("",@_);
  2517.     $msg .= ": $!\n" unless $msg =~ /\n$/;
  2518.     local $\ = '';
  2519.     print $OUT $msg;
  2520. }
  2521.  
  2522. sub reset_IN_OUT {
  2523.     my $switch_li = $LINEINFO eq $OUT;
  2524.     if ($term and $term->Features->{newTTY}) {
  2525.       ($IN, $OUT) = (shift, shift);
  2526.       $term->newTTY($IN, $OUT);
  2527.     } elsif ($term) {
  2528.     &warn("Too late to set IN/OUT filehandles, enabled on next `R'!\n");
  2529.     } else {
  2530.       ($IN, $OUT) = (shift, shift);
  2531.     }
  2532.     my $o = select $OUT;
  2533.     $| = 1;
  2534.     select $o;
  2535.     $LINEINFO = $OUT if $switch_li;
  2536. }
  2537.  
  2538. sub TTY {
  2539.     if (@_ and $term and $term->Features->{newTTY}) {
  2540.       my ($in, $out) = shift;
  2541.       if ($in =~ /,/) {
  2542.     ($in, $out) = split /,/, $in, 2;
  2543.       } else {
  2544.     $out = $in;
  2545.       }
  2546.       open IN, $in or die "cannot open `$in' for read: $!";
  2547.       open OUT, ">$out" or die "cannot open `$out' for write: $!";
  2548.       reset_IN_OUT(\*IN,\*OUT);
  2549.       return $tty = $in;
  2550.     }
  2551.     &warn("Too late to set TTY, enabled on next `R'!\n") if $term and @_;
  2552.     # Useful if done through PERLDB_OPTS:
  2553.     $console = $tty = shift if @_;
  2554.     $tty or $console;
  2555. }
  2556.  
  2557. sub noTTY {
  2558.     if ($term) {
  2559.     &warn("Too late to set noTTY, enabled on next `R'!\n") if @_;
  2560.     }
  2561.     $notty = shift if @_;
  2562.     $notty;
  2563. }
  2564.  
  2565. sub ReadLine {
  2566.     if ($term) {
  2567.     &warn("Too late to set ReadLine, enabled on next `R'!\n") if @_;
  2568.     }
  2569.     $rl = shift if @_;
  2570.     $rl;
  2571. }
  2572.  
  2573. sub RemotePort {
  2574.     if ($term) {
  2575.         &warn("Too late to set RemotePort, enabled on next 'R'!\n") if @_;
  2576.     }
  2577.     $remoteport = shift if @_;
  2578.     $remoteport;
  2579. }
  2580.  
  2581. sub tkRunning {
  2582.     if (${$term->Features}{tkRunning}) {
  2583.         return $term->tkRunning(@_);
  2584.     } else {
  2585.     local $\ = '';
  2586.     print $OUT "tkRunning not supported by current ReadLine package.\n";
  2587.     0;
  2588.     }
  2589. }
  2590.  
  2591. sub NonStop {
  2592.     if ($term) {
  2593.     &warn("Too late to set up NonStop mode, enabled on next `R'!\n") if @_;
  2594.     }
  2595.     $runnonstop = shift if @_;
  2596.     $runnonstop;
  2597. }
  2598.  
  2599. sub pager {
  2600.     if (@_) {
  2601.     $pager = shift;
  2602.     $pager="|".$pager unless $pager =~ /^(\+?\>|\|)/;
  2603.     }
  2604.     $pager;
  2605. }
  2606.  
  2607. sub shellBang {
  2608.     if (@_) {
  2609.     $sh = quotemeta shift;
  2610.     $sh .= "\\b" if $sh =~ /\w$/;
  2611.     }
  2612.     $psh = $sh;
  2613.     $psh =~ s/\\b$//;
  2614.     $psh =~ s/\\(.)/$1/g;
  2615.     $psh;
  2616. }
  2617.  
  2618. sub ornaments {
  2619.   if (defined $term) {
  2620.     local ($warnLevel,$dieLevel) = (0, 1);
  2621.     return '' unless $term->Features->{ornaments};
  2622.     eval { $term->ornaments(@_) } || '';
  2623.   } else {
  2624.     $ornaments = shift;
  2625.   }
  2626. }
  2627.  
  2628. sub recallCommand {
  2629.     if (@_) {
  2630.     $rc = quotemeta shift;
  2631.     $rc .= "\\b" if $rc =~ /\w$/;
  2632.     }
  2633.     $prc = $rc;
  2634.     $prc =~ s/\\b$//;
  2635.     $prc =~ s/\\(.)/$1/g;
  2636.     $prc;
  2637. }
  2638.  
  2639. sub LineInfo {
  2640.     return $lineinfo unless @_;
  2641.     $lineinfo = shift;
  2642.     my $stream = ($lineinfo =~ /^(\+?\>|\|)/) ? $lineinfo : ">$lineinfo";
  2643.     $slave_editor = ($stream =~ /^\|/);
  2644.     open(LINEINFO, "$stream") || &warn("Cannot open `$stream' for write");
  2645.     $LINEINFO = \*LINEINFO;
  2646.     my $save = select($LINEINFO);
  2647.     $| = 1;
  2648.     select($save);
  2649.     $lineinfo;
  2650. }
  2651.  
  2652. sub list_modules { # versions
  2653.   my %version;
  2654.   my $file;
  2655.   for (keys %INC) {
  2656.     $file = $_;
  2657.     s,\.p[lm]$,,i ;
  2658.     s,/,::,g ;
  2659.     s/^perl5db$/DB/;
  2660.     s/^Term::ReadLine::readline$/readline/;
  2661.     if (defined ${ $_ . '::VERSION' }) {
  2662.       $version{$file} = "${ $_ . '::VERSION' } from ";
  2663.     } 
  2664.     $version{$file} .= $INC{$file};
  2665.   }
  2666.   dumpit($OUT,\%version);
  2667. }
  2668.  
  2669. sub sethelp {
  2670.     # XXX: make sure there are tabs between the command and explanation,
  2671.     #      or print_help will screw up your formatting if you have
  2672.     #      eeevil ornaments enabled.  This is an insane mess.
  2673.  
  2674.     $help = "
  2675. Help is currently only available for the new 580 CommandSet, 
  2676. if you really want old behaviour, presumably you know what 
  2677. you're doing ?-)
  2678.  
  2679. B<T>        Stack trace.
  2680. B<s> [I<expr>]    Single step [in I<expr>].
  2681. B<n> [I<expr>]    Next, steps over subroutine calls [in I<expr>].
  2682. <B<CR>>        Repeat last B<n> or B<s> command.
  2683. B<r>        Return from current subroutine.
  2684. B<c> [I<line>|I<sub>]    Continue; optionally inserts a one-time-only breakpoint
  2685.         at the specified position.
  2686. B<l> I<min>B<+>I<incr>    List I<incr>+1 lines starting at I<min>.
  2687. B<l> I<min>B<->I<max>    List lines I<min> through I<max>.
  2688. B<l> I<line>        List single I<line>.
  2689. B<l> I<subname>    List first window of lines from subroutine.
  2690. B<l> I<\$var>        List first window of lines from subroutine referenced by I<\$var>.
  2691. B<l>        List next window of lines.
  2692. B<->        List previous window of lines.
  2693. B<v> [I<line>]    View window around I<line>.
  2694. B<.>        Return to the executed line.
  2695. B<f> I<filename>    Switch to viewing I<filename>. File must be already loaded.
  2696.         I<filename> may be either the full name of the file, or a regular
  2697.         expression matching the full file name:
  2698.         B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
  2699.         Evals (with saved bodies) are considered to be filenames:
  2700.         B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
  2701.         (in the order of execution).
  2702. B</>I<pattern>B</>    Search forwards for I<pattern>; final B</> is optional.
  2703. B<?>I<pattern>B<?>    Search backwards for I<pattern>; final B<?> is optional.
  2704. B<L> [I<a|b|w>]        List actions and or breakpoints and or watch-expressions.
  2705. B<S> [[B<!>]I<pattern>]    List subroutine names [not] matching I<pattern>.
  2706. B<t>        Toggle trace mode.
  2707. B<t> I<expr>        Trace through execution of I<expr>.
  2708. B<b>        Sets breakpoint on current line)
  2709. B<b> [I<line>] [I<condition>]
  2710.         Set breakpoint; I<line> defaults to the current execution line;
  2711.         I<condition> breaks if it evaluates to true, defaults to '1'.
  2712. B<b> I<subname> [I<condition>]
  2713.         Set breakpoint at first line of subroutine.
  2714. B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
  2715. B<b> B<load> I<filename> Set breakpoint on 'require'ing the given file.
  2716. B<b> B<postpone> I<subname> [I<condition>]
  2717.         Set breakpoint at first line of subroutine after 
  2718.         it is compiled.
  2719. B<b> B<compile> I<subname>
  2720.         Stop after the subroutine is compiled.
  2721. B<B> [I<line>]    Delete the breakpoint for I<line>.
  2722. B<B> I<*>             Delete all breakpoints.
  2723. B<a> [I<line>] I<command>
  2724.         Set an action to be done before the I<line> is executed;
  2725.         I<line> defaults to the current execution line.
  2726.         Sequence is: check for breakpoint/watchpoint, print line
  2727.         if necessary, do action, prompt user if necessary,
  2728.         execute line.
  2729. B<a>        Does nothing
  2730. B<A> [I<line>]    Delete the action for I<line>.
  2731. B<A> I<*>             Delete all actions.
  2732. B<w> I<expr>        Add a global watch-expression.
  2733. B<w>             Does nothing
  2734. B<W> I<expr>        Delete a global watch-expression.
  2735. B<W> I<*>             Delete all watch-expressions.
  2736. B<V> [I<pkg> [I<vars>]]    List some (default all) variables in package (default current).
  2737.         Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
  2738. B<X> [I<vars>]    Same as \"B<V> I<currentpackage> [I<vars>]\".
  2739. B<x> I<expr>        Evals expression in list context, dumps the result.
  2740. B<m> I<expr>        Evals expression in list context, prints methods callable
  2741.         on the first element of the result.
  2742. B<m> I<class>        Prints methods callable via the given class.
  2743. B<M>        Show versions of loaded modules.
  2744.  
  2745. B<<> ?            List Perl commands to run before each prompt.
  2746. B<<> I<expr>        Define Perl command to run before each prompt.
  2747. B<<<> I<expr>        Add to the list of Perl commands to run before each prompt.
  2748. B<>> ?            List Perl commands to run after each prompt.
  2749. B<>> I<expr>        Define Perl command to run after each prompt.
  2750. B<>>B<>> I<expr>        Add to the list of Perl commands to run after each prompt.
  2751. B<{> I<db_command>    Define debugger command to run before each prompt.
  2752. B<{> ?            List debugger commands to run before each prompt.
  2753. B<{{> I<db_command>    Add to the list of debugger commands to run before each prompt.
  2754. B<$prc> I<number>    Redo a previous command (default previous command).
  2755. B<$prc> I<-number>    Redo number'th-to-last command.
  2756. B<$prc> I<pattern>    Redo last command that started with I<pattern>.
  2757.         See 'B<O> I<recallCommand>' too.
  2758. B<$psh$psh> I<cmd>      Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
  2759.   . ( $rc eq $sh ? "" : "
  2760. B<$psh> [I<cmd>]     Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")." ) . "
  2761.         See 'B<O> I<shellBang>' too.
  2762. B<source> I<file>        Execute I<file> containing debugger commands (may nest).
  2763. B<H> I<-number>    Display last number commands (default all).
  2764. B<p> I<expr>        Same as \"I<print {DB::OUT} expr>\" in current package.
  2765. B<|>I<dbcmd>        Run debugger command, piping DB::OUT to current pager.
  2766. B<||>I<dbcmd>        Same as B<|>I<dbcmd> but DB::OUT is temporarilly select()ed as well.
  2767. B<\=> [I<alias> I<value>]    Define a command alias, or list current aliases.
  2768. I<command>        Execute as a perl statement in current package.
  2769. B<R>        Pure-man-restart of debugger, some of debugger state
  2770.         and command-line options may be lost.
  2771.         Currently the following settings are preserved:
  2772.         history, breakpoints and actions, debugger B<O>ptions 
  2773.         and the following command-line options: I<-w>, I<-I>, I<-e>.
  2774.  
  2775. B<o> [I<opt>] ...    Set boolean option to true
  2776. B<o> [I<opt>B<?>]    Query options
  2777. B<o> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ... 
  2778.         Set options.  Use quotes in spaces in value.
  2779.     I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
  2780.     I<pager>            program for output of \"|cmd\";
  2781.     I<tkRunning>            run Tk while prompting (with ReadLine);
  2782.     I<signalLevel> I<warnLevel> I<dieLevel>    level of verbosity;
  2783.     I<inhibit_exit>        Allows stepping off the end of the script.
  2784.     I<ImmediateStop>        Debugger should stop as early as possible.
  2785.     I<RemotePort>            Remote hostname:port for remote debugging
  2786.   The following options affect what happens with B<V>, B<X>, and B<x> commands:
  2787.     I<arrayDepth>, I<hashDepth>     print only first N elements ('' for all);
  2788.     I<compactDump>, I<veryCompact>     change style of array and hash dump;
  2789.     I<globPrint>             whether to print contents of globs;
  2790.     I<DumpDBFiles>         dump arrays holding debugged files;
  2791.     I<DumpPackages>         dump symbol tables of packages;
  2792.     I<DumpReused>             dump contents of \"reused\" addresses;
  2793.     I<quote>, I<HighBit>, I<undefPrint>     change style of string dump;
  2794.     I<bareStringify>         Do not print the overload-stringified value;
  2795.   Other options include:
  2796.     I<PrintRet>        affects printing of return value after B<r> command,
  2797.     I<frame>        affects printing messages on subroutine entry/exit.
  2798.     I<AutoTrace>    affects printing messages on possible breaking points.
  2799.     I<maxTraceLen>    gives max length of evals/args listed in stack trace.
  2800.     I<ornaments>     affects screen appearance of the command line.
  2801.     I<CreateTTY>     bits control attempts to create a new TTY on events:
  2802.             1: on fork()    2: debugger is started inside debugger
  2803.             4: on startup
  2804.     During startup options are initialized from \$ENV{PERLDB_OPTS}.
  2805.     You can put additional initialization options I<TTY>, I<noTTY>,
  2806.     I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
  2807.     `B<R>' after you set them).
  2808.  
  2809. B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction.
  2810. B<h>        Summary of debugger commands.
  2811. B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
  2812. B<h h>        Long help for debugger commands
  2813. B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the 
  2814.         named Perl I<manpage>, or on B<$doccmd> itself if omitted.
  2815.         Set B<\$DB::doccmd> to change viewer.
  2816.  
  2817. Type `|h h' for a paged display if this was too hard to read.
  2818.  
  2819. "; # Fix balance of vi % matching: }}}}
  2820.  
  2821.     #  note: tabs in the following section are not-so-helpful
  2822.     $summary = <<"END_SUM";
  2823. I<List/search source lines:>               I<Control script execution:>
  2824.   B<l> [I<ln>|I<sub>]  List source code            B<T>           Stack trace
  2825.   B<-> or B<.>      List previous/current line  B<s> [I<expr>]    Single step [in expr]
  2826.   B<v> [I<line>]    View around line            B<n> [I<expr>]    Next, steps over subs
  2827.   B<f> I<filename>  View source in file         <B<CR>/B<Enter>>  Repeat last B<n> or B<s>
  2828.   B</>I<pattern>B</> B<?>I<patt>B<?>   Search forw/backw    B<r>           Return from subroutine
  2829.   B<M>           Show module versions        B<c> [I<ln>|I<sub>]  Continue until position
  2830. I<Debugger controls:>                        B<L>           List break/watch/actions
  2831.   B<o> [...]     Set debugger options        B<t> [I<expr>]    Toggle trace [trace expr]
  2832.   B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
  2833.   B<$prc> [I<N>|I<pat>]   Redo a previous command     B<B> I<ln|*>      Delete a/all breakpoints
  2834.   B<H> [I<-num>]    Display last num commands   B<a> [I<ln>] I<cmd>  Do cmd before line
  2835.   B<=> [I<a> I<val>]   Define/list an alias        B<A> I<ln|*>      Delete a/all actions
  2836.   B<h> [I<db_cmd>]  Get help on command         B<w> I<expr>      Add a watch expression
  2837.   B<h h>         Complete help page          B<W> I<expr|*>    Delete a/all watch exprs
  2838.   B<|>[B<|>]I<db_cmd>  Send output to pager        B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
  2839.   B<q> or B<^D>     Quit                        B<R>           Attempt a restart
  2840. I<Data Examination:>     B<expr>     Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
  2841.   B<x>|B<m> I<expr>       Evals expr in list context, dumps the result or lists methods.
  2842.   B<p> I<expr>         Print expression (uses script's current package).
  2843.   B<S> [[B<!>]I<pat>]     List subroutine names [not] matching pattern
  2844.   B<V> [I<Pk> [I<Vars>]]  List Variables in Package.  Vars can be ~pattern or !pattern.
  2845.   B<X> [I<Vars>]       Same as \"B<V> I<current_package> [I<Vars>]\".
  2846.   B<y> [I<n> [I<Vars>]]   List lexicals in higher scope <n>.  Vars same as B<V>.
  2847. For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
  2848. END_SUM
  2849.                 # ')}}; # Fix balance of vi % matching
  2850.  
  2851.     # and this is really numb...
  2852.     $pre580_help = "
  2853. B<T>        Stack trace.
  2854. B<s> [I<expr>]    Single step [in I<expr>].
  2855. B<n> [I<expr>]    Next, steps over subroutine calls [in I<expr>].
  2856. <B<CR>>        Repeat last B<n> or B<s> command.
  2857. B<r>        Return from current subroutine.
  2858. B<c> [I<line>|I<sub>]    Continue; optionally inserts a one-time-only breakpoint
  2859.         at the specified position.
  2860. B<l> I<min>B<+>I<incr>    List I<incr>+1 lines starting at I<min>.
  2861. B<l> I<min>B<->I<max>    List lines I<min> through I<max>.
  2862. B<l> I<line>        List single I<line>.
  2863. B<l> I<subname>    List first window of lines from subroutine.
  2864. B<l> I<\$var>        List first window of lines from subroutine referenced by I<\$var>.
  2865. B<l>        List next window of lines.
  2866. B<->        List previous window of lines.
  2867. B<w> [I<line>]    List window around I<line>.
  2868. B<.>        Return to the executed line.
  2869. B<f> I<filename>    Switch to viewing I<filename>. File must be already loaded.
  2870.         I<filename> may be either the full name of the file, or a regular
  2871.         expression matching the full file name:
  2872.         B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
  2873.         Evals (with saved bodies) are considered to be filenames:
  2874.         B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
  2875.         (in the order of execution).
  2876. B</>I<pattern>B</>    Search forwards for I<pattern>; final B</> is optional.
  2877. B<?>I<pattern>B<?>    Search backwards for I<pattern>; final B<?> is optional.
  2878. B<L>        List all breakpoints and actions.
  2879. B<S> [[B<!>]I<pattern>]    List subroutine names [not] matching I<pattern>.
  2880. B<t>        Toggle trace mode.
  2881. B<t> I<expr>        Trace through execution of I<expr>.
  2882. B<b> [I<line>] [I<condition>]
  2883.         Set breakpoint; I<line> defaults to the current execution line;
  2884.         I<condition> breaks if it evaluates to true, defaults to '1'.
  2885. B<b> I<subname> [I<condition>]
  2886.         Set breakpoint at first line of subroutine.
  2887. B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
  2888. B<b> B<load> I<filename> Set breakpoint on `require'ing the given file.
  2889. B<b> B<postpone> I<subname> [I<condition>]
  2890.         Set breakpoint at first line of subroutine after 
  2891.         it is compiled.
  2892. B<b> B<compile> I<subname>
  2893.         Stop after the subroutine is compiled.
  2894. B<d> [I<line>]    Delete the breakpoint for I<line>.
  2895. B<D>        Delete all breakpoints.
  2896. B<a> [I<line>] I<command>
  2897.         Set an action to be done before the I<line> is executed;
  2898.         I<line> defaults to the current execution line.
  2899.         Sequence is: check for breakpoint/watchpoint, print line
  2900.         if necessary, do action, prompt user if necessary,
  2901.         execute line.
  2902. B<a> [I<line>]    Delete the action for I<line>.
  2903. B<A>        Delete all actions.
  2904. B<W> I<expr>        Add a global watch-expression.
  2905. B<W>        Delete all watch-expressions.
  2906. B<V> [I<pkg> [I<vars>]]    List some (default all) variables in package (default current).
  2907.         Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
  2908. B<X> [I<vars>]    Same as \"B<V> I<currentpackage> [I<vars>]\".
  2909. B<x> I<expr>        Evals expression in list context, dumps the result.
  2910. B<m> I<expr>        Evals expression in list context, prints methods callable
  2911.         on the first element of the result.
  2912. B<m> I<class>        Prints methods callable via the given class.
  2913.  
  2914. B<<> ?            List Perl commands to run before each prompt.
  2915. B<<> I<expr>        Define Perl command to run before each prompt.
  2916. B<<<> I<expr>        Add to the list of Perl commands to run before each prompt.
  2917. B<>> ?            List Perl commands to run after each prompt.
  2918. B<>> I<expr>        Define Perl command to run after each prompt.
  2919. B<>>B<>> I<expr>        Add to the list of Perl commands to run after each prompt.
  2920. B<{> I<db_command>    Define debugger command to run before each prompt.
  2921. B<{> ?            List debugger commands to run before each prompt.
  2922. B<{{> I<db_command>    Add to the list of debugger commands to run before each prompt.
  2923. B<$prc> I<number>    Redo a previous command (default previous command).
  2924. B<$prc> I<-number>    Redo number'th-to-last command.
  2925. B<$prc> I<pattern>    Redo last command that started with I<pattern>.
  2926.         See 'B<O> I<recallCommand>' too.
  2927. B<$psh$psh> I<cmd>      Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
  2928.   . ( $rc eq $sh ? "" : "
  2929. B<$psh> [I<cmd>]     Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")." ) . "
  2930.         See 'B<O> I<shellBang>' too.
  2931. B<source> I<file>        Execute I<file> containing debugger commands (may nest).
  2932. B<H> I<-number>    Display last number commands (default all).
  2933. B<p> I<expr>        Same as \"I<print {DB::OUT} expr>\" in current package.
  2934. B<|>I<dbcmd>        Run debugger command, piping DB::OUT to current pager.
  2935. B<||>I<dbcmd>        Same as B<|>I<dbcmd> but DB::OUT is temporarilly select()ed as well.
  2936. B<\=> [I<alias> I<value>]    Define a command alias, or list current aliases.
  2937. I<command>        Execute as a perl statement in current package.
  2938. B<v>        Show versions of loaded modules.
  2939. B<R>        Pure-man-restart of debugger, some of debugger state
  2940.         and command-line options may be lost.
  2941.         Currently the following settings are preserved:
  2942.         history, breakpoints and actions, debugger B<O>ptions 
  2943.         and the following command-line options: I<-w>, I<-I>, I<-e>.
  2944.  
  2945. B<O> [I<opt>] ...    Set boolean option to true
  2946. B<O> [I<opt>B<?>]    Query options
  2947. B<O> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ... 
  2948.         Set options.  Use quotes in spaces in value.
  2949.     I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
  2950.     I<pager>            program for output of \"|cmd\";
  2951.     I<tkRunning>            run Tk while prompting (with ReadLine);
  2952.     I<signalLevel> I<warnLevel> I<dieLevel>    level of verbosity;
  2953.     I<inhibit_exit>        Allows stepping off the end of the script.
  2954.     I<ImmediateStop>        Debugger should stop as early as possible.
  2955.     I<RemotePort>            Remote hostname:port for remote debugging
  2956.   The following options affect what happens with B<V>, B<X>, and B<x> commands:
  2957.     I<arrayDepth>, I<hashDepth>     print only first N elements ('' for all);
  2958.     I<compactDump>, I<veryCompact>     change style of array and hash dump;
  2959.     I<globPrint>             whether to print contents of globs;
  2960.     I<DumpDBFiles>         dump arrays holding debugged files;
  2961.     I<DumpPackages>         dump symbol tables of packages;
  2962.     I<DumpReused>             dump contents of \"reused\" addresses;
  2963.     I<quote>, I<HighBit>, I<undefPrint>     change style of string dump;
  2964.     I<bareStringify>         Do not print the overload-stringified value;
  2965.   Other options include:
  2966.     I<PrintRet>        affects printing of return value after B<r> command,
  2967.     I<frame>        affects printing messages on subroutine entry/exit.
  2968.     I<AutoTrace>    affects printing messages on possible breaking points.
  2969.     I<maxTraceLen>    gives max length of evals/args listed in stack trace.
  2970.     I<ornaments>     affects screen appearance of the command line.
  2971.     I<CreateTTY>     bits control attempts to create a new TTY on events:
  2972.             1: on fork()    2: debugger is started inside debugger
  2973.             4: on startup
  2974.     During startup options are initialized from \$ENV{PERLDB_OPTS}.
  2975.     You can put additional initialization options I<TTY>, I<noTTY>,
  2976.     I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
  2977.     `B<R>' after you set them).
  2978.  
  2979. B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction.
  2980. B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
  2981. B<h h>        Summary of debugger commands.
  2982. B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the 
  2983.         named Perl I<manpage>, or on B<$doccmd> itself if omitted.
  2984.         Set B<\$DB::doccmd> to change viewer.
  2985.  
  2986. Type `|h' for a paged display if this was too hard to read.
  2987.  
  2988. "; # Fix balance of vi % matching: }}}}
  2989.  
  2990.     #  note: tabs in the following section are not-so-helpful
  2991.     $pre580_summary = <<"END_SUM";
  2992. I<List/search source lines:>               I<Control script execution:>
  2993.   B<l> [I<ln>|I<sub>]  List source code            B<T>           Stack trace
  2994.   B<-> or B<.>      List previous/current line  B<s> [I<expr>]    Single step [in expr]
  2995.   B<w> [I<line>]    List around line            B<n> [I<expr>]    Next, steps over subs
  2996.   B<f> I<filename>  View source in file         <B<CR>/B<Enter>>  Repeat last B<n> or B<s>
  2997.   B</>I<pattern>B</> B<?>I<patt>B<?>   Search forw/backw    B<r>           Return from subroutine
  2998.   B<v>           Show versions of modules    B<c> [I<ln>|I<sub>]  Continue until position
  2999. I<Debugger controls:>                        B<L>           List break/watch/actions
  3000.   B<O> [...]     Set debugger options        B<t> [I<expr>]    Toggle trace [trace expr]
  3001.   B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
  3002.   B<$prc> [I<N>|I<pat>]   Redo a previous command     B<d> [I<ln>] or B<D> Delete a/all breakpoints
  3003.   B<H> [I<-num>]    Display last num commands   B<a> [I<ln>] I<cmd>  Do cmd before line
  3004.   B<=> [I<a> I<val>]   Define/list an alias        B<W> I<expr>      Add a watch expression
  3005.   B<h> [I<db_cmd>]  Get help on command         B<A> or B<W>      Delete all actions/watch
  3006.   B<|>[B<|>]I<db_cmd>  Send output to pager        B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
  3007.   B<q> or B<^D>     Quit                        B<R>           Attempt a restart
  3008. I<Data Examination:>     B<expr>     Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
  3009.   B<x>|B<m> I<expr>       Evals expr in list context, dumps the result or lists methods.
  3010.   B<p> I<expr>         Print expression (uses script's current package).
  3011.   B<S> [[B<!>]I<pat>]     List subroutine names [not] matching pattern
  3012.   B<V> [I<Pk> [I<Vars>]]  List Variables in Package.  Vars can be ~pattern or !pattern.
  3013.   B<X> [I<Vars>]       Same as \"B<V> I<current_package> [I<Vars>]\".
  3014.   B<y> [I<n> [I<Vars>]]   List lexicals in higher scope <n>.  Vars same as B<V>.
  3015. For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
  3016. END_SUM
  3017.                 # ')}}; # Fix balance of vi % matching
  3018.  
  3019. }
  3020.  
  3021. sub print_help {
  3022.     local $_ = shift;
  3023.  
  3024.     # Restore proper alignment destroyed by eeevil I<> and B<>
  3025.     # ornaments: A pox on both their houses!
  3026.     #
  3027.     # A help command will have everything up to and including
  3028.     # the first tab sequence padded into a field 16 (or if indented 20)
  3029.     # wide.  If it's wider than that, an extra space will be added.
  3030.     s{
  3031.     ^                 # only matters at start of line
  3032.       ( \040{4} | \t )*    # some subcommands are indented
  3033.       ( < ?         # so <CR> works
  3034.         [BI] < [^\t\n] + )  # find an eeevil ornament
  3035.       ( \t+ )        # original separation, discarded
  3036.       ( .* )        # this will now start (no earlier) than 
  3037.                 # column 16
  3038.     } {
  3039.     my($leadwhite, $command, $midwhite, $text) = ($1, $2, $3, $4);
  3040.     my $clean = $command;
  3041.     $clean =~ s/[BI]<([^>]*)>/$1/g;  
  3042.     # replace with this whole string:
  3043.     ($leadwhite ? " " x 4 : "")
  3044.       . $command
  3045.       . ((" " x (16 + ($leadwhite ? 4 : 0) - length($clean))) || " ")
  3046.       . $text;
  3047.  
  3048.     }mgex;
  3049.  
  3050.     s{                # handle bold ornaments
  3051.     B < ( [^>] + | > ) >
  3052.     } {
  3053.       $Term::ReadLine::TermCap::rl_term_set[2] 
  3054.     . $1
  3055.     . $Term::ReadLine::TermCap::rl_term_set[3]
  3056.     }gex;
  3057.  
  3058.     s{                # handle italic ornaments
  3059.     I < ( [^>] + | > ) >
  3060.     } {
  3061.       $Term::ReadLine::TermCap::rl_term_set[0] 
  3062.     . $1
  3063.     . $Term::ReadLine::TermCap::rl_term_set[1]
  3064.     }gex;
  3065.  
  3066.     local $\ = '';
  3067.     print $OUT $_;
  3068. }
  3069.  
  3070. sub fix_less {
  3071.     return if defined $ENV{LESS} && $ENV{LESS} =~ /r/;
  3072.     my $is_less = $pager =~ /\bless\b/;
  3073.     if ($pager =~ /\bmore\b/) { 
  3074.     my @st_more = stat('/usr/bin/more');
  3075.     my @st_less = stat('/usr/bin/less');
  3076.     $is_less = @st_more    && @st_less 
  3077.         && $st_more[0] == $st_less[0] 
  3078.         && $st_more[1] == $st_less[1];
  3079.     }
  3080.     # changes environment!
  3081.     $ENV{LESS} .= 'r'     if $is_less;
  3082. }
  3083.  
  3084. sub diesignal {
  3085.     local $frame = 0;
  3086.     local $doret = -2;
  3087.     $SIG{'ABRT'} = 'DEFAULT';
  3088.     kill 'ABRT', $$ if $panic++;
  3089.     if (defined &Carp::longmess) {
  3090.     local $SIG{__WARN__} = '';
  3091.     local $Carp::CarpLevel = 2;        # mydie + confess
  3092.     &warn(Carp::longmess("Signal @_"));
  3093.     }
  3094.     else {
  3095.     local $\ = '';
  3096.     print $DB::OUT "Got signal @_\n";
  3097.     }
  3098.     kill 'ABRT', $$;
  3099. }
  3100.  
  3101. sub dbwarn { 
  3102.   local $frame = 0;
  3103.   local $doret = -2;
  3104.   local $SIG{__WARN__} = '';
  3105.   local $SIG{__DIE__} = '';
  3106.   eval { require Carp } if defined $^S;    # If error/warning during compilation,
  3107.                                         # require may be broken.
  3108.   CORE::warn(@_, "\nCannot print stack trace, load with -MCarp option to see stack"),
  3109.     return unless defined &Carp::longmess;
  3110.   my ($mysingle,$mytrace) = ($single,$trace);
  3111.   $single = 0; $trace = 0;
  3112.   my $mess = Carp::longmess(@_);
  3113.   ($single,$trace) = ($mysingle,$mytrace);
  3114.   &warn($mess); 
  3115. }
  3116.  
  3117. sub dbdie {
  3118.   local $frame = 0;
  3119.   local $doret = -2;
  3120.   local $SIG{__DIE__} = '';
  3121.   local $SIG{__WARN__} = '';
  3122.   my $i = 0; my $ineval = 0; my $sub;
  3123.   if ($dieLevel > 2) {
  3124.       local $SIG{__WARN__} = \&dbwarn;
  3125.       &warn(@_);        # Yell no matter what
  3126.       return;
  3127.   }
  3128.   if ($dieLevel < 2) {
  3129.     die @_ if $^S;        # in eval propagate
  3130.   }
  3131.   # No need to check $^S, eval is much more robust nowadays
  3132.   eval { require Carp }; #if defined $^S;# If error/warning during compilation,
  3133.                                     # require may be broken.
  3134.  
  3135.   die(@_, "\nCannot print stack trace, load with -MCarp option to see stack")
  3136.     unless defined &Carp::longmess;
  3137.  
  3138.   # We do not want to debug this chunk (automatic disabling works
  3139.   # inside DB::DB, but not in Carp).
  3140.   my ($mysingle,$mytrace) = ($single,$trace);
  3141.   $single = 0; $trace = 0;
  3142.   my $mess = "@_";
  3143.   { 
  3144.     package Carp;        # Do not include us in the list
  3145.     eval {
  3146.       $mess = Carp::longmess(@_);
  3147.     };
  3148.   }
  3149.   ($single,$trace) = ($mysingle,$mytrace);
  3150.   die $mess;
  3151. }
  3152.  
  3153. sub warnLevel {
  3154.   if (@_) {
  3155.     $prevwarn = $SIG{__WARN__} unless $warnLevel;
  3156.     $warnLevel = shift;
  3157.     if ($warnLevel) {
  3158.       $SIG{__WARN__} = \&DB::dbwarn;
  3159.     } elsif ($prevwarn) {
  3160.       $SIG{__WARN__} = $prevwarn;
  3161.     }
  3162.   }
  3163.   $warnLevel;
  3164. }
  3165.  
  3166. sub dieLevel {
  3167.   local $\ = '';
  3168.   if (@_) {
  3169.     $prevdie = $SIG{__DIE__} unless $dieLevel;
  3170.     $dieLevel = shift;
  3171.     if ($dieLevel) {
  3172.       $SIG{__DIE__} = \&DB::dbdie; # if $dieLevel < 2;
  3173.       #$SIG{__DIE__} = \&DB::diehard if $dieLevel >= 2;
  3174.       print $OUT "Stack dump during die enabled", 
  3175.         ( $dieLevel == 1 ? " outside of evals" : ""), ".\n"
  3176.       if $I_m_init;
  3177.       print $OUT "Dump printed too.\n" if $dieLevel > 2;
  3178.     } elsif ($prevdie) {
  3179.       $SIG{__DIE__} = $prevdie;
  3180.       print $OUT "Default die handler restored.\n";
  3181.     }
  3182.   }
  3183.   $dieLevel;
  3184. }
  3185.  
  3186. sub signalLevel {
  3187.   if (@_) {
  3188.     $prevsegv = $SIG{SEGV} unless $signalLevel;
  3189.     $prevbus = $SIG{BUS} unless $signalLevel;
  3190.     $signalLevel = shift;
  3191.     if ($signalLevel) {
  3192.       $SIG{SEGV} = \&DB::diesignal;
  3193.       $SIG{BUS} = \&DB::diesignal;
  3194.     } else {
  3195.       $SIG{SEGV} = $prevsegv;
  3196.       $SIG{BUS} = $prevbus;
  3197.     }
  3198.   }
  3199.   $signalLevel;
  3200. }
  3201.  
  3202. sub CvGV_name {
  3203.   my $in = shift;
  3204.   my $name = CvGV_name_or_bust($in);
  3205.   defined $name ? $name : $in;
  3206. }
  3207.  
  3208. sub CvGV_name_or_bust {
  3209.   my $in = shift;
  3210.   return if $skipCvGV;        # Backdoor to avoid problems if XS broken...
  3211.   return unless ref $in;
  3212.   $in = \&$in;            # Hard reference...
  3213.   eval {require Devel::Peek; 1} or return;
  3214.   my $gv = Devel::Peek::CvGV($in) or return;
  3215.   *$gv{PACKAGE} . '::' . *$gv{NAME};
  3216. }
  3217.  
  3218. sub find_sub {
  3219.   my $subr = shift;
  3220.   $sub{$subr} or do {
  3221.     return unless defined &$subr;
  3222.     my $name = CvGV_name_or_bust($subr);
  3223.     my $data;
  3224.     $data = $sub{$name} if defined $name;
  3225.     return $data if defined $data;
  3226.  
  3227.     # Old stupid way...
  3228.     $subr = \&$subr;        # Hard reference
  3229.     my $s;
  3230.     for (keys %sub) {
  3231.       $s = $_, last if $subr eq \&$_;
  3232.     }
  3233.     $sub{$s} if $s;
  3234.   }
  3235. }
  3236.  
  3237. sub methods {
  3238.   my $class = shift;
  3239.   $class = ref $class if ref $class;
  3240.   local %seen;
  3241.   local %packs;
  3242.   methods_via($class, '', 1);
  3243.   methods_via('UNIVERSAL', 'UNIVERSAL', 0);
  3244. }
  3245.  
  3246. sub methods_via {
  3247.   my $class = shift;
  3248.   return if $packs{$class}++;
  3249.   my $prefix = shift;
  3250.   my $prepend = $prefix ? "via $prefix: " : '';
  3251.   my $name;
  3252.   for $name (grep {defined &{${"${class}::"}{$_}}} 
  3253.          sort keys %{"${class}::"}) {
  3254.     next if $seen{ $name }++;
  3255.     local $\ = '';
  3256.     local $, = '';
  3257.     print $DB::OUT "$prepend$name\n";
  3258.   }
  3259.   return unless shift;        # Recurse?
  3260.   for $name (@{"${class}::ISA"}) {
  3261.     $prepend = $prefix ? $prefix . " -> $name" : $name;
  3262.     methods_via($name, $prepend, 1);
  3263.   }
  3264. }
  3265.  
  3266. sub setman { 
  3267.     $doccmd = $^O !~ /^(?:MSWin32|VMS|os2|dos|amigaos|riscos|MacOS|NetWare)\z/s
  3268.         ? "man"             # O Happy Day!
  3269.         : "perldoc";        # Alas, poor unfortunates
  3270. }
  3271.  
  3272. sub runman {
  3273.     my $page = shift;
  3274.     unless ($page) {
  3275.     &system("$doccmd $doccmd");
  3276.     return;
  3277.     } 
  3278.     # this way user can override, like with $doccmd="man -Mwhatever"
  3279.     # or even just "man " to disable the path check.
  3280.     unless ($doccmd eq 'man') {
  3281.     &system("$doccmd $page");
  3282.     return;
  3283.     } 
  3284.  
  3285.     $page = 'perl' if lc($page) eq 'help';
  3286.  
  3287.     require Config;
  3288.     my $man1dir = $Config::Config{'man1dir'};
  3289.     my $man3dir = $Config::Config{'man3dir'};
  3290.     for ($man1dir, $man3dir) { s#/[^/]*\z## if /\S/ } 
  3291.     my $manpath = '';
  3292.     $manpath .= "$man1dir:" if $man1dir =~ /\S/;
  3293.     $manpath .= "$man3dir:" if $man3dir =~ /\S/ && $man1dir ne $man3dir;
  3294.     chop $manpath if $manpath;
  3295.     # harmless if missing, I figure
  3296.     my $oldpath = $ENV{MANPATH};
  3297.     $ENV{MANPATH} = $manpath if $manpath;
  3298.     my $nopathopt = $^O =~ /dunno what goes here/;
  3299.     if (CORE::system($doccmd, 
  3300.         # I just *know* there are men without -M
  3301.         (($manpath && !$nopathopt) ? ("-M", $manpath) : ()),  
  3302.         split ' ', $page) )
  3303.     {
  3304.     unless ($page =~ /^perl\w/) {
  3305.         if (grep { $page eq $_ } qw{ 
  3306.         5004delta 5005delta amiga api apio book boot bot call compile
  3307.         cygwin data dbmfilter debug debguts delta diag doc dos dsc embed
  3308.         faq faq1 faq2 faq3 faq4 faq5 faq6 faq7 faq8 faq9 filter fork
  3309.         form func guts hack hist hpux intern ipc lexwarn locale lol mod
  3310.         modinstall modlib number obj op opentut os2 os390 pod port 
  3311.         ref reftut run sec style sub syn thrtut tie toc todo toot tootc
  3312.         trap unicode var vms win32 xs xstut
  3313.           }) 
  3314.         {
  3315.         $page =~ s/^/perl/;
  3316.         CORE::system($doccmd, 
  3317.             (($manpath && !$nopathopt) ? ("-M", $manpath) : ()),  
  3318.             $page);
  3319.         }
  3320.     }
  3321.     } 
  3322.     if (defined $oldpath) {
  3323.     $ENV{MANPATH} = $manpath;
  3324.     } else {
  3325.     delete $ENV{MANPATH};
  3326.     } 
  3327.  
  3328. # The following BEGIN is very handy if debugger goes havoc, debugging debugger?
  3329.  
  3330. BEGIN {            # This does not compile, alas.
  3331.   $IN = \*STDIN;        # For bugs before DB::OUT has been opened
  3332.   $OUT = \*STDERR;        # For errors before DB::OUT has been opened
  3333.   $sh = '!';
  3334.   $rc = ',';
  3335.   @hist = ('?');
  3336.   $deep = 100;            # warning if stack gets this deep
  3337.   $window = 10;
  3338.   $preview = 3;
  3339.   $sub = '';
  3340.   $SIG{INT} = \&DB::catch;
  3341.   # This may be enabled to debug debugger:
  3342.   #$warnLevel = 1 unless defined $warnLevel;
  3343.   #$dieLevel = 1 unless defined $dieLevel;
  3344.   #$signalLevel = 1 unless defined $signalLevel;
  3345.  
  3346.   $db_stop = 0;            # Compiler warning
  3347.   $db_stop = 1 << 30;
  3348.   $level = 0;            # Level of recursive debugging
  3349.   # @stack and $doret are needed in sub sub, which is called for DB::postponed.
  3350.   # Triggers bug (?) in perl is we postpone this until runtime:
  3351.   @postponed = @stack = (0);
  3352.   $stack_depth = 0;        # Localized $#stack
  3353.   $doret = -2;
  3354.   $frame = 0;
  3355. }
  3356.  
  3357. BEGIN {$^W = $ini_warn;}    # Switch warnings back
  3358.  
  3359. #use Carp;            # This did break, left for debugging
  3360.  
  3361. sub db_complete {
  3362.   # Specific code for b c l V m f O, &blah, $blah, @blah, %blah
  3363.   my($text, $line, $start) = @_;
  3364.   my ($itext, $search, $prefix, $pack) =
  3365.     ($text, "^\Q${'package'}::\E([^:]+)\$");
  3366.   
  3367.   return sort grep /^\Q$text/, (keys %sub), qw(postpone load compile), # subroutines
  3368.                                (map { /$search/ ? ($1) : () } keys %sub)
  3369.     if (substr $line, 0, $start) =~ /^\|*[blc]\s+((postpone|compile)\s+)?$/;
  3370.   return sort grep /^\Q$text/, values %INC # files
  3371.     if (substr $line, 0, $start) =~ /^\|*b\s+load\s+$/;
  3372.   return sort map {($_, db_complete($_ . "::", "V ", 2))}
  3373.     grep /^\Q$text/, map { /^(.*)::$/ ? ($1) : ()} keys %:: # top-packages
  3374.       if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/ and $text =~ /^\w*$/;
  3375.   return sort map {($_, db_complete($_ . "::", "V ", 2))}
  3376.     grep !/^main::/,
  3377.       grep /^\Q$text/, map { /^(.*)::$/ ? ($prefix . "::$1") : ()} keys %{$prefix . '::'}
  3378.                  # packages
  3379.     if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/ 
  3380.       and $text =~ /^(.*[^:])::?(\w*)$/  and $prefix = $1;
  3381.   if ( $line =~ /^\|*f\s+(.*)/ ) { # Loaded files
  3382.     # We may want to complete to (eval 9), so $text may be wrong
  3383.     $prefix = length($1) - length($text);
  3384.     $text = $1;
  3385.     return sort 
  3386.     map {substr $_, 2 + $prefix} grep /^_<\Q$text/, (keys %main::), $0
  3387.   }
  3388.   if ((substr $text, 0, 1) eq '&') { # subroutines
  3389.     $text = substr $text, 1;
  3390.     $prefix = "&";
  3391.     return sort map "$prefix$_", 
  3392.                grep /^\Q$text/, 
  3393.                  (keys %sub),
  3394.                  (map { /$search/ ? ($1) : () } 
  3395.             keys %sub);
  3396.   }
  3397.   if ($text =~ /^[\$@%](.*)::(.*)/) { # symbols in a package
  3398.     $pack = ($1 eq 'main' ? '' : $1) . '::';
  3399.     $prefix = (substr $text, 0, 1) . $1 . '::';
  3400.     $text = $2;
  3401.     my @out 
  3402.       = map "$prefix$_", grep /^\Q$text/, grep /^_?[a-zA-Z]/, keys %$pack ;
  3403.     if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
  3404.       return db_complete($out[0], $line, $start);
  3405.     }
  3406.     return sort @out;
  3407.   }
  3408.   if ($text =~ /^[\$@%]/) { # symbols (in $package + packages in main)
  3409.     $pack = ($package eq 'main' ? '' : $package) . '::';
  3410.     $prefix = substr $text, 0, 1;
  3411.     $text = substr $text, 1;
  3412.     my @out = map "$prefix$_", grep /^\Q$text/, 
  3413.        (grep /^_?[a-zA-Z]/, keys %$pack), 
  3414.        ( $pack eq '::' ? () : (grep /::$/, keys %::) ) ;
  3415.     if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
  3416.       return db_complete($out[0], $line, $start);
  3417.     }
  3418.     return sort @out;
  3419.   }
  3420.   if ((substr $line, 0, $start) =~ /^\|*O\b.*\s$/) { # Options after a space
  3421.     my @out = grep /^\Q$text/, @options;
  3422.     my $val = option_val($out[0], undef);
  3423.     my $out = '? ';
  3424.     if (not defined $val or $val =~ /[\n\r]/) {
  3425.       # Can do nothing better
  3426.     } elsif ($val =~ /\s/) {
  3427.       my $found;
  3428.       foreach $l (split //, qq/\"\'\#\|/) {
  3429.     $out = "$l$val$l ", last if (index $val, $l) == -1;
  3430.       }
  3431.     } else {
  3432.       $out = "=$val ";
  3433.     }
  3434.     # Default to value if one completion, to question if many
  3435.     $rl_attribs->{completer_terminator_character} = (@out == 1 ? $out : '? ');
  3436.     return sort @out;
  3437.   }
  3438.   return $term->filename_list($text); # filenames
  3439. }
  3440.  
  3441. sub end_report {
  3442.   local $\ = '';
  3443.   print $OUT "Use `q' to quit or `R' to restart.  `h q' for details.\n"
  3444. }
  3445.  
  3446. sub clean_ENV {
  3447.     if (defined($ini_pids)) {
  3448.         $ENV{PERLDB_PIDS} = $ini_pids;
  3449.     } else {
  3450.         delete($ENV{PERLDB_PIDS});
  3451.     }
  3452. }
  3453.  
  3454. END {
  3455.   $finished = 1 if $inhibit_exit;      # So that some keys may be disabled.
  3456.   $fall_off_end = 1 unless $inhibit_exit;
  3457.   # Do not stop in at_exit() and destructors on exit:
  3458.   $DB::single = !$fall_off_end && !$runnonstop;
  3459.   DB::fake::at_exit() unless $fall_off_end or $runnonstop;
  3460. }
  3461.  
  3462.  
  3463. # ===================================== pre580 ================================
  3464. # this is very sad below here...
  3465. #
  3466.  
  3467. sub cmd_pre580_null {
  3468.     # do nothing...
  3469. }
  3470.  
  3471. sub cmd_pre580_a {
  3472.     my $cmd = shift;
  3473.     if ($cmd =~ /^(\d*)\s*(.*)/) {
  3474.         $i = $1 || $line; $j = $2;
  3475.         if (length $j) {
  3476.             if ($dbline[$i] == 0) {
  3477.                 print $OUT "Line $i may not have an action.\n";
  3478.             } else {
  3479.                 $had_breakpoints{$filename} |= 2;
  3480.                 $dbline{$i} =~ s/\0[^\0]*//;
  3481.                 $dbline{$i} .= "\0" . action($j);
  3482.             }
  3483.         } else {
  3484.             $dbline{$i} =~ s/\0[^\0]*//;
  3485.             delete $dbline{$i} if $dbline{$i} eq '';
  3486.         }
  3487.     }
  3488. }
  3489.  
  3490. sub cmd_pre580_b {
  3491.     my $cmd    = shift;
  3492.     my $dbline = shift;
  3493.     if ($cmd =~ /^load\b\s*(.*)/) {
  3494.         my $file = $1; $file =~ s/\s+$//;
  3495.         &cmd_b_load($file);
  3496.     } elsif ($cmd =~ /^(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/) {
  3497.         my $cond = length $3 ? $3 : '1';
  3498.         my ($subname, $break) = ($2, $1 eq 'postpone');
  3499.         $subname =~ s/\'/::/g;
  3500.         $subname = "${'package'}::" . $subname
  3501.         unless $subname =~ /::/;
  3502.         $subname = "main".$subname if substr($subname,0,2) eq "::";
  3503.         $postponed{$subname} = $break ? "break +0 if $cond" : "compile";
  3504.     } elsif ($cmd =~ /^([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/) { 
  3505.         my $subname = $1;
  3506.         my $cond = length $2 ? $2 : '1';
  3507.         &cmd_b_sub($subname, $cond);
  3508.     } elsif ($cmd =~ /^(\d*)\s*(.*)/) {
  3509.         my $i = $1 || $dbline;
  3510.         my $cond = length $2 ? $2 : '1';
  3511.         &cmd_b_line($i, $cond);
  3512.     }
  3513. }
  3514.  
  3515. sub cmd_pre580_D {
  3516.     my $cmd = shift;
  3517.     if ($cmd =~ /^\s*$/) {
  3518.         print $OUT "Deleting all breakpoints...\n";
  3519.         my $file;
  3520.         for $file (keys %had_breakpoints) {
  3521.             local *dbline = $main::{'_<' . $file};
  3522.             my $max = $#dbline;
  3523.             my $was;
  3524.  
  3525.             for ($i = 1; $i <= $max ; $i++) {
  3526.                 if (defined $dbline{$i}) {
  3527.                     $dbline{$i} =~ s/^[^\0]+//;
  3528.                     if ($dbline{$i} =~ s/^\0?$//) {
  3529.                         delete $dbline{$i};
  3530.                     }
  3531.                 }
  3532.             }
  3533.  
  3534.             if (not $had_breakpoints{$file} &= ~1) {
  3535.                 delete $had_breakpoints{$file};
  3536.             }
  3537.         }
  3538.         undef %postponed;
  3539.         undef %postponed_file;
  3540.         undef %break_on_load;
  3541.     }
  3542. }
  3543.  
  3544. sub cmd_pre580_h {
  3545.     my $cmd = shift;
  3546.     if ($cmd =~ /^\s*$/) {
  3547.         print_help($pre580_help);
  3548.     } elsif ($cmd =~ /^h\s*/) {
  3549.         print_help($pre580_summary);
  3550.     } elsif ($cmd =~ /^h\s+(\S.*)$/) { 
  3551.         my $asked = $1;            # for proper errmsg
  3552.         my $qasked = quotemeta($asked); # for searching
  3553.         # XXX: finds CR but not <CR>
  3554.         if ($pre580_help =~ /^<?(?:[IB]<)$qasked/m) {
  3555.             while ($pre580_help =~ /^(<?(?:[IB]<)$qasked([\s\S]*?)\n)(?!\s)/mg) {
  3556.                 print_help($1);
  3557.             }
  3558.         } else {
  3559.             print_help("B<$asked> is not a debugger command.\n");
  3560.         }
  3561.     }
  3562. }
  3563.  
  3564. sub cmd_pre580_W {
  3565.     my $cmd = shift;
  3566.     if ($cmd =~ /^$/) { 
  3567.         $trace &= ~2;
  3568.         @to_watch = @old_watch = ();
  3569.     } elsif ($cmd =~ /^(.*)/s) {
  3570.         push @to_watch, $1;
  3571.         $evalarg = $1;
  3572.         my ($val) = &eval;
  3573.         $val = (defined $val) ? "'$val'" : 'undef' ;
  3574.         push @old_watch, $val;
  3575.         $trace |= 2;
  3576.     }
  3577. }
  3578.  
  3579. package DB::fake;
  3580.  
  3581. sub at_exit {
  3582.   "Debugged program terminated.  Use `q' to quit or `R' to restart.";
  3583. }
  3584.  
  3585. package DB;            # Do not trace this 1; below!
  3586.  
  3587. 1;
  3588.  
  3589.