3 # Debugger for Perl 5.00x; perl5db.pl patch level:
5 $header = "perl5db.pl version $VERSION";
7 # It is crucial that there is no lexicals in scope of `eval ""' down below
9 # 'my' would make it visible from user code
10 # but so does local! --tchrist [... into @DB::res, not @res. IZ]
13 local $otrace = $trace;
14 local $osingle = $single;
16 { ($evalarg) = $evalarg =~ /(.*)/s; }
17 @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug
23 local $saved[0]; # Preserve the old value of $@
27 } elsif ($onetimeDump) {
28 if ($onetimeDump eq 'dump') {
29 local $option{dumpDepth} = $onetimedumpDepth
30 if defined $onetimedumpDepth;
32 } elsif ($onetimeDump eq 'methods') {
39 # After this point it is safe to introduce lexicals
40 # However, one should not overdo it: leave as much control from outside as possible
42 # This file is automatically included if you do perl -d.
43 # It's probably not useful to include this yourself.
45 # Before venturing further into these twisty passages, it is
46 # wise to read the perldebguts man page or risk the ire of dragons.
48 # Perl supplies the values for %sub. It effectively inserts
49 # a &DB::DB(); in front of every place that can have a
50 # breakpoint. Instead of a subroutine call it calls &DB::sub with
51 # $DB::sub being the called subroutine. It also inserts a BEGIN
52 # {require 'perl5db.pl'} before the first line.
54 # After each `require'd file is compiled, but before it is executed, a
55 # call to DB::postponed($main::{'_<'.$filename}) is emulated. Here the
56 # $filename is the expanded name of the `require'd file (as found as
59 # Additional services from Perl interpreter:
61 # if caller() is called from the package DB, it provides some
64 # The array @{$main::{'_<'.$filename}} (herein called @dbline) is the
65 # line-by-line contents of $filename.
67 # The hash %{'_<'.$filename} (herein called %dbline) contains
68 # breakpoints and action (it is keyed by line number), and individual
69 # entries are settable (as opposed to the whole hash). Only true/false
70 # is important to the interpreter, though the values used by
71 # perl5db.pl have the form "$break_condition\0$action". Values are
72 # magical in numeric context.
74 # The scalar ${'_<'.$filename} contains $filename.
76 # Note that no subroutine call is possible until &DB::sub is defined
77 # (for subroutines defined outside of the package DB). In fact the same is
78 # true if $deep is not defined.
83 # At start reads $rcfile that may set important options. This file
84 # may define a subroutine &afterinit that will be executed after the
85 # debugger is initialized.
87 # After $rcfile is read reads environment variable PERLDB_OPTS and parses
88 # it as a rest of `O ...' line in debugger prompt.
90 # The options that can be specified only at startup:
91 # [To set in $rcfile, call &parse_options("optionName=new_value").]
93 # TTY - the TTY to use for debugging i/o.
95 # noTTY - if set, goes in NonStop mode. On interrupt if TTY is not set
96 # uses the value of noTTY or "/tmp/perldbtty$$" to find TTY using
97 # Term::Rendezvous. Current variant is to have the name of TTY in this
100 # ReadLine - If false, dummy ReadLine is used, so you can debug
101 # ReadLine applications.
103 # NonStop - if true, no i/o is performed until interrupt.
105 # LineInfo - file or pipe to print line number info to. If it is a
106 # pipe, a short "emacs like" message is used.
108 # RemotePort - host:port to connect to on remote host for remote debugging.
110 # Example $rcfile: (delete leading hashes!)
112 # &parse_options("NonStop=1 LineInfo=db.out");
113 # sub afterinit { $trace = 1; }
115 # The script will run without human intervention, putting trace
116 # information into db.out. (If you interrupt it, you would better
117 # reset LineInfo to something "interactive"!)
119 ##################################################################
121 # Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich)
123 # modified Perl debugger, to be run from Emacs in perldb-mode
124 # Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990
125 # Johan Vromans -- upgrade to 4.0 pl 10
126 # Ilya Zakharevich -- patches after 5.001 (and some before ;-)
130 # A lot of things changed after 0.94. First of all, core now informs
131 # debugger about entry into XSUBs, overloaded operators, tied operations,
132 # BEGIN and END. Handy with `O f=2'.
134 # This can make debugger a little bit too verbose, please be patient
135 # and report your problems promptly.
137 # Now the option frame has 3 values: 0,1,2.
139 # Note that if DESTROY returns a reference to the object (or object),
140 # the deletion of data may be postponed until the next function call,
141 # due to the need to examine the return value.
143 # Changes: 0.95: `v' command shows versions.
144 # Changes: 0.96: `v' command shows version of readline.
145 # primitive completion works (dynamic variables, subs for `b' and `l',
146 # options). Can `p %var'
147 # Better help (`h <' now works). New commands <<, >>, {, {{.
148 # {dump|print}_trace() coded (to be able to do it from <<cmd).
149 # `c sub' documented.
150 # At last enough magic combined to stop after the end of debuggee.
151 # !! should work now (thanks to Emacs bracket matching an extra
152 # `]' in a regexp is caught).
153 # `L', `D' and `A' span files now (as documented).
154 # Breakpoints in `require'd code are possible (used in `R').
155 # Some additional words on internal work of debugger.
156 # `b load filename' implemented.
157 # `b postpone subr' implemented.
158 # now only `q' exits debugger (overwritable on $inhibit_exit).
159 # When restarting debugger breakpoints/actions persist.
160 # Buglet: When restarting debugger only one breakpoint/action per
161 # autoloaded function persists.
162 # Changes: 0.97: NonStop will not stop in at_exit().
163 # Option AutoTrace implemented.
164 # Trace printed differently if frames are printed too.
165 # new `inhibitExit' option.
166 # printing of a very long statement interruptible.
167 # Changes: 0.98: New command `m' for printing possible methods
168 # 'l -' is a synonym for `-'.
169 # Cosmetic bugs in printing stack trace.
170 # `frame' & 8 to print "expanded args" in stack trace.
171 # Can list/break in imported subs.
172 # new `maxTraceLen' option.
173 # frame & 4 and frame & 8 granted.
175 # nonstoppable lines do not have `:' near the line number.
176 # `b compile subname' implemented.
177 # Will not use $` any more.
178 # `-' behaves sane now.
179 # Changes: 0.99: Completion for `f', `m'.
180 # `m' will remove duplicate names instead of duplicate functions.
181 # `b load' strips trailing whitespace.
182 # completion ignores leading `|'; takes into account current package
183 # when completing a subroutine name (same for `l').
184 # Changes: 1.07: Many fixed by tchrist 13-March-2000
186 # + Added bare minimal security checks on perldb rc files, plus
187 # comments on what else is needed.
188 # + Fixed the ornaments that made "|h" completely unusable.
189 # They are not used in print_help if they will hurt. Strip pod
190 # if we're paging to less.
191 # + Fixed mis-formatting of help messages caused by ornaments
192 # to restore Larry's original formatting.
193 # + Fixed many other formatting errors. The code is still suboptimal,
194 # and needs a lot of work at restructuring. It's also misindented
196 # + Fixed bug where trying to look at an option like your pager
198 # + Fixed some $? processing. Note: if you use csh or tcsh, you will
199 # lose. You should consider shell escapes not using their shell,
200 # or else not caring about detailed status. This should really be
201 # unified into one place, too.
202 # + Fixed bug where invisible trailing whitespace on commands hoses you,
203 # tricking Perl into thinking you weren't calling a debugger command!
204 # + Fixed bug where leading whitespace on commands hoses you. (One
205 # suggests a leading semicolon or any other irrelevant non-whitespace
206 # to indicate literal Perl code.)
207 # + Fixed bugs that ate warnings due to wrong selected handle.
208 # + Fixed a precedence bug on signal stuff.
209 # + Fixed some unseemly wording.
210 # + Fixed bug in help command trying to call perl method code.
211 # + Fixed to call dumpvar from exception handler. SIGPIPE killed us.
213 # + Added some comments. This code is still nasty spaghetti.
214 # + Added message if you clear your pre/post command stacks which was
215 # very easy to do if you just typed a bare >, <, or {. (A command
216 # without an argument should *never* be a destructive action; this
217 # API is fundamentally screwed up; likewise option setting, which
218 # is equally buggered.)
219 # + Added command stack dump on argument of "?" for >, <, or {.
220 # + Added a semi-built-in doc viewer command that calls man with the
221 # proper %Config::Config path (and thus gets caching, man -k, etc),
222 # or else perldoc on obstreperous platforms.
223 # + Added to and rearranged the help information.
224 # + Detected apparent misuse of { ... } to declare a block; this used
225 # to work but now is a command, and mysteriously gave no complaint.
227 # Changes: 1.08: Apr 25, 2001 Jon Eveland <jweveland@yahoo.com>
229 # + This patch to perl5db.pl cleans up formatting issues on the help
230 # summary (h h) screen in the debugger. Mostly columnar alignment
231 # issues, plus converted the printed text to use all spaces, since
232 # tabs don't seem to help much here.
234 # Changes: 1.09: May 19, 2001 Ilya Zakharevich <ilya@math.ohio-state.edu>
235 # 0) Minor bugs corrected;
236 # a) Support for auto-creation of new TTY window on startup, either
237 # unconditionally, or if started as a kid of another debugger session;
238 # b) New `O'ption CreateTTY
239 # I<CreateTTY> bits control attempts to create a new TTY on events:
240 # 1: on fork() 2: debugger is started inside debugger
242 # c) Code to auto-create a new TTY window on OS/2 (currently one
243 # extra window per session - need named pipes to have more...);
244 # d) Simplified interface for custom createTTY functions (with a backward
245 # compatibility hack); now returns the TTY name to use; return of ''
246 # means that the function reset the I/O handles itself;
247 # d') Better message on the semantic of custom createTTY function;
248 # e) Convert the existing code to create a TTY into a custom createTTY
250 # f) Consistent support for TTY names of the form "TTYin,TTYout";
251 # g) Switch line-tracing output too to the created TTY window;
252 # h) make `b fork' DWIM with CORE::GLOBAL::fork;
253 # i) High-level debugger API cmd_*():
254 # cmd_b_load($filenamepart) # b load filenamepart
255 # cmd_b_line($lineno [, $cond]) # b lineno [cond]
256 # cmd_b_sub($sub [, $cond]) # b sub [cond]
257 # cmd_stop() # Control-C
258 # cmd_d($lineno) # d lineno (B)
259 # The cmd_*() API returns FALSE on failure; in this case it outputs
260 # the error message to the debugging output.
261 # j) Low-level debugger API
262 # break_on_load($filename) # b load filename
263 # @files = report_break_on_load() # List files with load-breakpoints
264 # breakable_line_in_filename($name, $from [, $to])
265 # # First breakable line in the
266 # # range $from .. $to. $to defaults
267 # # to $from, and may be less than $to
268 # breakable_line($from [, $to]) # Same for the current file
269 # break_on_filename_line($name, $lineno [, $cond])
270 # # Set breakpoint,$cond defaults to 1
271 # break_on_filename_line_range($name, $from, $to [, $cond])
272 # # As above, on the first
273 # # breakable line in range
274 # break_on_line($lineno [, $cond]) # As above, in the current file
275 # break_subroutine($sub [, $cond]) # break on the first breakable line
276 # ($name, $from, $to) = subroutine_filename_lines($sub)
277 # # The range of lines of the text
278 # The low-level API returns TRUE on success, and die()s on failure.
280 # Changes: 1.10: May 23, 2001 Daniel Lewart <d-lewart@uiuc.edu>
282 # + Fixed warnings generated by "perl -dWe 42"
283 # + Corrected spelling errors
284 # + Squeezed Help (h) output into 80 columns
286 # Changes: 1.11: May 24, 2001 David Dyck <dcd@tc.fluke.com>
287 # + Made "x @INC" work like it used to
289 # Changes: 1.12: May 24, 2001 Daniel Lewart <d-lewart@uiuc.edu>
290 # + Fixed warnings generated by "O" (Show debugger options)
291 # + Fixed warnings generated by "p 42" (Print expression)
292 # Changes: 1.13: Jun 19, 2001 Scott.L.Miller@compaq.com
293 # + Added windowSize option
294 # Changes: 1.14: Oct 9, 2001 multiple
295 # + Clean up after itself on VMS (Charles Lane in 12385)
296 # + Adding "@ file" syntax (Peter Scott in 12014)
297 # + Debug reloading selfloaded stuff (Ilya Zakharevich in 11457)
298 # + $^S and other debugger fixes (Ilya Zakharevich in 11120)
299 # + Forgot a my() declaration (Ilya Zakharevich in 11085)
300 # Changes: 1.15: Nov 6, 2001 Michael G Schwern <schwern@pobox.com>
301 # + Updated 1.14 change log
302 # + Added *dbline explainatory comments
303 # + Mentioning perldebguts man page
304 # Changes: 1.16: Feb 15, 2002 Mark-Jason Dominus <mjd@plover.com>
305 # + $onetimeDump improvements
306 # Changes: 1.17: Feb 20, 2002 Richard Foley <richard.foley@rfi.net>
307 # Moved some code to cmd_[.]()'s for clarity and ease of handling,
308 # rationalised the following commands and added cmd_wrapper() to
309 # enable switching between old and frighteningly consistent new
310 # behaviours for diehards: 'o CommandSet=pre580' (sigh...)
311 # a(add), A(del) # action expr (added del by line)
312 # + b(add), B(del) # break [line] (was b,D)
313 # + w(add), W(del) # watch expr (was W,W) added del by expr
314 # + h(summary), h h(long) # help (hh) (was h h,h)
315 # + m(methods), M(modules) # ... (was m,v)
316 # + o(option) # lc (was O)
317 # + v(view code), V(view Variables) # ... (was w,V)
319 ####################################################################
321 # Needed for the statement after exec():
323 BEGIN { $ini_warn = $^W; $^W = 0 } # Switch compilation warnings off until another BEGIN.
324 local($^W) = 0; # Switch run-time warnings off during init.
327 $dumpvar::arrayDepth,
328 $dumpvar::dumpDBFiles,
329 $dumpvar::dumpPackages,
330 $dumpvar::quoteHighBit,
331 $dumpvar::printUndef,
340 # Command-line + PERLLIB:
343 # $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?!
345 $trace = $signal = $single = 0; # Uninitialized warning suppression
346 # (local $^W cannot help - other packages!).
347 $inhibit_exit = $option{PrintRet} = 1;
349 @options = qw(hashDepth arrayDepth CommandSet dumpDepth
350 DumpDBFiles DumpPackages DumpReused
351 compactDump veryCompact quote HighBit undefPrint
352 globPrint PrintRet UsageOnly frame AutoTrace
353 TTY noTTY ReadLine NonStop LineInfo maxTraceLen
354 recallCommand ShellBang pager tkRunning ornaments
355 signalLevel warnLevel dieLevel inhibit_exit
356 ImmediateStop bareStringify CreateTTY
357 RemotePort windowSize);
360 hashDepth => \$dumpvar::hashDepth,
361 arrayDepth => \$dumpvar::arrayDepth,
362 CommandSet => \$CommandSet,
363 DumpDBFiles => \$dumpvar::dumpDBFiles,
364 DumpPackages => \$dumpvar::dumpPackages,
365 DumpReused => \$dumpvar::dumpReused,
366 HighBit => \$dumpvar::quoteHighBit,
367 undefPrint => \$dumpvar::printUndef,
368 globPrint => \$dumpvar::globPrint,
369 UsageOnly => \$dumpvar::usageOnly,
370 CreateTTY => \$CreateTTY,
371 bareStringify => \$dumpvar::bareStringify,
373 AutoTrace => \$trace,
374 inhibit_exit => \$inhibit_exit,
375 maxTraceLen => \$maxtrace,
376 ImmediateStop => \$ImmediateStop,
377 RemotePort => \$remoteport,
378 windowSize => \$window,
382 compactDump => \&dumpvar::compactDump,
383 veryCompact => \&dumpvar::veryCompact,
384 quote => \&dumpvar::quote,
387 ReadLine => \&ReadLine,
388 NonStop => \&NonStop,
389 LineInfo => \&LineInfo,
390 recallCommand => \&recallCommand,
391 ShellBang => \&shellBang,
393 signalLevel => \&signalLevel,
394 warnLevel => \&warnLevel,
395 dieLevel => \&dieLevel,
396 tkRunning => \&tkRunning,
397 ornaments => \&ornaments,
398 RemotePort => \&RemotePort,
402 compactDump => 'dumpvar.pl',
403 veryCompact => 'dumpvar.pl',
404 quote => 'dumpvar.pl',
407 # These guys may be defined in $ENV{PERL5DB} :
408 $rl = 1 unless defined $rl;
409 $warnLevel = 1 unless defined $warnLevel;
410 $dieLevel = 1 unless defined $dieLevel;
411 $signalLevel = 1 unless defined $signalLevel;
412 $pre = [] unless defined $pre;
413 $post = [] unless defined $post;
414 $pretype = [] unless defined $pretype;
415 $CreateTTY = 3 unless defined $CreateTTY;
416 $CommandSet = '580' unless defined $CommandSet;
418 warnLevel($warnLevel);
420 signalLevel($signalLevel);
423 defined $ENV{PAGER} ? $ENV{PAGER} :
424 eval { require Config } &&
425 defined $Config::Config{pager} ? $Config::Config{pager}
427 ) unless defined $pager;
429 &recallCommand("!") unless defined $prc;
430 &shellBang("!") unless defined $psh;
432 $maxtrace = 400 unless defined $maxtrace;
433 $ini_pids = $ENV{PERLDB_PIDS};
434 if (defined $ENV{PERLDB_PIDS}) {
435 $pids = "[$ENV{PERLDB_PIDS}]";
436 $ENV{PERLDB_PIDS} .= "->$$";
439 $ENV{PERLDB_PIDS} = "$$";
444 *emacs = $slave_editor if $slave_editor; # May be used in afterinit()...
446 if (-e "/dev/tty") { # this is the wrong metric!
449 $rcfile="perldb.ini";
452 # This isn't really safe, because there's a race
453 # between checking and opening. The solution is to
454 # open and fstat the handle, but then you have to read and
455 # eval the contents. But then the silly thing gets
456 # your lexical scope, which is unfortunately at best.
460 # Just exactly what part of the word "CORE::" don't you understand?
461 local $SIG{__WARN__};
464 unless (is_safe_file($file)) {
465 CORE::warn <<EO_GRIPE;
466 perldb: Must not source insecure rcfile $file.
467 You or the superuser must be the owner, and it must not
468 be writable by anyone but its owner.
474 CORE::warn("perldb: couldn't parse $file: $@") if $@;
478 # Verifies that owner is either real user or superuser and that no
479 # one but owner may write to it. This function is of limited use
480 # when called on a path instead of upon a handle, because there are
481 # no guarantees that filename (by dirent) whose file (by ino) is
482 # eventually accessed is the same as the one tested.
483 # Assumes that the file's existence is not in doubt.
486 stat($path) || return; # mysteriously vaporized
487 my($dev,$ino,$mode,$nlink,$uid,$gid) = stat(_);
489 return 0 if $uid != 0 && $uid != $<;
490 return 0 if $mode & 022;
495 safe_do("./$rcfile");
497 elsif (defined $ENV{HOME} && -f "$ENV{HOME}/$rcfile") {
498 safe_do("$ENV{HOME}/$rcfile");
500 elsif (defined $ENV{LOGDIR} && -f "$ENV{LOGDIR}/$rcfile") {
501 safe_do("$ENV{LOGDIR}/$rcfile");
504 if (defined $ENV{PERLDB_OPTS}) {
505 parse_options($ENV{PERLDB_OPTS});
508 if ( not defined &get_fork_TTY and defined $ENV{TERM} and $ENV{TERM} eq 'xterm'
509 and defined $ENV{WINDOWID} and defined $ENV{DISPLAY} ) { # _inside_ XTERM?
510 *get_fork_TTY = \&xterm_get_fork_TTY;
511 } elsif ($^O eq 'os2') {
512 *get_fork_TTY = \&os2_get_fork_TTY;
515 # Here begin the unreadable code. It needs fixing.
517 if (exists $ENV{PERLDB_RESTART}) {
518 delete $ENV{PERLDB_RESTART};
520 @hist = get_list('PERLDB_HIST');
521 %break_on_load = get_list("PERLDB_ON_LOAD");
522 %postponed = get_list("PERLDB_POSTPONE");
523 my @had_breakpoints= get_list("PERLDB_VISITED");
524 for (0 .. $#had_breakpoints) {
525 my %pf = get_list("PERLDB_FILE_$_");
526 $postponed_file{$had_breakpoints[$_]} = \%pf if %pf;
528 my %opt = get_list("PERLDB_OPT");
530 while (($opt,$val) = each %opt) {
531 $val =~ s/[\\\']/\\$1/g;
532 parse_options("$opt'$val'");
534 @INC = get_list("PERLDB_INC");
536 $pretype = [get_list("PERLDB_PRETYPE")];
537 $pre = [get_list("PERLDB_PRE")];
538 $post = [get_list("PERLDB_POST")];
539 @typeahead = get_list("PERLDB_TYPEAHEAD", @typeahead);
545 # Is Perl being run from a slave editor or graphical debugger?
546 $slave_editor = ((defined $main::ARGV[0]) and ($main::ARGV[0] eq '-emacs'));
547 $rl = 0, shift(@main::ARGV) if $slave_editor;
549 #require Term::ReadLine;
551 if ($^O eq 'cygwin') {
552 # /dev/tty is binary. use stdin for textmode
554 } elsif (-e "/dev/tty") {
555 $console = "/dev/tty";
556 } elsif ($^O eq 'dos' or -e "con" or $^O eq 'MSWin32') {
558 } elsif ($^O eq 'MacOS') {
559 if ($MacPerl::Version !~ /MPW/) {
560 $console = "Dev:Console:Perl Debug"; # Separate window for application
562 $console = "Dev:Console";
565 $console = "sys\$command";
568 if (($^O eq 'MSWin32') and ($slave_editor or defined $ENV{EMACS})) {
572 if ($^O eq 'NetWare') {
577 if (defined $ENV{OS2_SHELL} and ($slave_editor or $ENV{WINDOWID})) { # In OS/2
585 $console = $tty if defined $tty;
587 if (defined $remoteport) {
589 $OUT = new IO::Socket::INET( Timeout => '10',
590 PeerAddr => $remoteport,
593 if (!$OUT) { die "Unable to connect to remote host: $remoteport\n"; }
596 create_IN_OUT(4) if $CreateTTY & 4;
598 my ($i, $o) = split /,/, $console;
599 $o = $i unless defined $o;
600 open(IN,"+<$i") || open(IN,"<$i") || open(IN,"<&STDIN");
601 open(OUT,"+>$o") || open(OUT,">$o") || open(OUT,">&STDERR")
602 || open(OUT,">&STDOUT"); # so we don't dongle stdout
603 } elsif (not defined $console) {
605 open(OUT,">&STDERR") || open(OUT,">&STDOUT"); # so we don't dongle stdout
606 $console = 'STDIN/OUT';
608 # so open("|more") can read from STDOUT and so we don't dingle stdin
609 $IN = \*IN, $OUT = \*OUT if $console or not defined $console;
611 my $previous = select($OUT);
612 $| = 1; # for DB::OUT
615 $LINEINFO = $OUT unless defined $LINEINFO;
616 $lineinfo = $console unless defined $lineinfo;
618 $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/;
619 unless ($runnonstop) {
620 if ($term_pid eq '-1') {
621 print $OUT "\nDaughter DB session started...\n";
623 print $OUT "\nLoading DB routines from $header\n";
624 print $OUT ("Editor support ",
625 $slave_editor ? "enabled" : "available",
627 print $OUT "\nEnter h or `h h' for help, or `$doccmd perldebug' for more help.\n\n";
635 s/(.*)/'$1'/ unless /^-?[\d.]+$/;
638 if (defined &afterinit) { # May be defined in $rcfile
644 ############################################################ Subroutines
647 # _After_ the perl program is compiled, $single is set to 1:
648 if ($single and not $second_time++) {
649 if ($runnonstop) { # Disable until signal
650 for ($i=0; $i <= $stack_depth; ) {
654 # return; # Would not print trace!
655 } elsif ($ImmediateStop) {
660 $runnonstop = 0 if $single or $signal; # Disable it if interactive.
662 ($package, $filename, $line) = caller;
663 $filename_ini = $filename;
664 $usercontext = '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' .
665 "package $package;"; # this won't let them modify, alas
666 local(*dbline) = $main::{'_<' . $filename};
668 if ($dbline{$line} && (($stop,$action) = split(/\0/,$dbline{$line}))) {
672 $evalarg = "\$DB::signal |= 1 if do {$stop}"; &eval;
673 $dbline{$line} =~ s/;9($|\0)/$1/;
676 my $was_signal = $signal;
678 for (my $n = 0; $n <= $#to_watch; $n++) {
679 $evalarg = $to_watch[$n];
680 local $onetimeDump; # Do not output results
681 my ($val) = &eval; # Fix context (&eval is doing array)?
682 $val = ( (defined $val) ? "'$val'" : 'undef' );
683 if ($val ne $old_watch[$n]) {
686 Watchpoint $n:\t$to_watch[$n] changed:
687 old value:\t$old_watch[$n]
690 $old_watch[$n] = $val;
694 if ($trace & 4) { # User-installed watch
695 return if watchfunction($package, $filename, $line)
696 and not $single and not $was_signal and not ($trace & ~4);
698 $was_signal = $signal;
700 if ($single || ($trace & 1) || $was_signal) {
702 $position = "\032\032$filename:$line:0\n";
703 print_lineinfo($position);
704 } elsif ($package eq 'DB::fake') {
707 Debugged program terminated. Use B<q> to quit or B<R> to restart,
708 use B<O> I<inhibit_exit> to avoid stopping after program termination,
709 B<h q>, B<h R> or B<h O> to get additional info.
712 $usercontext = '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' .
713 "package $package;"; # this won't let them modify, alas
716 $prefix = $sub =~ /::/ ? "" : "${'package'}::";
717 $prefix .= "$sub($filename:";
718 $after = ($dbline[$line] =~ /\n$/ ? '' : "\n");
719 if (length($prefix) > 30) {
720 $position = "$prefix$line):\n$line:\t$dbline[$line]$after";
725 $position = "$prefix$line$infix$dbline[$line]$after";
728 print_lineinfo(' ' x $stack_depth, "$line:\t$dbline[$line]$after");
730 print_lineinfo($position);
732 for ($i = $line + 1; $i <= $max && $dbline[$i] == 0; ++$i) { #{ vi
733 last if $dbline[$i] =~ /^\s*[\;\}\#\n]/;
735 $after = ($dbline[$i] =~ /\n$/ ? '' : "\n");
736 $incr_pos = "$prefix$i$infix$dbline[$i]$after";
737 $position .= $incr_pos;
739 print_lineinfo(' ' x $stack_depth, "$i:\t$dbline[$i]$after");
741 print_lineinfo($incr_pos);
746 $evalarg = $action, &eval if $action;
747 if ($single || $was_signal) {
748 local $level = $level + 1;
749 foreach $evalarg (@$pre) {
752 print $OUT $stack_depth . " levels deep in subroutine calls!\n"
755 $incr = -1; # for backward motion.
756 @typeahead = (@$pretype, @typeahead);
758 while (($term || &setterm),
759 ($term_pid == $$ or resetterm(1)),
760 defined ($cmd=&readline("$pidprompt DB" . ('<' x $level) .
761 ($#hist+1) . ('>' x $level) . " ")))
765 $cmd =~ s/\\$/\n/ && do {
766 $cmd .= &readline(" cont: ");
769 $cmd =~ /^$/ && ($cmd = $laststep);
770 push(@hist,$cmd) if length($cmd) > 1;
772 $cmd =~ s/^\s+//s; # trim annoying leading whitespace
773 $cmd =~ s/\s+$//s; # trim annoying trailing whitespace
774 ($i) = split(/\s+/,$cmd);
776 # squelch the sigmangler
778 local $SIG{__WARN__};
779 eval "\$cmd =~ $alias{$i}";
781 print $OUT "Couldn't evaluate `$i' alias: $@";
785 $cmd =~ /^q$/ && ($fall_off_end = 1) && clean_ENV() && exit $?;
786 $cmd =~ /^t$/ && do {
788 print $OUT "Trace = " .
789 (($trace & 1) ? "on" : "off" ) . "\n";
791 $cmd =~ /^S(\s+(!)?(.+))?$/ && do {
792 $Srev = defined $2; $Spatt = $3; $Snocheck = ! defined $1;
793 foreach $subname (sort(keys %sub)) {
794 if ($Snocheck or $Srev^($subname =~ /$Spatt/)) {
795 print $OUT $subname,"\n";
799 $cmd =~ s/^X\b/V $package/;
800 $cmd =~ /^V$/ && do {
801 $cmd = "V $package"; };
802 $cmd =~ /^V\b\s*(\S+)\s*(.*)/ && do {
803 local ($savout) = select($OUT);
805 @vars = split(' ',$2);
806 do 'dumpvar.pl' unless defined &main::dumpvar;
807 if (defined &main::dumpvar) {
810 # must detect sigpipe failures
811 eval { &main::dumpvar($packname,@vars) };
813 die unless $@ =~ /dumpvar print failed/;
816 print $OUT "dumpvar.pl not available.\n";
820 $cmd =~ s/^x\b/ / && do { # So that will be evaled
821 $onetimeDump = 'dump';
822 # handle special "x 3 blah" syntax
823 if ($cmd =~ s/^\s*(\d+)(?=\s)/ /) {
824 $onetimedumpDepth = $1;
827 $cmd =~ s/^m\s+([\w:]+)\s*$/ / && do {
828 methods($1); next CMD};
829 $cmd =~ s/^m\b/ / && do { # So this will be evaled
830 $onetimeDump = 'methods'; };
831 $cmd =~ /^f\b\s*(.*)/ && do {
835 print $OUT "The old f command is now the r command.\n"; # hint
836 print $OUT "The new f command switches filenames.\n";
839 if (!defined $main::{'_<' . $file}) {
840 if (($try) = grep(m#^_<.*$file#, keys %main::)) {{
841 $try = substr($try,2);
842 print $OUT "Choosing $try matching `$file':\n";
846 if (!defined $main::{'_<' . $file}) {
847 print $OUT "No file matching `$file' is loaded.\n";
849 } elsif ($file ne $filename) {
850 *dbline = $main::{'_<' . $file};
856 print $OUT "Already in $file.\n";
860 $cmd =~ /^\.$/ && do {
861 $incr = -1; # for backward motion.
863 $filename = $filename_ini;
864 *dbline = $main::{'_<' . $filename};
866 print_lineinfo($position);
868 $cmd =~ /^-$/ && do {
869 $start -= $incr + $window + 1;
870 $start = 1 if $start <= 0;
872 $cmd = 'l ' . ($start) . '+'; };
874 $cmd =~ /^([aAbBDhlLMoOvwW])\b\s*(.*)/s && do {
875 &cmd_wrapper($1, $2, $line);
879 $cmd =~ /^\<\<\s*(.*)/ && do { # \<\< for CPerl sake: not HERE
880 push @$pre, action($1);
882 $cmd =~ /^>>\s*(.*)/ && do {
883 push @$post, action($1);
885 $cmd =~ /^<\s*(.*)/ && do {
887 print $OUT "All < actions cleared.\n";
893 print $OUT "No pre-prompt Perl actions.\n";
896 print $OUT "Perl commands run before each prompt:\n";
897 for my $action ( @$pre ) {
898 print $OUT "\t< -- $action\n";
904 $cmd =~ /^>\s*(.*)/ && do {
906 print $OUT "All > actions cleared.\n";
912 print $OUT "No post-prompt Perl actions.\n";
915 print $OUT "Perl commands run after each prompt:\n";
916 for my $action ( @$post ) {
917 print $OUT "\t> -- $action\n";
921 $post = [action($1)];
923 $cmd =~ /^\{\{\s*(.*)/ && do {
924 if ($cmd =~ /^\{.*\}$/ && unbalanced(substr($cmd,2))) {
925 print $OUT "{{ is now a debugger command\n",
926 "use `;{{' if you mean Perl code\n";
932 $cmd =~ /^\{\s*(.*)/ && do {
934 print $OUT "All { actions cleared.\n";
940 print $OUT "No pre-prompt debugger actions.\n";
943 print $OUT "Debugger commands run before each prompt:\n";
944 for my $action ( @$pretype ) {
945 print $OUT "\t{ -- $action\n";
949 if ($cmd =~ /^\{.*\}$/ && unbalanced(substr($cmd,1))) {
950 print $OUT "{ is now a debugger command\n",
951 "use `;{' if you mean Perl code\n";
957 $cmd =~ /^n$/ && do {
958 end_report(), next CMD if $finished and $level <= 1;
962 $cmd =~ /^s$/ && do {
963 end_report(), next CMD if $finished and $level <= 1;
967 $cmd =~ /^c\b\s*([\w:]*)\s*$/ && do {
968 end_report(), next CMD if $finished and $level <= 1;
970 # Probably not needed, since we finish an interactive
971 # sub-session anyway...
972 # local $filename = $filename;
973 # local *dbline = *dbline; # XXX Would this work?!
974 if ($subname =~ /\D/) { # subroutine name
975 $subname = $package."::".$subname
976 unless $subname =~ /::/;
977 ($file,$i) = (find_sub($subname) =~ /^(.*):(.*)$/);
981 *dbline = $main::{'_<' . $filename};
982 $had_breakpoints{$filename} |= 1;
984 ++$i while $dbline[$i] == 0 && $i < $max;
986 print $OUT "Subroutine $subname not found.\n";
991 if ($dbline[$i] == 0) {
992 print $OUT "Line $i not breakable.\n";
995 $dbline{$i} =~ s/($|\0)/;9$1/; # add one-time-only b.p.
997 for ($i=0; $i <= $stack_depth; ) {
1001 $cmd =~ /^r$/ && do {
1002 end_report(), next CMD if $finished and $level <= 1;
1003 $stack[$stack_depth] |= 1;
1004 $doret = $option{PrintRet} ? $stack_depth - 1 : -2;
1006 $cmd =~ /^R$/ && do {
1007 print $OUT "Warning: some settings and command-line options may be lost!\n";
1008 my (@script, @flags, $cl);
1009 push @flags, '-w' if $ini_warn;
1010 # Put all the old includes at the start to get
1011 # the same debugger.
1013 push @flags, '-I', $_;
1015 push @flags, '-T' if ${^TAINT};
1016 # Arrange for setting the old INC:
1017 set_list("PERLDB_INC", @ini_INC);
1019 for (1..$#{'::_<-e'}) { # The first line is PERL5DB
1020 chomp ($cl = ${'::_<-e'}[$_]);
1021 push @script, '-e', $cl;
1026 set_list("PERLDB_HIST",
1027 $term->Features->{getHistory}
1028 ? $term->GetHistory : @hist);
1029 my @had_breakpoints = keys %had_breakpoints;
1030 set_list("PERLDB_VISITED", @had_breakpoints);
1031 set_list("PERLDB_OPT", %option);
1032 set_list("PERLDB_ON_LOAD", %break_on_load);
1034 for (0 .. $#had_breakpoints) {
1035 my $file = $had_breakpoints[$_];
1036 *dbline = $main::{'_<' . $file};
1037 next unless %dbline or $postponed_file{$file};
1038 (push @hard, $file), next
1039 if $file =~ /^\(\w*eval/;
1041 @add = %{$postponed_file{$file}}
1042 if $postponed_file{$file};
1043 set_list("PERLDB_FILE_$_", %dbline, @add);
1045 for (@hard) { # Yes, really-really...
1046 # Find the subroutines in this eval
1047 *dbline = $main::{'_<' . $_};
1048 my ($quoted, $sub, %subs, $line) = quotemeta $_;
1049 for $sub (keys %sub) {
1050 next unless $sub{$sub} =~ /^$quoted:(\d+)-(\d+)$/;
1051 $subs{$sub} = [$1, $2];
1055 "No subroutines in $_, ignoring breakpoints.\n";
1058 LINES: for $line (keys %dbline) {
1059 # One breakpoint per sub only:
1060 my ($offset, $sub, $found);
1061 SUBS: for $sub (keys %subs) {
1062 if ($subs{$sub}->[1] >= $line # Not after the subroutine
1063 and (not defined $offset # Not caught
1064 or $offset < 0 )) { # or badly caught
1066 $offset = $line - $subs{$sub}->[0];
1067 $offset = "+$offset", last SUBS if $offset >= 0;
1070 if (defined $offset) {
1071 $postponed{$found} =
1072 "break $offset if $dbline{$line}";
1074 print $OUT "Breakpoint in $_:$line ignored: after all the subroutines.\n";
1078 set_list("PERLDB_POSTPONE", %postponed);
1079 set_list("PERLDB_PRETYPE", @$pretype);
1080 set_list("PERLDB_PRE", @$pre);
1081 set_list("PERLDB_POST", @$post);
1082 set_list("PERLDB_TYPEAHEAD", @typeahead);
1083 $ENV{PERLDB_RESTART} = 1;
1084 delete $ENV{PERLDB_PIDS}; # Restore ini state
1085 $ENV{PERLDB_PIDS} = $ini_pids if defined $ini_pids;
1086 #print "$^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS";
1087 exec($^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS) ||
1088 print $OUT "exec failed: $!\n";
1090 $cmd =~ /^T$/ && do {
1091 print_trace($OUT, 1); # skip DB
1093 $cmd =~ /^w\b\s*(.*)/s && do { &cmd_w($1); next CMD; };
1094 $cmd =~ /^W\b\s*(.*)/s && do { &cmd_W($1); next CMD; };
1095 $cmd =~ /^\/(.*)$/ && do {
1097 $inpat =~ s:([^\\])/$:$1:;
1099 # squelch the sigmangler
1100 local $SIG{__DIE__};
1101 local $SIG{__WARN__};
1102 eval '$inpat =~ m'."\a$inpat\a";
1114 $start = 1 if ($start > $max);
1115 last if ($start == $end);
1116 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
1117 if ($slave_editor) {
1118 print $OUT "\032\032$filename:$start:0\n";
1120 print $OUT "$start:\t", $dbline[$start], "\n";
1125 print $OUT "/$pat/: not found\n" if ($start == $end);
1127 $cmd =~ /^\?(.*)$/ && do {
1129 $inpat =~ s:([^\\])\?$:$1:;
1131 # squelch the sigmangler
1132 local $SIG{__DIE__};
1133 local $SIG{__WARN__};
1134 eval '$inpat =~ m'."\a$inpat\a";
1146 $start = $max if ($start <= 0);
1147 last if ($start == $end);
1148 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
1149 if ($slave_editor) {
1150 print $OUT "\032\032$filename:$start:0\n";
1152 print $OUT "$start:\t", $dbline[$start], "\n";
1157 print $OUT "?$pat?: not found\n" if ($start == $end);
1159 $cmd =~ /^$rc+\s*(-)?(\d+)?$/ && do {
1160 pop(@hist) if length($cmd) > 1;
1161 $i = $1 ? ($#hist-($2||1)) : ($2||$#hist);
1163 print $OUT $cmd, "\n";
1165 $cmd =~ /^$sh$sh\s*([\x00-\xff]*)/ && do {
1168 $cmd =~ /^$rc([^$rc].*)$/ && do {
1170 pop(@hist) if length($cmd) > 1;
1171 for ($i = $#hist; $i; --$i) {
1172 last if $hist[$i] =~ /$pat/;
1175 print $OUT "No such command!\n\n";
1179 print $OUT $cmd, "\n";
1181 $cmd =~ /^$sh$/ && do {
1182 &system($ENV{SHELL}||"/bin/sh");
1184 $cmd =~ /^$sh\s*([\x00-\xff]*)/ && do {
1185 # XXX: using csh or tcsh destroys sigint retvals!
1186 #&system($1); # use this instead
1187 &system($ENV{SHELL}||"/bin/sh","-c",$1);
1189 $cmd =~ /^H\b\s*(-(\d+))?/ && do {
1190 $end = $2 ? ($#hist-$2) : 0;
1191 $hist = 0 if $hist < 0;
1192 for ($i=$#hist; $i>$end; $i--) {
1193 print $OUT "$i: ",$hist[$i],"\n"
1194 unless $hist[$i] =~ /^.?$/;
1197 $cmd =~ /^(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?$/ && do {
1200 $cmd =~ s/^p$/print {\$DB::OUT} \$_/;
1201 $cmd =~ s/^p\b/print {\$DB::OUT} /;
1202 $cmd =~ s/^=\s*// && do {
1204 if (length $cmd == 0) {
1205 @keys = sort keys %alias;
1206 } elsif (my($k,$v) = ($cmd =~ /^(\S+)\s+(\S.*)/)) {
1207 # can't use $_ or kill //g state
1208 for my $x ($k, $v) { $x =~ s/\a/\\a/g }
1209 $alias{$k} = "s\a$k\a$v\a";
1210 # squelch the sigmangler
1211 local $SIG{__DIE__};
1212 local $SIG{__WARN__};
1213 unless (eval "sub { s\a$k\a$v\a }; 1") {
1214 print $OUT "Can't alias $k to $v: $@\n";
1223 if ((my $v = $alias{$k}) =~ s
\as\a$k\a(.*)\a$
\a1
\a) {
1224 print $OUT "$k\t= $1\n";
1226 elsif (defined $alias{$k}) {
1227 print $OUT "$k\t$alias{$k}\n";
1230 print "No alias for $k\n";
1234 $cmd =~ /^\@\s*(.*\S)/ && do {
1235 if (open my $fh, $1) {
1238 &warn("Can't execute `$1': $!\n");
1241 $cmd =~ /^\|\|?\s*[^|]/ && do {
1242 if ($pager =~ /^\|/) {
1243 open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
1244 open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
1246 open(SAVEOUT,">&OUT") || &warn("Can't save DB::OUT");
1249 unless ($piped=open(OUT,$pager)) {
1250 &warn("Can't pipe output to `$pager'");
1251 if ($pager =~ /^\|/) {
1252 open(OUT,">&STDOUT") # XXX: lost message
1253 || &warn("Can't restore DB::OUT");
1254 open(STDOUT,">&SAVEOUT")
1255 || &warn("Can't restore STDOUT");
1258 open(OUT,">&STDOUT") # XXX: lost message
1259 || &warn("Can't restore DB::OUT");
1263 $SIG{PIPE}= \&DB::catch if $pager =~ /^\|/
1264 && ("" eq $SIG{PIPE} || "DEFAULT" eq $SIG{PIPE});
1265 $selected= select(OUT);
1267 select( $selected ), $selected= "" unless $cmd =~ /^\|\|/;
1268 $cmd =~ s/^\|+\s*//;
1271 # XXX Local variants do not work!
1272 $cmd =~ s/^t\s/\$DB::trace |= 1;\n/;
1273 $cmd =~ s/^s\s/\$DB::single = 1;\n/ && do {$laststep = 's'};
1274 $cmd =~ s/^n\s/\$DB::single = 2;\n/ && do {$laststep = 'n'};
1276 $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd"; &eval;
1278 $onetimeDump = undef;
1279 $onetimedumpDepth = undef;
1280 } elsif ($term_pid == $$) {
1285 if ($pager =~ /^\|/) {
1287 # we cannot warn here: the handle is missing --tchrist
1288 close(OUT) || print SAVEOUT "\nCan't close DB::OUT\n";
1290 # most of the $? crud was coping with broken cshisms
1292 print SAVEOUT "Pager `$pager' failed: ";
1294 print SAVEOUT "shell returned -1\n";
1297 ( $? & 127 ) ? " (SIG#".($?&127).")" : "",
1298 ( $? & 128 ) ? " -- core dumped" : "", "\n";
1300 print SAVEOUT "status ", ($? >> 8), "\n";
1304 open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
1305 open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
1306 $SIG{PIPE} = "DEFAULT" if $SIG{PIPE} eq \&DB::catch;
1307 # Will stop ignoring SIGPIPE if done like nohup(1)
1308 # does SIGINT but Perl doesn't give us a choice.
1310 open(OUT,">&SAVEOUT") || &warn("Can't restore DB::OUT");
1313 select($selected), $selected= "" unless $selected eq "";
1317 $fall_off_end = 1 unless defined $cmd; # Emulate `q' on EOF
1318 foreach $evalarg (@$post) {
1321 } # if ($single || $signal)
1322 ($@, $!, $^E, $,, $/, $\, $^W) = @saved;
1326 # The following code may be executed now:
1330 my ($al, $ret, @ret) = "";
1331 if (length($sub) > 10 && substr($sub, -10, 10) eq '::AUTOLOAD') {
1334 local $stack_depth = $stack_depth + 1; # Protect from non-local exits
1335 $#stack = $stack_depth;
1336 $stack[-1] = $single;
1338 $single |= 4 if $stack_depth == $deep;
1340 ? ( print_lineinfo(' ' x ($stack_depth - 1), "in "),
1341 # Why -1? But it works! :-(
1342 print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
1343 : print_lineinfo(' ' x ($stack_depth - 1), "entering $sub$al\n")) if $frame;
1346 $single |= $stack[$stack_depth--];
1348 ? ( print_lineinfo(' ' x $stack_depth, "out "),
1349 print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
1350 : print_lineinfo(' ' x $stack_depth, "exited $sub$al\n")) if $frame & 2;
1351 if ($doret eq $stack_depth or $frame & 16) {
1352 my $fh = ($doret eq $stack_depth ? $OUT : $LINEINFO);
1353 print $fh ' ' x $stack_depth if $frame & 16;
1354 print $fh "list context return from $sub:\n";
1355 dumpit($fh, \@ret );
1360 if (defined wantarray) {
1365 $single |= $stack[$stack_depth--];
1367 ? ( print_lineinfo(' ' x $stack_depth, "out "),
1368 print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
1369 : print_lineinfo(' ' x $stack_depth, "exited $sub$al\n")) if $frame & 2;
1370 if ($doret eq $stack_depth or $frame & 16 and defined wantarray) {
1371 my $fh = ($doret eq $stack_depth ? $OUT : $LINEINFO);
1372 print $fh (' ' x $stack_depth) if $frame & 16;
1373 print $fh (defined wantarray
1374 ? "scalar context return from $sub: "
1375 : "void context return from $sub\n");
1376 dumpit( $fh, $ret ) if defined wantarray;
1385 ### Functions with multiple modes of failure die on error, the rest
1386 ### returns FALSE on error.
1387 ### User-interface functions cmd_* output error message.
1389 ### Note all cmd_[a-zA-Z]'s require $line, $dblineno as first arguments
1394 'A' => 'pre580_null',
1396 'B' => 'pre580_null',
1397 'd' => 'pre580_null',
1400 'M' => 'pre580_null',
1402 'o' => 'pre580_null',
1412 my $dblineno = shift;
1414 # with this level of indirection we can wrap
1415 # to old (pre580) or other command sets easily
1418 $set{$CommandSet}{$cmd} || $cmd
1420 # print "rjsf: cmd_wrapper($cmd): $CommandSet($set{$CommandSet}{$cmd}) => call($call)\n";
1422 return &$call($line, $dblineno);
1426 my $line = shift || ''; # [.|line] expr
1427 my $dbline = shift; $line =~ s/^(\.|(?:[^\d]))/$dbline/;
1428 if ($line =~ /^\s*(\d*)\s*(\S.+)/) {
1429 my ($lineno, $expr) = ($1, $2);
1431 if ($dbline[$lineno] == 0) {
1432 print $OUT "Line $lineno($dbline[$lineno]) does not have an action?\n";
1434 $had_breakpoints{$filename} |= 2;
1435 $dbline{$lineno} =~ s/\0[^\0]*//;
1436 $dbline{$lineno} .= "\0" . action($expr);
1440 print $OUT "Adding an action requires an optional lineno and an expression\n"; # hint
1445 my $line = shift || '';
1446 my $dbline = shift; $line =~ s/^\./$dbline/;
1448 eval { &delete_action(); 1 } or print $OUT $@ and return;
1449 } elsif ($line =~ /^(\S.*)/) {
1450 eval { &delete_action($1); 1 } or print $OUT $@ and return;
1452 print $OUT "Deleting an action requires a line number, or '*' for all\n"; # hint
1459 die "Line $i has no action .\n" if $dbline[$i] == 0;
1460 $dbline{$i} =~ s/\0[^\0]*//; # \^a
1461 delete $dbline{$i} if $dbline{$i} eq '';
1463 print $OUT "Deleting all actions...\n";
1464 for my $file (keys %had_breakpoints) {
1465 local *dbline = $main::{'_<' . $file};
1468 for ($i = 1; $i <= $max ; $i++) {
1469 if (defined $dbline{$i}) {
1470 $dbline{$i} =~ s/\0[^\0]*//;
1471 delete $dbline{$i} if $dbline{$i} eq '';
1473 unless ($had_breakpoints{$file} &= ~2) {
1474 delete $had_breakpoints{$file};
1482 my $line = shift; # [.|line] [cond]
1483 my $dbline = shift; $line =~ s/^\./$dbline/;
1484 if ($line =~ /^\s*$/) {
1485 &cmd_b_line($dbline, 1);
1486 } elsif ($line =~ /^load\b\s*(.*)/) {
1487 my $file = $1; $file =~ s/\s+$//;
1489 } elsif ($line =~ /^(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/) {
1490 my $cond = length $3 ? $3 : '1';
1491 my ($subname, $break) = ($2, $1 eq 'postpone');
1492 $subname =~ s/\'/::/g;
1493 $subname = "${'package'}::" . $subname unless $subname =~ /::/;
1494 $subname = "main".$subname if substr($subname,0,2) eq "::";
1495 $postponed{$subname} = $break ? "break +0 if $cond" : "compile";
1496 } elsif ($line =~ /^([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/) {
1498 $cond = length $2 ? $2 : '1';
1499 &cmd_b_sub($subname, $cond);
1500 } elsif ($line =~ /^(\d*)\s*(.*)/) {
1501 $line = $1 || $dbline;
1502 $cond = length $2 ? $2 : '1';
1503 &cmd_b_line($line, $cond);
1505 print "confused by line($line)?\n";
1511 $break_on_load{$file} = 1;
1512 $had_breakpoints{$file} |= 1;
1515 sub report_break_on_load {
1516 sort keys %break_on_load;
1524 push @files, $::INC{$file} if $::INC{$file};
1525 $file .= '.pm', redo unless $file =~ /\./;
1527 break_on_load($_) for @files;
1528 @files = report_break_on_load;
1529 print $OUT "Will stop on load of `@files'.\n";
1532 $filename_error = '';
1534 sub breakable_line {
1535 my ($from, $to) = @_;
1538 my $delta = $from < $to ? +1 : -1;
1539 my $limit = $delta > 0 ? $#dbline : 1;
1540 $limit = $to if ($limit - $to) * $delta > 0;
1541 $i += $delta while $dbline[$i] == 0 and ($limit - $i) * $delta > 0;
1543 return $i unless $dbline[$i] == 0;
1544 my ($pl, $upto) = ('', '');
1545 ($pl, $upto) = ('s', "..$to") if @_ >=2 and $from != $to;
1546 die "Line$pl $from$upto$filename_error not breakable\n";
1549 sub breakable_line_in_filename {
1551 local *dbline = $main::{'_<' . $f};
1552 local $filename_error = " of `$f'";
1557 my ($i, $cond) = @_;
1558 $cond = 1 unless @_ >= 2;
1562 die "Line $i$filename_error not breakable.\n" if $dbline[$i] == 0;
1563 $had_breakpoints{$filename} |= 1;
1564 if ($dbline{$i}) { $dbline{$i} =~ s/^[^\0]*/$cond/; }
1565 else { $dbline{$i} = $cond; }
1569 eval { break_on_line(@_); 1 } or print $OUT $@ and return;
1572 sub break_on_filename_line {
1573 my ($f, $i, $cond) = @_;
1574 $cond = 1 unless @_ >= 3;
1575 local *dbline = $main::{'_<' . $f};
1576 local $filename_error = " of `$f'";
1577 local $filename = $f;
1578 break_on_line($i, $cond);
1581 sub break_on_filename_line_range {
1582 my ($f, $from, $to, $cond) = @_;
1583 my $i = breakable_line_in_filename($f, $from, $to);
1584 $cond = 1 unless @_ >= 3;
1585 break_on_filename_line($f,$i,$cond);
1588 sub subroutine_filename_lines {
1589 my ($subname,$cond) = @_;
1590 # Filename below can contain ':'
1591 find_sub($subname) =~ /^(.*):(\d+)-(\d+)$/;
1594 sub break_subroutine {
1595 my $subname = shift;
1596 my ($file,$s,$e) = subroutine_filename_lines($subname) or
1597 die "Subroutine $subname not found.\n";
1598 $cond = 1 unless @_ >= 2;
1599 break_on_filename_line_range($file,$s,$e,@_);
1603 my ($subname,$cond) = @_;
1604 $cond = 1 unless @_ >= 2;
1605 unless (ref $subname eq 'CODE') {
1606 $subname =~ s/\'/::/g;
1608 $subname = "${'package'}::" . $subname
1609 unless $subname =~ /::/;
1610 $subname = "CORE::GLOBAL::$s"
1611 if not defined &$subname and $s !~ /::/ and defined &{"CORE::GLOBAL::$s"};
1612 $subname = "main".$subname if substr($subname,0,2) eq "::";
1614 eval { break_subroutine($subname,$cond); 1 } or print $OUT $@ and return;
1618 my $line = ($_[0] =~ /^\./) ? $dbline : shift || '';
1619 my $dbline = shift; $line =~ s/^\./$dbline/;
1621 eval { &delete_breakpoint(); 1 } or print $OUT $@ and return;
1622 } elsif ($line =~ /^(\S.*)/) {
1623 eval { &delete_breakpoint($line || $dbline); 1 } or print $OUT $@ and return;
1625 print $OUT "Deleting a breakpoint requires a line number, or '*' for all\n"; # hint
1629 sub delete_breakpoint {
1632 die "Line $i not breakable.\n" if $dbline[$i] == 0;
1633 $dbline{$i} =~ s/^[^\0]*//;
1634 delete $dbline{$i} if $dbline{$i} eq '';
1636 print $OUT "Deleting all breakpoints...\n";
1637 for my $file (keys %had_breakpoints) {
1638 local *dbline = $main::{'_<' . $file};
1641 for ($i = 1; $i <= $max ; $i++) {
1642 if (defined $dbline{$i}) {
1643 $dbline{$i} =~ s/^[^\0]+//;
1644 if ($dbline{$i} =~ s/^\0?$//) {
1649 if (not $had_breakpoints{$file} &= ~1) {
1650 delete $had_breakpoints{$file};
1654 undef %postponed_file;
1655 undef %break_on_load;
1659 sub cmd_stop { # As on ^C, but not signal-safy.
1664 my $line = shift || '';
1665 if ($line =~ /^h\s*/) {
1667 } elsif ($line =~ /^(\S.*)$/) {
1668 # support long commands; otherwise bogus errors
1669 # happen when you ask for h on <CR> for example
1670 my $asked = $1; # for proper errmsg
1671 my $qasked = quotemeta($asked); # for searching
1672 # XXX: finds CR but not <CR>
1673 if ($help =~ /^<?(?:[IB]<)$qasked/m) {
1674 while ($help =~ /^(<?(?:[IB]<)$qasked([\s\S]*?)\n)(?!\s)/mg) {
1678 print_help("B<$asked> is not a debugger command.\n");
1681 print_help($summary);
1687 $line =~ s/^-\s*$/-/;
1688 if ($line =~ /^(\$.*)/s) {
1691 print($OUT "Error: $@\n"), next CMD if $@;
1693 print($OUT "Interpreted as: $1 $s\n");
1696 } elsif ($line =~ /^([\':A-Za-z_][\':\w]*(\[.*\])?)/s) {
1697 my $s = $subname = $1;
1698 $subname =~ s/\'/::/;
1699 $subname = $package."::".$subname
1700 unless $subname =~ /::/;
1701 $subname = "CORE::GLOBAL::$s"
1702 if not defined &$subname and $s !~ /::/
1703 and defined &{"CORE::GLOBAL::$s"};
1704 $subname = "main".$subname if substr($subname,0,2) eq "::";
1705 @pieces = split(/:/,find_sub($subname) || $sub{$subname});
1706 $subrange = pop @pieces;
1707 $file = join(':', @pieces);
1708 if ($file ne $filename) {
1709 print $OUT "Switching to file '$file'.\n"
1710 unless $slave_editor;
1711 *dbline = $main::{'_<' . $file};
1716 if (eval($subrange) < -$window) {
1717 $subrange =~ s/-.*/+/;
1722 print $OUT "Subroutine $subname not found.\n";
1724 } elsif ($line =~ /^\s*$/) {
1725 $incr = $window - 1;
1726 $line = $start . '-' . ($start + $incr);
1728 } elsif ($line =~ /^(\d*)\+(\d*)$/) {
1731 $incr = $window - 1 unless $incr;
1732 $line = $start . '-' . ($start + $incr);
1734 } elsif ($line =~ /^((-?[\d\$\.]+)([-,]([\d\$\.]+))?)?/) {
1735 $end = (!defined $2) ? $max : ($4 ? $4 : $2);
1736 $end = $max if $end > $max;
1738 $i = $line if $i eq '.';
1741 if ($slave_editor) {
1742 print $OUT "\032\032$filename:$i:0\n";
1745 for (; $i <= $end; $i++) {
1747 ($stop,$action) = split(/\0/, $dbline{$i}) if
1750 and $filename eq $filename_ini)
1752 : ($dbline[$i]+0 ? ':' : ' ') ;
1753 $arrow .= 'b' if $stop;
1754 $arrow .= 'a' if $action;
1755 print $OUT "$i$arrow\t", $dbline[$i];
1756 $i++, last if $signal;
1758 print $OUT "\n" unless $dbline[$i-1] =~ /\n$/;
1760 $start = $i; # remember in case they want more
1761 $start = $max if $start > $max;
1766 my $arg = shift || 'abw'; $arg = 'abw' unless $CommandSet eq '580'; # sigh...
1767 my $action_wanted = ($arg =~ /a/) ? 1 : 0;
1768 my $break_wanted = ($arg =~ /b/) ? 1 : 0;
1769 my $watch_wanted = ($arg =~ /w/) ? 1 : 0;
1771 if ($break_wanted or $action_wanted) {
1772 for my $file (keys %had_breakpoints) {
1773 local *dbline = $main::{'_<' . $file};
1776 for ($i = 1; $i <= $max; $i++) {
1777 if (defined $dbline{$i}) {
1778 print $OUT "$file:\n" unless $was++;
1779 print $OUT " $i:\t", $dbline[$i];
1780 ($stop,$action) = split(/\0/, $dbline{$i});
1781 print $OUT " break if (", $stop, ")\n"
1782 if $stop and $break_wanted;
1783 print $OUT " action: ", $action, "\n"
1784 if $action and $action_wanted;
1790 if (%postponed and $break_wanted) {
1791 print $OUT "Postponed breakpoints in subroutines:\n";
1793 for $subname (keys %postponed) {
1794 print $OUT " $subname\t$postponed{$subname}\n";
1798 my @have = map { # Combined keys
1799 keys %{$postponed_file{$_}}
1800 } keys %postponed_file;
1801 if (@have and ($break_wanted or $action_wanted)) {
1802 print $OUT "Postponed breakpoints in files:\n";
1804 for $file (keys %postponed_file) {
1805 my $db = $postponed_file{$file};
1806 print $OUT " $file:\n";
1807 for $line (sort {$a <=> $b} keys %$db) {
1808 print $OUT " $line:\n";
1809 my ($stop,$action) = split(/\0/, $$db{$line});
1810 print $OUT " break if (", $stop, ")\n"
1811 if $stop and $break_wanted;
1812 print $OUT " action: ", $action, "\n"
1813 if $action and $action_wanted;
1819 if (%break_on_load and $break_wanted) {
1820 print $OUT "Breakpoints on load:\n";
1822 for $file (keys %break_on_load) {
1823 print $OUT " $file\n";
1827 if ($watch_wanted) {
1829 print $OUT "Watch-expressions:\n" if @to_watch;
1830 for my $expr (@to_watch) {
1831 print $OUT " $expr\n";
1843 my $opt = shift || ''; # opt[=val]
1844 if ($opt =~ /^(\S.*)/) {
1856 if ($line =~ /^(\d*)$/) {
1857 $incr = $window - 1;
1860 $line = $start . '-' . ($start + $incr);
1866 my $expr = shift || '';
1867 if ($expr =~ /^(\S.*)/) {
1868 push @to_watch, $expr;
1871 $val = (defined $val) ? "'$val'" : 'undef' ;
1872 push @old_watch, $val;
1875 print $OUT "Adding a watch-expression requires an expression\n"; # hint
1880 my $expr = shift || '';
1883 print $OUT "Deleting all watch expressions ...\n";
1884 @to_watch = @old_watch = ();
1885 } elsif ($expr =~ /^(\S.*)/) {
1887 foreach (@to_watch) {
1888 my $val = $to_watch[$i_cnt];
1889 if ($val eq $expr) { # =~ m/^\Q$i$/) {
1890 splice(@to_watch, $i_cnt, 1);
1895 print $OUT "Deleting a watch-expression requires an expression, or '*' for all\n"; # hint
1899 ### END of the API section
1902 @saved = ($@, $!, $^E, $,, $/, $\, $^W);
1903 $, = ""; $/ = "\n"; $\ = ""; $^W = 0;
1906 sub print_lineinfo {
1907 resetterm(1) if $LINEINFO eq $OUT and $term_pid != $$;
1911 # The following takes its argument via $evalarg to preserve current @_
1914 my $subname = shift;
1915 if ($postponed{$subname} =~ s/^break\s([+-]?\d+)\s+if\s//) {
1916 my $offset = $1 || 0;
1917 # Filename below can contain ':'
1918 my ($file,$i) = (find_sub($subname) =~ /^(.*):(\d+)-.*$/);
1921 local *dbline = $main::{'_<' . $file};
1922 local $^W = 0; # != 0 is magical below
1923 $had_breakpoints{$file} |= 1;
1925 ++$i until $dbline[$i] != 0 or $i >= $max;
1926 $dbline{$i} = delete $postponed{$subname};
1928 print $OUT "Subroutine $subname not found.\n";
1932 elsif ($postponed{$subname} eq 'compile') { $signal = 1 }
1933 #print $OUT "In postponed_sub for `$subname'.\n";
1937 if ($ImmediateStop) {
1941 return &postponed_sub
1942 unless ref \$_[0] eq 'GLOB'; # A subroutine is compiled.
1943 # Cannot be done before the file is compiled
1944 local *dbline = shift;
1945 my $filename = $dbline;
1946 $filename =~ s/^_<//;
1947 $signal = 1, print $OUT "'$filename' loaded...\n"
1948 if $break_on_load{$filename};
1949 print_lineinfo(' ' x $stack_depth, "Package $filename.\n") if $frame;
1950 return unless $postponed_file{$filename};
1951 $had_breakpoints{$filename} |= 1;
1952 #%dbline = %{$postponed_file{$filename}}; # Cannot be done: unsufficient magic
1954 for $key (keys %{$postponed_file{$filename}}) {
1955 $dbline{$key} = ${$postponed_file{$filename}}{$key};
1957 delete $postponed_file{$filename};
1961 local ($savout) = select(shift);
1962 my $osingle = $single;
1963 my $otrace = $trace;
1964 $single = $trace = 0;
1967 unless (defined &main::dumpValue) {
1970 if (defined &main::dumpValue) {
1972 my $maxdepth = shift || $option{dumpDepth};
1973 $maxdepth = -1 unless defined $maxdepth; # -1 means infinite depth
1974 &main::dumpValue($v, $maxdepth);
1976 print $OUT "dumpvar.pl not available.\n";
1983 # Tied method do not create a context, so may get wrong message:
1987 resetterm(1) if $fh eq $LINEINFO and $LINEINFO eq $OUT and $term_pid != $$;
1988 my @sub = dump_trace($_[0] + 1, $_[1]);
1989 my $short = $_[2]; # Print short report, next one for sub name
1991 for ($i=0; $i <= $#sub; $i++) {
1994 my $args = defined $sub[$i]{args}
1995 ? "(@{ $sub[$i]{args} })"
1997 $args = (substr $args, 0, $maxtrace - 3) . '...'
1998 if length $args > $maxtrace;
1999 my $file = $sub[$i]{file};
2000 $file = $file eq '-e' ? $file : "file `$file'" unless $short;
2002 $s = (substr $s, 0, $maxtrace - 3) . '...' if length $s > $maxtrace;
2004 my $sub = @_ >= 4 ? $_[3] : $s;
2005 print $fh "$sub[$i]{context}=$sub$args from $file:$sub[$i]{line}\n";
2007 print $fh "$sub[$i]{context} = $s$args" .
2008 " called from $file" .
2009 " line $sub[$i]{line}\n";
2016 my $count = shift || 1e9;
2019 my ($p,$file,$line,$sub,$h,$args,$e,$r,@a,@sub,$context);
2020 my $nothard = not $frame & 8;
2021 local $frame = 0; # Do not want to trace this.
2022 my $otrace = $trace;
2025 $i < $count and ($p,$file,$line,$sub,$h,$context,$e,$r) = caller($i);
2030 if (not defined $arg) {
2032 } elsif ($nothard and tied $arg) {
2034 } elsif ($nothard and $type = ref $arg) {
2035 push @a, "ref($type)";
2037 local $_ = "$arg"; # Safe to stringify now - should not call f().
2040 unless /^(?: -?[\d.]+ | \*[\w:]* )$/x;
2041 s/([\200-\377])/sprintf("M-%c",ord($1)&0177)/eg;
2042 s/([\0-\37\177])/sprintf("^%c",ord($1)^64)/eg;
2046 $context = $context ? '@' : (defined $context ? "\$" : '.');
2047 $args = $h ? [@a] : undef;
2048 $e =~ s/\n\s*\;\s*\Z// if $e;
2049 $e =~ s/([\\\'])/\\$1/g if $e;
2051 $sub = "require '$e'";
2052 } elsif (defined $r) {
2054 } elsif ($sub eq '(eval)') {
2055 $sub = "eval {...}";
2057 push(@sub, {context => $context, sub => $sub, args => $args,
2058 file => $file, line => $line});
2067 while ($action =~ s/\\$//) {
2076 # i hate using globals!
2077 $balanced_brace_re ||= qr{
2080 (?> [^{}] + ) # Non-parens without backtracking
2082 (??{ $balanced_brace_re }) # Group with matching parens
2086 return $_[0] !~ m/$balanced_brace_re/;
2090 &readline("cont: ");
2094 # We save, change, then restore STDIN and STDOUT to avoid fork() since
2095 # some non-Unix systems can do system() but have problems with fork().
2096 open(SAVEIN,"<&STDIN") || &warn("Can't save STDIN");
2097 open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
2098 open(STDIN,"<&IN") || &warn("Can't redirect STDIN");
2099 open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
2101 # XXX: using csh or tcsh destroys sigint retvals!
2103 open(STDIN,"<&SAVEIN") || &warn("Can't restore STDIN");
2104 open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
2109 # most of the $? crud was coping with broken cshisms
2111 &warn("(Command exited ", ($? >> 8), ")\n");
2113 &warn( "(Command died of SIG#", ($? & 127),
2114 (($? & 128) ? " -- core dumped" : "") , ")", "\n");
2124 eval { require Term::ReadLine } or die $@;
2127 my ($i, $o) = split $tty, /,/;
2128 $o = $i unless defined $o;
2129 open(IN,"<$i") or die "Cannot open TTY `$i' for read: $!";
2130 open(OUT,">$o") or die "Cannot open TTY `$o' for write: $!";
2133 my $sel = select($OUT);
2137 eval "require Term::Rendezvous;" or die;
2138 my $rv = $ENV{PERLDB_NOTTY} || "/tmp/perldbtty$$";
2139 my $term_rv = new Term::Rendezvous $rv;
2141 $OUT = $term_rv->OUT;
2144 if ($term_pid eq '-1') { # In a TTY with another debugger
2148 $term = new Term::ReadLine::Stub 'perldb', $IN, $OUT;
2150 $term = new Term::ReadLine 'perldb', $IN, $OUT;
2152 $rl_attribs = $term->Attribs;
2153 $rl_attribs->{basic_word_break_characters} .= '-:+/*,[])}'
2154 if defined $rl_attribs->{basic_word_break_characters}
2155 and index($rl_attribs->{basic_word_break_characters}, ":") == -1;
2156 $rl_attribs->{special_prefixes} = '$@&%';
2157 $rl_attribs->{completer_word_break_characters} .= '$@&%';
2158 $rl_attribs->{completion_function} = \&db_complete;
2160 $LINEINFO = $OUT unless defined $LINEINFO;
2161 $lineinfo = $console unless defined $lineinfo;
2163 if ($term->Features->{setHistory} and "@hist" ne "?") {
2164 $term->SetHistory(@hist);
2166 ornaments($ornaments) if defined $ornaments;
2170 # Example get_fork_TTY functions
2171 sub xterm_get_fork_TTY {
2172 (my $name = $0) =~ s,^.*[/\\],,s;
2173 open XT, qq[3>&1 xterm -title "Daughter Perl debugger $pids $name" -e sh -c 'tty 1>&3;\
2177 $pidprompt = ''; # Shown anyway in titlebar
2181 # This example function resets $IN, $OUT itself
2182 sub os2_get_fork_TTY {
2183 local $^F = 40; # XXXX Fixme!
2184 my ($in1, $out1, $in2, $out2);
2185 # Having -d in PERL5OPT would lead to a disaster...
2186 local $ENV{PERL5OPT} = $ENV{PERL5OPT} if $ENV{PERL5OPT};
2187 $ENV{PERL5OPT} =~ s/(?:^|(?<=\s))-d\b// if $ENV{PERL5OPT};
2188 $ENV{PERL5OPT} =~ s/(?:^|(?<=\s))-d\B/-/ if $ENV{PERL5OPT};
2189 print $OUT "Making kid PERL5OPT->`$ENV{PERL5OPT}'.\n" if $ENV{PERL5OPT};
2190 (my $name = $0) =~ s,^.*[/\\],,s;
2192 if ( pipe $in1, $out1 and pipe $in2, $out2
2193 # system P_SESSION will fail if there is another process
2194 # in the same session with a "dependent" asynchronous child session.
2195 and @args = ($rl, fileno $in1, fileno $out2,
2196 "Daughter Perl debugger $pids $name") and
2197 (($kpid = CORE::system 4, $^X, '-we', <<'ES', @args) >= 0 # P_SESSION
2200 my ($rl, $in) = (shift, shift); # Read from $in and pass through
2202 system P_NOWAIT, $^X, '-we', <<EOS or die "Cannot start a grandkid";
2203 open IN, '<&=$in' or die "open <&=$in: \$!";
2204 \$| = 1; print while sysread IN, \$_, 1<<16;
2208 open OUT, ">&=$out" or die "Cannot open &=$out for writing: $!";
2210 require Term::ReadKey if $rl;
2211 Term::ReadKey::ReadMode(4) if $rl; # Nodelay on kbd. Pipe is automatically nodelay...
2212 print while sysread STDIN, $_, 1<<($rl ? 16 : 0);
2214 or warn "system P_SESSION: $!, $^E" and 0)
2215 and close $in1 and close $out2 ) {
2216 $pidprompt = ''; # Shown anyway in titlebar
2217 reset_IN_OUT($in2, $out1);
2219 return ''; # Indicate that reset_IN_OUT is called
2224 sub create_IN_OUT { # Create a window with IN/OUT handles redirected there
2225 my $in = &get_fork_TTY if defined &get_fork_TTY;
2226 $in = $fork_TTY if defined $fork_TTY; # Backward compatibility
2227 if (not defined $in) {
2229 print_help(<<EOP) if $why == 1;
2230 I<#########> Forked, but do not know how to create a new B<TTY>. I<#########>
2232 print_help(<<EOP) if $why == 2;
2233 I<#########> Daughter session, do not know how to change a B<TTY>. I<#########>
2234 This may be an asynchronous session, so the parent debugger may be active.
2236 print_help(<<EOP) if $why != 4;
2237 Since two debuggers fight for the same TTY, input is severely entangled.
2241 I know how to switch the output to a different window in xterms
2242 and OS/2 consoles only. For a manual switch, put the name of the created I<TTY>
2243 in B<\$DB::fork_TTY>, or define a function B<DB::get_fork_TTY()> returning this.
2245 On I<UNIX>-like systems one can get the name of a I<TTY> for the given window
2246 by typing B<tty>, and disconnect the I<shell> from I<TTY> by B<sleep 1000000>.
2249 } elsif ($in ne '') {
2252 $console = ''; # Indicate no need to open-from-the-console
2257 sub resetterm { # We forked, so we need a different TTY
2259 my $systemed = $in > 1 ? '-' : '';
2261 $pids =~ s/\]/$systemed->$$]/;
2263 $pids = "[$term_pid->$$]";
2267 return unless $CreateTTY & $in;
2274 my $left = @typeahead;
2275 my $got = shift @typeahead;
2276 print $OUT "auto(-$left)", shift, $got, "\n";
2277 $term->AddHistory($got)
2278 if length($got) > 1 and defined $term->Features->{addHistory};
2284 my $line = CORE::readline($cmdfhs[-1]);
2285 defined $line ? (print $OUT ">> $line" and return $line)
2286 : close pop @cmdfhs;
2288 if (ref $OUT and UNIVERSAL::isa($OUT, 'IO::Socket::INET')) {
2289 $OUT->write(join('', @_));
2291 $IN->recv( $stuff, 2048 ); # XXX: what's wrong with sysread?
2295 $term->readline(@_);
2300 my ($opt, $val)= @_;
2301 $val = option_val($opt,'N/A');
2302 $val =~ s/([\\\'])/\\$1/g;
2303 printf $OUT "%20s = '%s'\n", $opt, $val;
2307 my ($opt, $default)= @_;
2309 if (defined $optionVars{$opt}
2310 and defined ${$optionVars{$opt}}) {
2311 $val = ${$optionVars{$opt}};
2312 } elsif (defined $optionAction{$opt}
2313 and defined &{$optionAction{$opt}}) {
2314 $val = &{$optionAction{$opt}}();
2315 } elsif (defined $optionAction{$opt}
2316 and not defined $option{$opt}
2317 or defined $optionVars{$opt}
2318 and not defined ${$optionVars{$opt}}) {
2321 $val = $option{$opt};
2323 $val = $default unless defined $val;
2329 # too dangerous to let intuitive usage overwrite important things
2330 # defaultion should never be the default
2331 my %opt_needs_val = map { ( $_ => 1 ) } qw{
2332 dumpDepth arrayDepth hashDepth LineInfo maxTraceLen ornaments windowSize
2333 pager quote ReadLine recallCommand RemotePort ShellBang TTY
2338 s/^(\w+)(\W?)// or print($OUT "Invalid option `$_'\n"), last;
2339 my ($opt,$sep) = ($1,$2);
2342 print($OUT "Option query `$opt?' followed by non-space `$_'\n"), last
2344 #&dump_option($opt);
2345 } elsif ($sep !~ /\S/) {
2347 $val = "1"; # this is an evil default; make 'em set it!
2348 } elsif ($sep eq "=") {
2349 if (s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x) {
2351 ($val = $2) =~ s/\\([$quote\\])/$1/g;
2355 print OUT qq(Option better cleared using $opt=""\n)
2359 } else { #{ to "let some poor schmuck bounce on the % key in B<vi>."
2360 my ($end) = "\\" . substr( ")]>}$sep", index("([<{",$sep), 1 ); #}
2361 s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)// or
2362 print($OUT "Unclosed option value `$opt$sep$_'\n"), last;
2363 ($val = $1) =~ s/\\([\\$end])/$1/g;
2367 my $matches = grep( /^\Q$opt/ && ($option = $_), @options )
2368 || grep( /^\Q$opt/i && ($option = $_), @options );
2370 print($OUT "Unknown option `$opt'\n"), next unless $matches;
2371 print($OUT "Ambiguous option `$opt'\n"), next if $matches > 1;
2373 if ($opt_needs_val{$option} && $val_defaulted) {
2374 my $cmd = ($CommandSet eq '580') ? 'o' : 'O';
2375 print $OUT "Option `$opt' is non-boolean. Use `$cmd $option=VAL' to set, `$cmd $option?' to query\n";
2379 $option{$option} = $val if defined $val;
2384 require '$optionRequire{$option}';
2386 } || die # XXX: shouldn't happen
2387 if defined $optionRequire{$option} &&
2390 ${$optionVars{$option}} = $val
2391 if defined $optionVars{$option} &&
2394 &{$optionAction{$option}} ($val)
2395 if defined $optionAction{$option} &&
2396 defined &{$optionAction{$option}} &&
2400 dump_option($option) unless $OUT eq \*STDERR;
2405 my ($stem,@list) = @_;
2407 $ENV{"${stem}_n"} = @list;
2408 for $i (0 .. $#list) {
2410 $val =~ s/\\/\\\\/g;
2411 $val =~ s/([\0-\37\177\200-\377])/"\\0x" . unpack('H2',$1)/eg;
2412 $ENV{"${stem}_$i"} = $val;
2419 my $n = delete $ENV{"${stem}_n"};
2421 for $i (0 .. $n - 1) {
2422 $val = delete $ENV{"${stem}_$i"};
2423 $val =~ s/\\((\\)|0x(..))/ $2 ? $2 : pack('H2', $3) /ge;
2431 return; # Put nothing on the stack - malloc/free land!
2435 my($msg)= join("",@_);
2436 $msg .= ": $!\n" unless $msg =~ /\n$/;
2441 my $switch_li = $LINEINFO eq $OUT;
2442 if ($term and $term->Features->{newTTY}) {
2443 ($IN, $OUT) = (shift, shift);
2444 $term->newTTY($IN, $OUT);
2446 &warn("Too late to set IN/OUT filehandles, enabled on next `R'!\n");
2448 ($IN, $OUT) = (shift, shift);
2450 my $o = select $OUT;
2453 $LINEINFO = $OUT if $switch_li;
2457 if (@_ and $term and $term->Features->{newTTY}) {
2458 my ($in, $out) = shift;
2460 ($in, $out) = split /,/, $in, 2;
2464 open IN, $in or die "cannot open `$in' for read: $!";
2465 open OUT, ">$out" or die "cannot open `$out' for write: $!";
2466 reset_IN_OUT(\*IN,\*OUT);
2469 &warn("Too late to set TTY, enabled on next `R'!\n") if $term and @_;
2470 # Useful if done through PERLDB_OPTS:
2471 $console = $tty = shift if @_;
2477 &warn("Too late to set noTTY, enabled on next `R'!\n") if @_;
2479 $notty = shift if @_;
2485 &warn("Too late to set ReadLine, enabled on next `R'!\n") if @_;
2493 &warn("Too late to set RemotePort, enabled on next 'R'!\n") if @_;
2495 $remoteport = shift if @_;
2500 if (${$term->Features}{tkRunning}) {
2501 return $term->tkRunning(@_);
2503 print $OUT "tkRunning not supported by current ReadLine package.\n";
2510 &warn("Too late to set up NonStop mode, enabled on next `R'!\n") if @_;
2512 $runnonstop = shift if @_;
2519 $pager="|".$pager unless $pager =~ /^(\+?\>|\|)/;
2526 $sh = quotemeta shift;
2527 $sh .= "\\b" if $sh =~ /\w$/;
2531 $psh =~ s/\\(.)/$1/g;
2536 if (defined $term) {
2537 local ($warnLevel,$dieLevel) = (0, 1);
2538 return '' unless $term->Features->{ornaments};
2539 eval { $term->ornaments(@_) } || '';
2547 $rc = quotemeta shift;
2548 $rc .= "\\b" if $rc =~ /\w$/;
2552 $prc =~ s/\\(.)/$1/g;
2557 return $lineinfo unless @_;
2559 my $stream = ($lineinfo =~ /^(\+?\>|\|)/) ? $lineinfo : ">$lineinfo";
2560 $slave_editor = ($stream =~ /^\|/);
2561 open(LINEINFO, "$stream") || &warn("Cannot open `$stream' for write");
2562 $LINEINFO = \*LINEINFO;
2563 my $save = select($LINEINFO);
2569 sub list_modules { # versions
2577 s/^Term::ReadLine::readline$/readline/;
2578 if (defined ${ $_ . '::VERSION' }) {
2579 $version{$file} = "${ $_ . '::VERSION' } from ";
2581 $version{$file} .= $INC{$file};
2583 dumpit($OUT,\%version);
2587 # XXX: make sure there are tabs between the command and explanation,
2588 # or print_help will screw up your formatting if you have
2589 # eeevil ornaments enabled. This is an insane mess.
2592 Help is currently only available for the new 580 CommandSet,
2593 if you really want old behaviour, presumably you know what
2597 B<s> [I<expr>] Single step [in I<expr>].
2598 B<n> [I<expr>] Next, steps over subroutine calls [in I<expr>].
2599 <B<CR>> Repeat last B<n> or B<s> command.
2600 B<r> Return from current subroutine.
2601 B<c> [I<line>|I<sub>] Continue; optionally inserts a one-time-only breakpoint
2602 at the specified position.
2603 B<l> I<min>B<+>I<incr> List I<incr>+1 lines starting at I<min>.
2604 B<l> I<min>B<->I<max> List lines I<min> through I<max>.
2605 B<l> I<line> List single I<line>.
2606 B<l> I<subname> List first window of lines from subroutine.
2607 B<l> I<\$var> List first window of lines from subroutine referenced by I<\$var>.
2608 B<l> List next window of lines.
2609 B<-> List previous window of lines.
2610 B<v> [I<line>] View window around I<line>.
2611 B<.> Return to the executed line.
2612 B<f> I<filename> Switch to viewing I<filename>. File must be already loaded.
2613 I<filename> may be either the full name of the file, or a regular
2614 expression matching the full file name:
2615 B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
2616 Evals (with saved bodies) are considered to be filenames:
2617 B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
2618 (in the order of execution).
2619 B</>I<pattern>B</> Search forwards for I<pattern>; final B</> is optional.
2620 B<?>I<pattern>B<?> Search backwards for I<pattern>; final B<?> is optional.
2621 B<L> [I<a|b|w>] List actions and or breakpoints and or watch-expressions.
2622 B<S> [[B<!>]I<pattern>] List subroutine names [not] matching I<pattern>.
2623 B<t> Toggle trace mode.
2624 B<t> I<expr> Trace through execution of I<expr>.
2625 B<b> Sets breakpoint on current line)
2626 B<b> [I<line>] [I<condition>]
2627 Set breakpoint; I<line> defaults to the current execution line;
2628 I<condition> breaks if it evaluates to true, defaults to '1'.
2629 B<b> I<subname> [I<condition>]
2630 Set breakpoint at first line of subroutine.
2631 B<b> I<\$var> Set breakpoint at first line of subroutine referenced by I<\$var>.
2632 B<b> B<load> I<filename> Set breakpoint on 'require'ing the given file.
2633 B<b> B<postpone> I<subname> [I<condition>]
2634 Set breakpoint at first line of subroutine after
2636 B<b> B<compile> I<subname>
2637 Stop after the subroutine is compiled.
2638 B<B> [I<line>] Delete the breakpoint for I<line>.
2639 B<B> I<*> Delete all breakpoints.
2640 B<a> [I<line>] I<command>
2641 Set an action to be done before the I<line> is executed;
2642 I<line> defaults to the current execution line.
2643 Sequence is: check for breakpoint/watchpoint, print line
2644 if necessary, do action, prompt user if necessary,
2647 B<A> [I<line>] Delete the action for I<line>.
2648 B<A> I<*> Delete all actions.
2649 B<w> I<expr> Add a global watch-expression.
2651 B<W> I<expr> Delete a global watch-expression.
2652 B<W> I<*> Delete all watch-expressions.
2653 B<V> [I<pkg> [I<vars>]] List some (default all) variables in package (default current).
2654 Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
2655 B<X> [I<vars>] Same as \"B<V> I<currentpackage> [I<vars>]\".
2656 B<x> I<expr> Evals expression in list context, dumps the result.
2657 B<m> I<expr> Evals expression in list context, prints methods callable
2658 on the first element of the result.
2659 B<m> I<class> Prints methods callable via the given class.
2660 B<M> Show versions of loaded modules.
2662 B<<> ? List Perl commands to run before each prompt.
2663 B<<> I<expr> Define Perl command to run before each prompt.
2664 B<<<> I<expr> Add to the list of Perl commands to run before each prompt.
2665 B<>> ? List Perl commands to run after each prompt.
2666 B<>> I<expr> Define Perl command to run after each prompt.
2667 B<>>B<>> I<expr> Add to the list of Perl commands to run after each prompt.
2668 B<{> I<db_command> Define debugger command to run before each prompt.
2669 B<{> ? List debugger commands to run before each prompt.
2670 B<{{> I<db_command> Add to the list of debugger commands to run before each prompt.
2671 B<$prc> I<number> Redo a previous command (default previous command).
2672 B<$prc> I<-number> Redo number'th-to-last command.
2673 B<$prc> I<pattern> Redo last command that started with I<pattern>.
2674 See 'B<O> I<recallCommand>' too.
2675 B<$psh$psh> I<cmd> Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
2676 . ( $rc eq $sh ? "" : "
2677 B<$psh> [I<cmd>] Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")." ) . "
2678 See 'B<O> I<shellBang>' too.
2679 B<@>I<file> Execute I<file> containing debugger commands (may nest).
2680 B<H> I<-number> Display last number commands (default all).
2681 B<p> I<expr> Same as \"I<print {DB::OUT} expr>\" in current package.
2682 B<|>I<dbcmd> Run debugger command, piping DB::OUT to current pager.
2683 B<||>I<dbcmd> Same as B<|>I<dbcmd> but DB::OUT is temporarilly select()ed as well.
2684 B<\=> [I<alias> I<value>] Define a command alias, or list current aliases.
2685 I<command> Execute as a perl statement in current package.
2686 B<R> Pure-man-restart of debugger, some of debugger state
2687 and command-line options may be lost.
2688 Currently the following settings are preserved:
2689 history, breakpoints and actions, debugger B<O>ptions
2690 and the following command-line options: I<-w>, I<-I>, I<-e>.
2692 B<o> [I<opt>] ... Set boolean option to true
2693 B<o> [I<opt>B<?>] Query options
2694 B<o> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ...
2695 Set options. Use quotes in spaces in value.
2696 I<recallCommand>, I<ShellBang> chars used to recall command or spawn shell;
2697 I<pager> program for output of \"|cmd\";
2698 I<tkRunning> run Tk while prompting (with ReadLine);
2699 I<signalLevel> I<warnLevel> I<dieLevel> level of verbosity;
2700 I<inhibit_exit> Allows stepping off the end of the script.
2701 I<ImmediateStop> Debugger should stop as early as possible.
2702 I<RemotePort> Remote hostname:port for remote debugging
2703 The following options affect what happens with B<V>, B<X>, and B<x> commands:
2704 I<arrayDepth>, I<hashDepth> print only first N elements ('' for all);
2705 I<compactDump>, I<veryCompact> change style of array and hash dump;
2706 I<globPrint> whether to print contents of globs;
2707 I<DumpDBFiles> dump arrays holding debugged files;
2708 I<DumpPackages> dump symbol tables of packages;
2709 I<DumpReused> dump contents of \"reused\" addresses;
2710 I<quote>, I<HighBit>, I<undefPrint> change style of string dump;
2711 I<bareStringify> Do not print the overload-stringified value;
2712 Other options include:
2713 I<PrintRet> affects printing of return value after B<r> command,
2714 I<frame> affects printing messages on subroutine entry/exit.
2715 I<AutoTrace> affects printing messages on possible breaking points.
2716 I<maxTraceLen> gives max length of evals/args listed in stack trace.
2717 I<ornaments> affects screen appearance of the command line.
2718 I<CreateTTY> bits control attempts to create a new TTY on events:
2719 1: on fork() 2: debugger is started inside debugger
2721 During startup options are initialized from \$ENV{PERLDB_OPTS}.
2722 You can put additional initialization options I<TTY>, I<noTTY>,
2723 I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
2724 `B<R>' after you set them).
2726 B<q> or B<^D> Quit. Set B<\$DB::finished = 0> to debug global destruction.
2727 B<h> Summary of debugger commands.
2728 B<h> [I<db_command>] Get help [on a specific debugger command], enter B<|h> to page.
2729 B<h h> Long help for debugger commands
2730 B<$doccmd> I<manpage> Runs the external doc viewer B<$doccmd> command on the
2731 named Perl I<manpage>, or on B<$doccmd> itself if omitted.
2732 Set B<\$DB::doccmd> to change viewer.
2734 Type `|h h' for a paged display if this was too hard to read.
2736 "; # Fix balance of vi % matching: }}}}
2738 # note: tabs in the following section are not-so-helpful
2739 $summary = <<"END_SUM";
2740 I<List/search source lines:> I<Control script execution:>
2741 B<l> [I<ln>|I<sub>] List source code B<T> Stack trace
2742 B<-> or B<.> List previous/current line B<s> [I<expr>] Single step [in expr]
2743 B<v> [I<line>] View around line B<n> [I<expr>] Next, steps over subs
2744 B<f> I<filename> View source in file <B<CR>/B<Enter>> Repeat last B<n> or B<s>
2745 B</>I<pattern>B</> B<?>I<patt>B<?> Search forw/backw B<r> Return from subroutine
2746 B<M> Show module versions B<c> [I<ln>|I<sub>] Continue until position
2747 I<Debugger controls:> B<L> List break/watch/actions
2748 B<o> [...] Set debugger options B<t> [I<expr>] Toggle trace [trace expr]
2749 B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
2750 B<$prc> [I<N>|I<pat>] Redo a previous command B<B> I<ln|*> Delete a/all breakpoints
2751 B<H> [I<-num>] Display last num commands B<a> [I<ln>] I<cmd> Do cmd before line
2752 B<=> [I<a> I<val>] Define/list an alias B<A> I<ln|*> Delete a/all actions
2753 B<h> [I<db_cmd>] Get help on command B<w> I<expr> Add a watch expression
2754 B<h h> Complete help page B<W> I<expr|*> Delete a/all watch expressions
2755 B<|>[B<|>]I<db_cmd> Send output to pager B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
2756 B<q> or B<^D> Quit B<R> Attempt a restart
2757 I<Data Examination:> B<expr> Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
2758 B<x>|B<m> I<expr> Evals expr in list context, dumps the result or lists methods.
2759 B<p> I<expr> Print expression (uses script's current package).
2760 B<S> [[B<!>]I<pat>] List subroutine names [not] matching pattern
2761 B<V> [I<Pk> [I<Vars>]] List Variables in Package. Vars can be ~pattern or !pattern.
2762 B<X> [I<Vars>] Same as \"B<V> I<current_package> [I<Vars>]\".
2763 For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
2765 # ')}}; # Fix balance of vi % matching
2767 # and this is really numb...
2770 B<s> [I<expr>] Single step [in I<expr>].
2771 B<n> [I<expr>] Next, steps over subroutine calls [in I<expr>].
2772 <B<CR>> Repeat last B<n> or B<s> command.
2773 B<r> Return from current subroutine.
2774 B<c> [I<line>|I<sub>] Continue; optionally inserts a one-time-only breakpoint
2775 at the specified position.
2776 B<l> I<min>B<+>I<incr> List I<incr>+1 lines starting at I<min>.
2777 B<l> I<min>B<->I<max> List lines I<min> through I<max>.
2778 B<l> I<line> List single I<line>.
2779 B<l> I<subname> List first window of lines from subroutine.
2780 B<l> I<\$var> List first window of lines from subroutine referenced by I<\$var>.
2781 B<l> List next window of lines.
2782 B<-> List previous window of lines.
2783 B<w> [I<line>] List window around I<line>.
2784 B<.> Return to the executed line.
2785 B<f> I<filename> Switch to viewing I<filename>. File must be already loaded.
2786 I<filename> may be either the full name of the file, or a regular
2787 expression matching the full file name:
2788 B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
2789 Evals (with saved bodies) are considered to be filenames:
2790 B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
2791 (in the order of execution).
2792 B</>I<pattern>B</> Search forwards for I<pattern>; final B</> is optional.
2793 B<?>I<pattern>B<?> Search backwards for I<pattern>; final B<?> is optional.
2794 B<L> List all breakpoints and actions.
2795 B<S> [[B<!>]I<pattern>] List subroutine names [not] matching I<pattern>.
2796 B<t> Toggle trace mode.
2797 B<t> I<expr> Trace through execution of I<expr>.
2798 B<b> [I<line>] [I<condition>]
2799 Set breakpoint; I<line> defaults to the current execution line;
2800 I<condition> breaks if it evaluates to true, defaults to '1'.
2801 B<b> I<subname> [I<condition>]
2802 Set breakpoint at first line of subroutine.
2803 B<b> I<\$var> Set breakpoint at first line of subroutine referenced by I<\$var>.
2804 B<b> B<load> I<filename> Set breakpoint on `require'ing the given file.
2805 B<b> B<postpone> I<subname> [I<condition>]
2806 Set breakpoint at first line of subroutine after
2808 B<b> B<compile> I<subname>
2809 Stop after the subroutine is compiled.
2810 B<d> [I<line>] Delete the breakpoint for I<line>.
2811 B<D> Delete all breakpoints.
2812 B<a> [I<line>] I<command>
2813 Set an action to be done before the I<line> is executed;
2814 I<line> defaults to the current execution line.
2815 Sequence is: check for breakpoint/watchpoint, print line
2816 if necessary, do action, prompt user if necessary,
2818 B<a> [I<line>] Delete the action for I<line>.
2819 B<A> Delete all actions.
2820 B<W> I<expr> Add a global watch-expression.
2821 B<W> Delete all watch-expressions.
2822 B<V> [I<pkg> [I<vars>]] List some (default all) variables in package (default current).
2823 Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
2824 B<X> [I<vars>] Same as \"B<V> I<currentpackage> [I<vars>]\".
2825 B<x> I<expr> Evals expression in list context, dumps the result.
2826 B<m> I<expr> Evals expression in list context, prints methods callable
2827 on the first element of the result.
2828 B<m> I<class> Prints methods callable via the given class.
2830 B<<> ? List Perl commands to run before each prompt.
2831 B<<> I<expr> Define Perl command to run before each prompt.
2832 B<<<> I<expr> Add to the list of Perl commands to run before each prompt.
2833 B<>> ? List Perl commands to run after each prompt.
2834 B<>> I<expr> Define Perl command to run after each prompt.
2835 B<>>B<>> I<expr> Add to the list of Perl commands to run after each prompt.
2836 B<{> I<db_command> Define debugger command to run before each prompt.
2837 B<{> ? List debugger commands to run before each prompt.
2838 B<{{> I<db_command> Add to the list of debugger commands to run before each prompt.
2839 B<$prc> I<number> Redo a previous command (default previous command).
2840 B<$prc> I<-number> Redo number'th-to-last command.
2841 B<$prc> I<pattern> Redo last command that started with I<pattern>.
2842 See 'B<O> I<recallCommand>' too.
2843 B<$psh$psh> I<cmd> Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
2844 . ( $rc eq $sh ? "" : "
2845 B<$psh> [I<cmd>] Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")." ) . "
2846 See 'B<O> I<shellBang>' too.
2847 B<@>I<file> Execute I<file> containing debugger commands (may nest).
2848 B<H> I<-number> Display last number commands (default all).
2849 B<p> I<expr> Same as \"I<print {DB::OUT} expr>\" in current package.
2850 B<|>I<dbcmd> Run debugger command, piping DB::OUT to current pager.
2851 B<||>I<dbcmd> Same as B<|>I<dbcmd> but DB::OUT is temporarilly select()ed as well.
2852 B<\=> [I<alias> I<value>] Define a command alias, or list current aliases.
2853 I<command> Execute as a perl statement in current package.
2854 B<v> Show versions of loaded modules.
2855 B<R> Pure-man-restart of debugger, some of debugger state
2856 and command-line options may be lost.
2857 Currently the following settings are preserved:
2858 history, breakpoints and actions, debugger B<O>ptions
2859 and the following command-line options: I<-w>, I<-I>, I<-e>.
2861 B<O> [I<opt>] ... Set boolean option to true
2862 B<O> [I<opt>B<?>] Query options
2863 B<O> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ...
2864 Set options. Use quotes in spaces in value.
2865 I<recallCommand>, I<ShellBang> chars used to recall command or spawn shell;
2866 I<pager> program for output of \"|cmd\";
2867 I<tkRunning> run Tk while prompting (with ReadLine);
2868 I<signalLevel> I<warnLevel> I<dieLevel> level of verbosity;
2869 I<inhibit_exit> Allows stepping off the end of the script.
2870 I<ImmediateStop> Debugger should stop as early as possible.
2871 I<RemotePort> Remote hostname:port for remote debugging
2872 The following options affect what happens with B<V>, B<X>, and B<x> commands:
2873 I<arrayDepth>, I<hashDepth> print only first N elements ('' for all);
2874 I<compactDump>, I<veryCompact> change style of array and hash dump;
2875 I<globPrint> whether to print contents of globs;
2876 I<DumpDBFiles> dump arrays holding debugged files;
2877 I<DumpPackages> dump symbol tables of packages;
2878 I<DumpReused> dump contents of \"reused\" addresses;
2879 I<quote>, I<HighBit>, I<undefPrint> change style of string dump;
2880 I<bareStringify> Do not print the overload-stringified value;
2881 Other options include:
2882 I<PrintRet> affects printing of return value after B<r> command,
2883 I<frame> affects printing messages on subroutine entry/exit.
2884 I<AutoTrace> affects printing messages on possible breaking points.
2885 I<maxTraceLen> gives max length of evals/args listed in stack trace.
2886 I<ornaments> affects screen appearance of the command line.
2887 I<CreateTTY> bits control attempts to create a new TTY on events:
2888 1: on fork() 2: debugger is started inside debugger
2890 During startup options are initialized from \$ENV{PERLDB_OPTS}.
2891 You can put additional initialization options I<TTY>, I<noTTY>,
2892 I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
2893 `B<R>' after you set them).
2895 B<q> or B<^D> Quit. Set B<\$DB::finished = 0> to debug global destruction.
2896 B<h> [I<db_command>] Get help [on a specific debugger command], enter B<|h> to page.
2897 B<h h> Summary of debugger commands.
2898 B<$doccmd> I<manpage> Runs the external doc viewer B<$doccmd> command on the
2899 named Perl I<manpage>, or on B<$doccmd> itself if omitted.
2900 Set B<\$DB::doccmd> to change viewer.
2902 Type `|h' for a paged display if this was too hard to read.
2904 "; # Fix balance of vi % matching: }}}}
2906 # note: tabs in the following section are not-so-helpful
2907 $pre580_summary = <<"END_SUM";
2908 I<List/search source lines:> I<Control script execution:>
2909 B<l> [I<ln>|I<sub>] List source code B<T> Stack trace
2910 B<-> or B<.> List previous/current line B<s> [I<expr>] Single step [in expr]
2911 B<w> [I<line>] List around line B<n> [I<expr>] Next, steps over subs
2912 B<f> I<filename> View source in file <B<CR>/B<Enter>> Repeat last B<n> or B<s>
2913 B</>I<pattern>B</> B<?>I<patt>B<?> Search forw/backw B<r> Return from subroutine
2914 B<v> Show versions of modules B<c> [I<ln>|I<sub>] Continue until position
2915 I<Debugger controls:> B<L> List break/watch/actions
2916 B<O> [...] Set debugger options B<t> [I<expr>] Toggle trace [trace expr]
2917 B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
2918 B<$prc> [I<N>|I<pat>] Redo a previous command B<d> [I<ln>] or B<D> Delete a/all breakpoints
2919 B<H> [I<-num>] Display last num commands B<a> [I<ln>] I<cmd> Do cmd before line
2920 B<=> [I<a> I<val>] Define/list an alias B<W> I<expr> Add a watch expression
2921 B<h> [I<db_cmd>] Get help on command B<A> or B<W> Delete all actions/watch
2922 B<|>[B<|>]I<db_cmd> Send output to pager B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
2923 B<q> or B<^D> Quit B<R> Attempt a restart
2924 I<Data Examination:> B<expr> Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
2925 B<x>|B<m> I<expr> Evals expr in list context, dumps the result or lists methods.
2926 B<p> I<expr> Print expression (uses script's current package).
2927 B<S> [[B<!>]I<pat>] List subroutine names [not] matching pattern
2928 B<V> [I<Pk> [I<Vars>]] List Variables in Package. Vars can be ~pattern or !pattern.
2929 B<X> [I<Vars>] Same as \"B<V> I<current_package> [I<Vars>]\".
2930 For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
2932 # ')}}; # Fix balance of vi % matching
2939 # Restore proper alignment destroyed by eeevil I<> and B<>
2940 # ornaments: A pox on both their houses!
2942 # A help command will have everything up to and including
2943 # the first tab sequence padded into a field 16 (or if indented 20)
2944 # wide. If it's wider than that, an extra space will be added.
2946 ^ # only matters at start of line
2947 ( \040{4} | \t )* # some subcommands are indented
2948 ( < ? # so <CR> works
2949 [BI] < [^\t\n] + ) # find an eeevil ornament
2950 ( \t+ ) # original separation, discarded
2951 ( .* ) # this will now start (no earlier) than
2954 my($leadwhite, $command, $midwhite, $text) = ($1, $2, $3, $4);
2955 my $clean = $command;
2956 $clean =~ s/[BI]<([^>]*)>/$1/g;
2957 # replace with this whole string:
2958 ($leadwhite ? " " x 4 : "")
2960 . ((" " x (16 + ($leadwhite ? 4 : 0) - length($clean))) || " ")
2965 s{ # handle bold ornaments
2966 B < ( [^>] + | > ) >
2968 $Term::ReadLine::TermCap::rl_term_set[2]
2970 . $Term::ReadLine::TermCap::rl_term_set[3]
2973 s{ # handle italic ornaments
2974 I < ( [^>] + | > ) >
2976 $Term::ReadLine::TermCap::rl_term_set[0]
2978 . $Term::ReadLine::TermCap::rl_term_set[1]
2985 return if defined $ENV{LESS} && $ENV{LESS} =~ /r/;
2986 my $is_less = $pager =~ /\bless\b/;
2987 if ($pager =~ /\bmore\b/) {
2988 my @st_more = stat('/usr/bin/more');
2989 my @st_less = stat('/usr/bin/less');
2990 $is_less = @st_more && @st_less
2991 && $st_more[0] == $st_less[0]
2992 && $st_more[1] == $st_less[1];
2994 # changes environment!
2995 $ENV{LESS} .= 'r' if $is_less;
3001 $SIG{'ABRT'} = 'DEFAULT';
3002 kill 'ABRT', $$ if $panic++;
3003 if (defined &Carp::longmess) {
3004 local $SIG{__WARN__} = '';
3005 local $Carp::CarpLevel = 2; # mydie + confess
3006 &warn(Carp::longmess("Signal @_"));
3009 print $DB::OUT "Got signal @_\n";
3017 local $SIG{__WARN__} = '';
3018 local $SIG{__DIE__} = '';
3019 eval { require Carp } if defined $^S; # If error/warning during compilation,
3020 # require may be broken.
3021 CORE::warn(@_, "\nCannot print stack trace, load with -MCarp option to see stack"),
3022 return unless defined &Carp::longmess;
3023 my ($mysingle,$mytrace) = ($single,$trace);
3024 $single = 0; $trace = 0;
3025 my $mess = Carp::longmess(@_);
3026 ($single,$trace) = ($mysingle,$mytrace);
3033 local $SIG{__DIE__} = '';
3034 local $SIG{__WARN__} = '';
3035 my $i = 0; my $ineval = 0; my $sub;
3036 if ($dieLevel > 2) {
3037 local $SIG{__WARN__} = \&dbwarn;
3038 &warn(@_); # Yell no matter what
3041 if ($dieLevel < 2) {
3042 die @_ if $^S; # in eval propagate
3044 # No need to check $^S, eval is much more robust nowadays
3045 eval { require Carp }; #if defined $^S;# If error/warning during compilation,
3046 # require may be broken.
3048 die(@_, "\nCannot print stack trace, load with -MCarp option to see stack")
3049 unless defined &Carp::longmess;
3051 # We do not want to debug this chunk (automatic disabling works
3052 # inside DB::DB, but not in Carp).
3053 my ($mysingle,$mytrace) = ($single,$trace);
3054 $single = 0; $trace = 0;
3057 package Carp; # Do not include us in the list
3059 $mess = Carp::longmess(@_);
3062 ($single,$trace) = ($mysingle,$mytrace);
3068 $prevwarn = $SIG{__WARN__} unless $warnLevel;
3071 $SIG{__WARN__} = \&DB::dbwarn;
3072 } elsif ($prevwarn) {
3073 $SIG{__WARN__} = $prevwarn;
3081 $prevdie = $SIG{__DIE__} unless $dieLevel;
3084 $SIG{__DIE__} = \&DB::dbdie; # if $dieLevel < 2;
3085 #$SIG{__DIE__} = \&DB::diehard if $dieLevel >= 2;
3086 print $OUT "Stack dump during die enabled",
3087 ( $dieLevel == 1 ? " outside of evals" : ""), ".\n"
3089 print $OUT "Dump printed too.\n" if $dieLevel > 2;
3090 } elsif ($prevdie) {
3091 $SIG{__DIE__} = $prevdie;
3092 print $OUT "Default die handler restored.\n";
3100 $prevsegv = $SIG{SEGV} unless $signalLevel;
3101 $prevbus = $SIG{BUS} unless $signalLevel;
3102 $signalLevel = shift;
3104 $SIG{SEGV} = \&DB::diesignal;
3105 $SIG{BUS} = \&DB::diesignal;
3107 $SIG{SEGV} = $prevsegv;
3108 $SIG{BUS} = $prevbus;
3116 my $name = CvGV_name_or_bust($in);
3117 defined $name ? $name : $in;
3120 sub CvGV_name_or_bust {
3122 return if $skipCvGV; # Backdoor to avoid problems if XS broken...
3123 return unless ref $in;
3124 $in = \&$in; # Hard reference...
3125 eval {require Devel::Peek; 1} or return;
3126 my $gv = Devel::Peek::CvGV($in) or return;
3127 *$gv{PACKAGE} . '::' . *$gv{NAME};
3133 return unless defined &$subr;
3134 my $name = CvGV_name_or_bust($subr);
3136 $data = $sub{$name} if defined $name;
3137 return $data if defined $data;
3140 $subr = \&$subr; # Hard reference
3143 $s = $_, last if $subr eq \&$_;
3151 $class = ref $class if ref $class;
3154 methods_via($class, '', 1);
3155 methods_via('UNIVERSAL', 'UNIVERSAL', 0);
3160 return if $packs{$class}++;
3162 my $prepend = $prefix ? "via $prefix: " : '';
3164 for $name (grep {defined &{${"${class}::"}{$_}}}
3165 sort keys %{"${class}::"}) {
3166 next if $seen{ $name }++;
3167 print $DB::OUT "$prepend$name\n";
3169 return unless shift; # Recurse?
3170 for $name (@{"${class}::ISA"}) {
3171 $prepend = $prefix ? $prefix . " -> $name" : $name;
3172 methods_via($name, $prepend, 1);
3177 $doccmd = $^O !~ /^(?:MSWin32|VMS|os2|dos|amigaos|riscos|MacOS|NetWare)\z/s
3178 ? "man" # O Happy Day!
3179 : "perldoc"; # Alas, poor unfortunates
3185 &system("$doccmd $doccmd");
3188 # this way user can override, like with $doccmd="man -Mwhatever"
3189 # or even just "man " to disable the path check.
3190 unless ($doccmd eq 'man') {
3191 &system("$doccmd $page");
3195 $page = 'perl' if lc($page) eq 'help';
3198 my $man1dir = $Config::Config{'man1dir'};
3199 my $man3dir = $Config::Config{'man3dir'};
3200 for ($man1dir, $man3dir) { s#/[^/]*\z## if /\S/ }
3202 $manpath .= "$man1dir:" if $man1dir =~ /\S/;
3203 $manpath .= "$man3dir:" if $man3dir =~ /\S/ && $man1dir ne $man3dir;
3204 chop $manpath if $manpath;
3205 # harmless if missing, I figure
3206 my $oldpath = $ENV{MANPATH};
3207 $ENV{MANPATH} = $manpath if $manpath;
3208 my $nopathopt = $^O =~ /dunno what goes here/;
3209 if (CORE::system($doccmd,
3210 # I just *know* there are men without -M
3211 (($manpath && !$nopathopt) ? ("-M", $manpath) : ()),
3214 unless ($page =~ /^perl\w/) {
3215 if (grep { $page eq $_ } qw{
3216 5004delta 5005delta amiga api apio book boot bot call compile
3217 cygwin data dbmfilter debug debguts delta diag doc dos dsc embed
3218 faq faq1 faq2 faq3 faq4 faq5 faq6 faq7 faq8 faq9 filter fork
3219 form func guts hack hist hpux intern ipc lexwarn locale lol mod
3220 modinstall modlib number obj op opentut os2 os390 pod port
3221 ref reftut run sec style sub syn thrtut tie toc todo toot tootc
3222 trap unicode var vms win32 xs xstut
3226 CORE::system($doccmd,
3227 (($manpath && !$nopathopt) ? ("-M", $manpath) : ()),
3232 if (defined $oldpath) {
3233 $ENV{MANPATH} = $manpath;
3235 delete $ENV{MANPATH};
3239 # The following BEGIN is very handy if debugger goes havoc, debugging debugger?
3241 BEGIN { # This does not compile, alas.
3242 $IN = \*STDIN; # For bugs before DB::OUT has been opened
3243 $OUT = \*STDERR; # For errors before DB::OUT has been opened
3247 $deep = 100; # warning if stack gets this deep
3251 $SIG{INT} = \&DB::catch;
3252 # This may be enabled to debug debugger:
3253 #$warnLevel = 1 unless defined $warnLevel;
3254 #$dieLevel = 1 unless defined $dieLevel;
3255 #$signalLevel = 1 unless defined $signalLevel;
3257 $db_stop = 0; # Compiler warning
3259 $level = 0; # Level of recursive debugging
3260 # @stack and $doret are needed in sub sub, which is called for DB::postponed.
3261 # Triggers bug (?) in perl is we postpone this until runtime:
3262 @postponed = @stack = (0);
3263 $stack_depth = 0; # Localized $#stack
3268 BEGIN {$^W = $ini_warn;} # Switch warnings back
3270 #use Carp; # This did break, left for debugging
3273 # Specific code for b c l V m f O, &blah, $blah, @blah, %blah
3274 my($text, $line, $start) = @_;
3275 my ($itext, $search, $prefix, $pack) =
3276 ($text, "^\Q${'package'}::\E([^:]+)\$");
3278 return sort grep /^\Q$text/, (keys %sub), qw(postpone load compile), # subroutines
3279 (map { /$search/ ? ($1) : () } keys %sub)
3280 if (substr $line, 0, $start) =~ /^\|*[blc]\s+((postpone|compile)\s+)?$/;
3281 return sort grep /^\Q$text/, values %INC # files
3282 if (substr $line, 0, $start) =~ /^\|*b\s+load\s+$/;
3283 return sort map {($_, db_complete($_ . "::", "V ", 2))}
3284 grep /^\Q$text/, map { /^(.*)::$/ ? ($1) : ()} keys %:: # top-packages
3285 if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/ and $text =~ /^\w*$/;
3286 return sort map {($_, db_complete($_ . "::", "V ", 2))}
3288 grep /^\Q$text/, map { /^(.*)::$/ ? ($prefix . "::$1") : ()} keys %{$prefix . '::'}
3290 if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/
3291 and $text =~ /^(.*[^:])::?(\w*)$/ and $prefix = $1;
3292 if ( $line =~ /^\|*f\s+(.*)/ ) { # Loaded files
3293 # We may want to complete to (eval 9), so $text may be wrong
3294 $prefix = length($1) - length($text);
3297 map {substr $_, 2 + $prefix} grep /^_<\Q$text/, (keys %main::), $0
3299 if ((substr $text, 0, 1) eq '&') { # subroutines
3300 $text = substr $text, 1;
3302 return sort map "$prefix$_",
3305 (map { /$search/ ? ($1) : () }
3308 if ($text =~ /^[\$@%](.*)::(.*)/) { # symbols in a package
3309 $pack = ($1 eq 'main' ? '' : $1) . '::';
3310 $prefix = (substr $text, 0, 1) . $1 . '::';
3313 = map "$prefix$_", grep /^\Q$text/, grep /^_?[a-zA-Z]/, keys %$pack ;
3314 if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
3315 return db_complete($out[0], $line, $start);
3319 if ($text =~ /^[\$@%]/) { # symbols (in $package + packages in main)
3320 $pack = ($package eq 'main' ? '' : $package) . '::';
3321 $prefix = substr $text, 0, 1;
3322 $text = substr $text, 1;
3323 my @out = map "$prefix$_", grep /^\Q$text/,
3324 (grep /^_?[a-zA-Z]/, keys %$pack),
3325 ( $pack eq '::' ? () : (grep /::$/, keys %::) ) ;
3326 if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
3327 return db_complete($out[0], $line, $start);
3331 if ((substr $line, 0, $start) =~ /^\|*O\b.*\s$/) { # Options after a space
3332 my @out = grep /^\Q$text/, @options;
3333 my $val = option_val($out[0], undef);
3335 if (not defined $val or $val =~ /[\n\r]/) {
3336 # Can do nothing better
3337 } elsif ($val =~ /\s/) {
3339 foreach $l (split //, qq/\"\'\#\|/) {
3340 $out = "$l$val$l ", last if (index $val, $l) == -1;
3345 # Default to value if one completion, to question if many
3346 $rl_attribs->{completer_terminator_character} = (@out == 1 ? $out : '? ');
3349 return $term->filename_list($text); # filenames
3353 print $OUT "Use `q' to quit or `R' to restart. `h q' for details.\n"
3357 if (defined($ini_pids)) {
3358 $ENV{PERLDB_PIDS} = $ini_pids;
3360 delete($ENV{PERLDB_PIDS});
3365 $finished = 1 if $inhibit_exit; # So that some keys may be disabled.
3366 $fall_off_end = 1 unless $inhibit_exit;
3367 # Do not stop in at_exit() and destructors on exit:
3368 $DB::single = !$fall_off_end && !$runnonstop;
3369 DB::fake::at_exit() unless $fall_off_end or $runnonstop;
3373 # ===================================== pre580 ================================
3374 # this is very sad below here...
3377 sub cmd_pre580_null {
3383 if ($cmd =~ /^(\d*)\s*(.*)/) {
3384 $i = $1 || $line; $j = $2;
3386 if ($dbline[$i] == 0) {
3387 print $OUT "Line $i may not have an action.\n";
3389 $had_breakpoints{$filename} |= 2;
3390 $dbline{$i} =~ s/\0[^\0]*//;
3391 $dbline{$i} .= "\0" . action($j);
3394 $dbline{$i} =~ s/\0[^\0]*//;
3395 delete $dbline{$i} if $dbline{$i} eq '';
3403 if ($cmd =~ /^load\b\s*(.*)/) {
3404 my $file = $1; $file =~ s/\s+$//;
3406 } elsif ($cmd =~ /^(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/) {
3407 my $cond = length $3 ? $3 : '1';
3408 my ($subname, $break) = ($2, $1 eq 'postpone');
3409 $subname =~ s/\'/::/g;
3410 $subname = "${'package'}::" . $subname
3411 unless $subname =~ /::/;
3412 $subname = "main".$subname if substr($subname,0,2) eq "::";
3413 $postponed{$subname} = $break ? "break +0 if $cond" : "compile";
3414 } elsif ($cmd =~ /^([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/) {
3416 my $cond = length $2 ? $2 : '1';
3417 &cmd_b_sub($subname, $cond);
3418 } elsif ($cmd =~ /^(\d*)\s*(.*)/) {
3419 my $i = $1 || $dbline;
3420 my $cond = length $2 ? $2 : '1';
3421 &cmd_b_line($i, $cond);
3427 if ($cmd =~ /^\s*$/) {
3428 print $OUT "Deleting all breakpoints...\n";
3430 for $file (keys %had_breakpoints) {
3431 local *dbline = $main::{'_<' . $file};
3435 for ($i = 1; $i <= $max ; $i++) {
3436 if (defined $dbline{$i}) {
3437 $dbline{$i} =~ s/^[^\0]+//;
3438 if ($dbline{$i} =~ s/^\0?$//) {
3444 if (not $had_breakpoints{$file} &= ~1) {
3445 delete $had_breakpoints{$file};
3449 undef %postponed_file;
3450 undef %break_on_load;
3456 if ($cmd =~ /^\s*$/) {
3457 print_help($pre580_help);
3458 } elsif ($cmd =~ /^h\s*/) {
3459 print_help($pre580_summary);
3460 } elsif ($cmd =~ /^h\s+(\S.*)$/) {
3461 my $asked = $1; # for proper errmsg
3462 my $qasked = quotemeta($asked); # for searching
3463 # XXX: finds CR but not <CR>
3464 if ($pre580_help =~ /^<?(?:[IB]<)$qasked/m) {
3465 while ($pre580_help =~ /^(<?(?:[IB]<)$qasked([\s\S]*?)\n)(?!\s)/mg) {
3469 print_help("B<$asked> is not a debugger command.\n");
3478 @to_watch = @old_watch = ();
3479 } elsif ($cmd =~ /^(.*)/s) {
3483 $val = (defined $val) ? "'$val'" : 'undef' ;
3484 push @old_watch, $val;
3492 "Debugged program terminated. Use `q' to quit or `R' to restart.";
3495 package DB; # Do not trace this 1; below!