xref: /openbsd-src/gnu/usr.bin/perl/lib/perl5db.pl (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1
2=head1 NAME
3
4perl5db.pl - the perl debugger
5
6=head1 SYNOPSIS
7
8    perl -d  your_Perl_script
9
10=head1 DESCRIPTION
11
12C<perl5db.pl> is the perl debugger. It is loaded automatically by Perl when
13you invoke a script with C<perl -d>. This documentation tries to outline the
14structure and services provided by C<perl5db.pl>, and to describe how you
15can use them.
16
17=head1 GENERAL NOTES
18
19The debugger can look pretty forbidding to many Perl programmers. There are
20a number of reasons for this, many stemming out of the debugger's history.
21
22When the debugger was first written, Perl didn't have a lot of its nicer
23features - no references, no lexical variables, no closures, no object-oriented
24programming. So a lot of the things one would normally have done using such
25features was done using global variables, globs and the C<local()> operator
26in creative ways.
27
28Some of these have survived into the current debugger; a few of the more
29interesting and still-useful idioms are noted in this section, along with notes
30on the comments themselves.
31
32=head2 Why not use more lexicals?
33
34Experienced Perl programmers will note that the debugger code tends to use
35mostly package globals rather than lexically-scoped variables. This is done
36to allow a significant amount of control of the debugger from outside the
37debugger itself.
38
39Unfortunately, though the variables are accessible, they're not well
40documented, so it's generally been a decision that hasn't made a lot of
41difference to most users. Where appropriate, comments have been added to
42make variables more accessible and usable, with the understanding that these
43I<are> debugger internals, and are therefore subject to change. Future
44development should probably attempt to replace the globals with a well-defined
45API, but for now, the variables are what we've got.
46
47=head2 Automated variable stacking via C<local()>
48
49As you may recall from reading C<perlfunc>, the C<local()> operator makes a
50temporary copy of a variable in the current scope. When the scope ends, the
51old copy is restored. This is often used in the debugger to handle the
52automatic stacking of variables during recursive calls:
53
54     sub foo {
55        local $some_global++;
56
57        # Do some stuff, then ...
58        return;
59     }
60
61What happens is that on entry to the subroutine, C<$some_global> is localized,
62then altered. When the subroutine returns, Perl automatically undoes the
63localization, restoring the previous value. Voila, automatic stack management.
64
65The debugger uses this trick a I<lot>. Of particular note is C<DB::eval>,
66which lets the debugger get control inside of C<eval>'ed code. The debugger
67localizes a saved copy of C<$@> inside the subroutine, which allows it to
68keep C<$@> safe until it C<DB::eval> returns, at which point the previous
69value of C<$@> is restored. This makes it simple (well, I<simpler>) to keep
70track of C<$@> inside C<eval>s which C<eval> other C<eval's>.
71
72In any case, watch for this pattern. It occurs fairly often.
73
74=head2 The C<^> trick
75
76This is used to cleverly reverse the sense of a logical test depending on
77the value of an auxiliary variable. For instance, the debugger's C<S>
78(search for subroutines by pattern) allows you to negate the pattern
79like this:
80
81   # Find all non-'foo' subs:
82   S !/foo/
83
84Boolean algebra states that the truth table for XOR looks like this:
85
86=over 4
87
88=item * 0 ^ 0 = 0
89
90(! not present and no match) --> false, don't print
91
92=item * 0 ^ 1 = 1
93
94(! not present and matches) --> true, print
95
96=item * 1 ^ 0 = 1
97
98(! present and no match) --> true, print
99
100=item * 1 ^ 1 = 0
101
102(! present and matches) --> false, don't print
103
104=back
105
106As you can see, the first pair applies when C<!> isn't supplied, and
107the second pair applies when it is. The XOR simply allows us to
108compact a more complicated if-then-elseif-else into a more elegant
109(but perhaps overly clever) single test. After all, it needed this
110explanation...
111
112=head2 FLAGS, FLAGS, FLAGS
113
114There is a certain C programming legacy in the debugger. Some variables,
115such as C<$single>, C<$trace>, and C<$frame>, have I<magical> values composed
116of 1, 2, 4, etc. (powers of 2) OR'ed together. This allows several pieces
117of state to be stored independently in a single scalar.
118
119A test like
120
121    if ($scalar & 4) ...
122
123is checking to see if the appropriate bit is on. Since each bit can be
124"addressed" independently in this way, C<$scalar> is acting sort of like
125an array of bits. Obviously, since the contents of C<$scalar> are just a
126bit-pattern, we can save and restore it easily (it will just look like
127a number).
128
129The problem, is of course, that this tends to leave magic numbers scattered
130all over your program whenever a bit is set, cleared, or checked. So why do
131it?
132
133=over 4
134
135=item *
136
137First, doing an arithmetical or bitwise operation on a scalar is
138just about the fastest thing you can do in Perl: C<use constant> actually
139creates a subroutine call, and array and hash lookups are much slower. Is
140this over-optimization at the expense of readability? Possibly, but the
141debugger accesses these  variables a I<lot>. Any rewrite of the code will
142probably have to benchmark alternate implementations and see which is the
143best balance of readability and speed, and then document how it actually
144works.
145
146=item *
147
148Second, it's very easy to serialize a scalar number. This is done in
149the restart code; the debugger state variables are saved in C<%ENV> and then
150restored when the debugger is restarted. Having them be just numbers makes
151this trivial.
152
153=item *
154
155Third, some of these variables are being shared with the Perl core
156smack in the middle of the interpreter's execution loop. It's much faster for
157a C program (like the interpreter) to check a bit in a scalar than to access
158several different variables (or a Perl array).
159
160=back
161
162=head2 What are those C<XXX> comments for?
163
164Any comment containing C<XXX> means that the comment is either somewhat
165speculative - it's not exactly clear what a given variable or chunk of
166code is doing, or that it is incomplete - the basics may be clear, but the
167subtleties are not completely documented.
168
169Send in a patch if you can clear up, fill out, or clarify an C<XXX>.
170
171=head1 DATA STRUCTURES MAINTAINED BY CORE
172
173There are a number of special data structures provided to the debugger by
174the Perl interpreter.
175
176The array C<@{$main::{'_<'.$filename}}> (aliased locally to C<@dbline>
177via glob assignment) contains the text from C<$filename>, with each
178element corresponding to a single line of C<$filename>. Additionally,
179breakable lines will be dualvars with the numeric component being the
180memory address of a COP node. Non-breakable lines are dualvar to 0.
181
182The hash C<%{'_<'.$filename}> (aliased locally to C<%dbline> via glob
183assignment) contains breakpoints and actions.  The keys are line numbers;
184you can set individual values, but not the whole hash. The Perl interpreter
185uses this hash to determine where breakpoints have been set. Any true value is
186considered to be a breakpoint; C<perl5db.pl> uses C<$break_condition\0$action>.
187Values are magical in numeric context: 1 if the line is breakable, 0 if not.
188
189The scalar C<${"_<$filename"}> simply contains the string C<$filename>.
190This is also the case for evaluated strings that contain subroutines, or
191which are currently being executed.  The $filename for C<eval>ed strings looks
192like C<(eval 34).
193
194=head1 DEBUGGER STARTUP
195
196When C<perl5db.pl> starts, it reads an rcfile (C<perl5db.ini> for
197non-interactive sessions, C<.perldb> for interactive ones) that can set a number
198of options. In addition, this file may define a subroutine C<&afterinit>
199that will be executed (in the debugger's context) after the debugger has
200initialized itself.
201
202Next, it checks the C<PERLDB_OPTS> environment variable and treats its
203contents as the argument of a C<o> command in the debugger.
204
205=head2 STARTUP-ONLY OPTIONS
206
207The following options can only be specified at startup.
208To set them in your rcfile, add a call to
209C<&parse_options("optionName=new_value")>.
210
211=over 4
212
213=item * TTY
214
215the TTY to use for debugging i/o.
216
217=item * noTTY
218
219if set, goes in NonStop mode.  On interrupt, if TTY is not set,
220uses the value of noTTY or F<$HOME/.perldbtty$$> to find TTY using
221Term::Rendezvous.  Current variant is to have the name of TTY in this
222file.
223
224=item * ReadLine
225
226if false, a dummy ReadLine is used, so you can debug
227ReadLine applications.
228
229=item * NonStop
230
231if true, no i/o is performed until interrupt.
232
233=item * LineInfo
234
235file or pipe to print line number info to.  If it is a
236pipe, a short "emacs like" message is used.
237
238=item * RemotePort
239
240host:port to connect to on remote host for remote debugging.
241
242=item * HistFile
243
244file to store session history to. There is no default and so no
245history file is written unless this variable is explicitly set.
246
247=item * HistSize
248
249number of commands to store to the file specified in C<HistFile>.
250Default is 100.
251
252=back
253
254=head3 SAMPLE RCFILE
255
256 &parse_options("NonStop=1 LineInfo=db.out");
257  sub afterinit { $trace = 1; }
258
259The script will run without human intervention, putting trace
260information into C<db.out>.  (If you interrupt it, you had better
261reset C<LineInfo> to something I<interactive>!)
262
263=head1 INTERNALS DESCRIPTION
264
265=head2 DEBUGGER INTERFACE VARIABLES
266
267Perl supplies the values for C<%sub>.  It effectively inserts
268a C<&DB::DB();> in front of each place that can have a
269breakpoint. At each subroutine call, it calls C<&DB::sub> with
270C<$DB::sub> set to the called subroutine. It also inserts a C<BEGIN
271{require 'perl5db.pl'}> before the first line.
272
273After each C<require>d file is compiled, but before it is executed, a
274call to C<&DB::postponed($main::{'_<'.$filename})> is done. C<$filename>
275is the expanded name of the C<require>d file (as found via C<%INC>).
276
277=head3 IMPORTANT INTERNAL VARIABLES
278
279=head4 C<$CreateTTY>
280
281Used to control when the debugger will attempt to acquire another TTY to be
282used for input.
283
284=over
285
286=item * 1 -  on C<fork()>
287
288=item * 2 - debugger is started inside debugger
289
290=item * 4 -  on startup
291
292=back
293
294=head4 C<$doret>
295
296The value -2 indicates that no return value should be printed.
297Any other positive value causes C<DB::sub> to print return values.
298
299=head4 C<$evalarg>
300
301The item to be eval'ed by C<DB::eval>. Used to prevent messing with the current
302contents of C<@_> when C<DB::eval> is called.
303
304=head4 C<$frame>
305
306Determines what messages (if any) will get printed when a subroutine (or eval)
307is entered or exited.
308
309=over 4
310
311=item * 0 -  No enter/exit messages
312
313=item * 1 - Print I<entering> messages on subroutine entry
314
315=item * 2 - Adds exit messages on subroutine exit. If no other flag is on, acts like 1+2.
316
317=item * 4 - Extended messages: C<< <in|out> I<context>=I<fully-qualified sub name> from I<file>:I<line> >>. If no other flag is on, acts like 1+4.
318
319=item * 8 - Adds parameter information to messages, and overloaded stringify and tied FETCH is enabled on the printed arguments. Ignored if C<4> is not on.
320
321=item * 16 - Adds C<I<context> return from I<subname>: I<value>> messages on subroutine/eval exit. Ignored if C<4> is not on.
322
323=back
324
325To get everything, use C<$frame=30> (or C<o f=30> as a debugger command).
326The debugger internally juggles the value of C<$frame> during execution to
327protect external modules that the debugger uses from getting traced.
328
329=head4 C<$level>
330
331Tracks current debugger nesting level. Used to figure out how many
332C<E<lt>E<gt>> pairs to surround the line number with when the debugger
333outputs a prompt. Also used to help determine if the program has finished
334during command parsing.
335
336=head4 C<$onetimeDump>
337
338Controls what (if anything) C<DB::eval()> will print after evaluating an
339expression.
340
341=over 4
342
343=item * C<undef> - don't print anything
344
345=item * C<dump> - use C<dumpvar.pl> to display the value returned
346
347=item * C<methods> - print the methods callable on the first item returned
348
349=back
350
351=head4 C<$onetimeDumpDepth>
352
353Controls how far down C<dumpvar.pl> will go before printing C<...> while
354dumping a structure. Numeric. If C<undef>, print all levels.
355
356=head4 C<$signal>
357
358Used to track whether or not an C<INT> signal has been detected. C<DB::DB()>,
359which is called before every statement, checks this and puts the user into
360command mode if it finds C<$signal> set to a true value.
361
362=head4 C<$single>
363
364Controls behavior during single-stepping. Stacked in C<@stack> on entry to
365each subroutine; popped again at the end of each subroutine.
366
367=over 4
368
369=item * 0 - run continuously.
370
371=item * 1 - single-step, go into subs. The C<s> command.
372
373=item * 2 - single-step, don't go into subs. The C<n> command.
374
375=item * 4 - print current sub depth (turned on to force this when C<too much
376recursion> occurs.
377
378=back
379
380=head4 C<$trace>
381
382Controls the output of trace information.
383
384=over 4
385
386=item * 1 - The C<t> command was entered to turn on tracing (every line executed is printed)
387
388=item * 2 - watch expressions are active
389
390=item * 4 - user defined a C<watchfunction()> in C<afterinit()>
391
392=back
393
394=head4 C<$slave_editor>
395
3961 if C<LINEINFO> was directed to a pipe; 0 otherwise.
397
398=head4 C<@cmdfhs>
399
400Stack of filehandles that C<DB::readline()> will read commands from.
401Manipulated by the debugger's C<source> command and C<DB::readline()> itself.
402
403=head4 C<@dbline>
404
405Local alias to the magical line array, C<@{$main::{'_<'.$filename}}> ,
406supplied by the Perl interpreter to the debugger. Contains the source.
407
408=head4 C<@old_watch>
409
410Previous values of watch expressions. First set when the expression is
411entered; reset whenever the watch expression changes.
412
413=head4 C<@saved>
414
415Saves important globals (C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, C<$^W>)
416so that the debugger can substitute safe values while it's running, and
417restore them when it returns control.
418
419=head4 C<@stack>
420
421Saves the current value of C<$single> on entry to a subroutine.
422Manipulated by the C<c> command to turn off tracing in all subs above the
423current one.
424
425=head4 C<@to_watch>
426
427The 'watch' expressions: to be evaluated before each line is executed.
428
429=head4 C<@typeahead>
430
431The typeahead buffer, used by C<DB::readline>.
432
433=head4 C<%alias>
434
435Command aliases. Stored as character strings to be substituted for a command
436entered.
437
438=head4 C<%break_on_load>
439
440Keys are file names, values are 1 (break when this file is loaded) or undef
441(don't break when it is loaded).
442
443=head4 C<%dbline>
444
445Keys are line numbers, values are C<condition\0action>. If used in numeric
446context, values are 0 if not breakable, 1 if breakable, no matter what is
447in the actual hash entry.
448
449=head4 C<%had_breakpoints>
450
451Keys are file names; values are bitfields:
452
453=over 4
454
455=item * 1 - file has a breakpoint in it.
456
457=item * 2 - file has an action in it.
458
459=back
460
461A zero or undefined value means this file has neither.
462
463=head4 C<%option>
464
465Stores the debugger options. These are character string values.
466
467=head4 C<%postponed>
468
469Saves breakpoints for code that hasn't been compiled yet.
470Keys are subroutine names, values are:
471
472=over 4
473
474=item * C<compile> - break when this sub is compiled
475
476=item * C<< break +0 if <condition> >> - break (conditionally) at the start of this routine. The condition will be '1' if no condition was specified.
477
478=back
479
480=head4 C<%postponed_file>
481
482This hash keeps track of breakpoints that need to be set for files that have
483not yet been compiled. Keys are filenames; values are references to hashes.
484Each of these hashes is keyed by line number, and its values are breakpoint
485definitions (C<condition\0action>).
486
487=head1 DEBUGGER INITIALIZATION
488
489The debugger's initialization actually jumps all over the place inside this
490package. This is because there are several BEGIN blocks (which of course
491execute immediately) spread through the code. Why is that?
492
493The debugger needs to be able to change some things and set some things up
494before the debugger code is compiled; most notably, the C<$deep> variable that
495C<DB::sub> uses to tell when a program has recursed deeply. In addition, the
496debugger has to turn off warnings while the debugger code is compiled, but then
497restore them to their original setting before the program being debugged begins
498executing.
499
500The first C<BEGIN> block simply turns off warnings by saving the current
501setting of C<$^W> and then setting it to zero. The second one initializes
502the debugger variables that are needed before the debugger begins executing.
503The third one puts C<$^X> back to its former value.
504
505We'll detail the second C<BEGIN> block later; just remember that if you need
506to initialize something before the debugger starts really executing, that's
507where it has to go.
508
509=cut
510
511package DB;
512
513use strict;
514
515BEGIN {eval 'use IO::Handle'}; # Needed for flush only? breaks under miniperl
516
517BEGIN {
518    require feature;
519    $^V =~ /^v(\d+\.\d+)/;
520    feature->import(":$1");
521}
522
523# Debugger for Perl 5.00x; perl5db.pl patch level:
524use vars qw($VERSION $header);
525
526$VERSION = '1.44_02';
527
528$header = "perl5db.pl version $VERSION";
529
530=head1 DEBUGGER ROUTINES
531
532=head2 C<DB::eval()>
533
534This function replaces straight C<eval()> inside the debugger; it simplifies
535the process of evaluating code in the user's context.
536
537The code to be evaluated is passed via the package global variable
538C<$DB::evalarg>; this is done to avoid fiddling with the contents of C<@_>.
539
540Before we do the C<eval()>, we preserve the current settings of C<$trace>,
541C<$single>, C<$^D> and C<$usercontext>.  The latter contains the
542preserved values of C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, C<$^W> and the
543user's current package, grabbed when C<DB::DB> got control.  This causes the
544proper context to be used when the eval is actually done.  Afterward, we
545restore C<$trace>, C<$single>, and C<$^D>.
546
547Next we need to handle C<$@> without getting confused. We save C<$@> in a
548local lexical, localize C<$saved[0]> (which is where C<save()> will put
549C<$@>), and then call C<save()> to capture C<$@>, C<$!>, C<$^E>, C<$,>,
550C<$/>, C<$\>, and C<$^W>) and set C<$,>, C<$/>, C<$\>, and C<$^W> to values
551considered sane by the debugger. If there was an C<eval()> error, we print
552it on the debugger's output. If C<$onetimedump> is defined, we call
553C<dumpit> if it's set to 'dump', or C<methods> if it's set to
554'methods'. Setting it to something else causes the debugger to do the eval
555but not print the result - handy if you want to do something else with it
556(the "watch expressions" code does this to get the value of the watch
557expression but not show it unless it matters).
558
559In any case, we then return the list of output from C<eval> to the caller,
560and unwinding restores the former version of C<$@> in C<@saved> as well
561(the localization of C<$saved[0]> goes away at the end of this scope).
562
563=head3 Parameters and variables influencing execution of DB::eval()
564
565C<DB::eval> isn't parameterized in the standard way; this is to keep the
566debugger's calls to C<DB::eval()> from mucking with C<@_>, among other things.
567The variables listed below influence C<DB::eval()>'s execution directly.
568
569=over 4
570
571=item C<$evalarg> - the thing to actually be eval'ed
572
573=item C<$trace> - Current state of execution tracing
574
575=item C<$single> - Current state of single-stepping
576
577=item C<$onetimeDump> - what is to be displayed after the evaluation
578
579=item C<$onetimeDumpDepth> - how deep C<dumpit()> should go when dumping results
580
581=back
582
583The following variables are altered by C<DB::eval()> during its execution. They
584are "stacked" via C<local()>, enabling recursive calls to C<DB::eval()>.
585
586=over 4
587
588=item C<@res> - used to capture output from actual C<eval>.
589
590=item C<$otrace> - saved value of C<$trace>.
591
592=item C<$osingle> - saved value of C<$single>.
593
594=item C<$od> - saved value of C<$^D>.
595
596=item C<$saved[0]> - saved value of C<$@>.
597
598=item $\ - for output of C<$@> if there is an evaluation error.
599
600=back
601
602=head3 The problem of lexicals
603
604The context of C<DB::eval()> presents us with some problems. Obviously,
605we want to be 'sandboxed' away from the debugger's internals when we do
606the eval, but we need some way to control how punctuation variables and
607debugger globals are used.
608
609We can't use local, because the code inside C<DB::eval> can see localized
610variables; and we can't use C<my> either for the same reason. The code
611in this routine compromises and uses C<my>.
612
613After this routine is over, we don't have user code executing in the debugger's
614context, so we can use C<my> freely.
615
616=cut
617
618############################################## Begin lexical danger zone
619
620# 'my' variables used here could leak into (that is, be visible in)
621# the context that the code being evaluated is executing in. This means that
622# the code could modify the debugger's variables.
623#
624# Fiddling with the debugger's context could be Bad. We insulate things as
625# much as we can.
626
627use vars qw(
628    @args
629    %break_on_load
630    $CommandSet
631    $CreateTTY
632    $DBGR
633    @dbline
634    $dbline
635    %dbline
636    $dieLevel
637    $filename
638    $histfile
639    $histsize
640    $IN
641    $inhibit_exit
642    @ini_INC
643    $ini_warn
644    $maxtrace
645    $od
646    @options
647    $osingle
648    $otrace
649    $pager
650    $post
651    %postponed
652    $prc
653    $pre
654    $pretype
655    $psh
656    @RememberOnROptions
657    $remoteport
658    @res
659    $rl
660    @saved
661    $signalLevel
662    $sub
663    $term
664    $usercontext
665    $warnLevel
666);
667
668our (
669    @cmdfhs,
670    $evalarg,
671    $frame,
672    $hist,
673    $ImmediateStop,
674    $line,
675    $onetimeDump,
676    $onetimedumpDepth,
677    %option,
678    $OUT,
679    $packname,
680    $signal,
681    $single,
682    $start,
683    %sub,
684    $subname,
685    $trace,
686    $window,
687);
688
689# Used to save @ARGV and extract any debugger-related flags.
690use vars qw(@ARGS);
691
692# Used to prevent multiple entries to diesignal()
693# (if for instance diesignal() itself dies)
694use vars qw($panic);
695
696# Used to prevent the debugger from running nonstop
697# after a restart
698our ($second_time);
699
700sub _calc_usercontext {
701    my ($package) = @_;
702
703    # Cancel strict completely for the evaluated code, so the code
704    # the user evaluates won't be affected by it. (Shlomi Fish)
705    return 'no strict; ($@, $!, $^E, $,, $/, $\, $^W) = @DB::saved;'
706    . "package $package;";    # this won't let them modify, alas
707}
708
709sub eval {
710
711    # 'my' would make it visible from user code
712    #    but so does local! --tchrist
713    # Remember: this localizes @DB::res, not @main::res.
714    local @res;
715    {
716
717        # Try to keep the user code from messing  with us. Save these so that
718        # even if the eval'ed code changes them, we can put them back again.
719        # Needed because the user could refer directly to the debugger's
720        # package globals (and any 'my' variables in this containing scope)
721        # inside the eval(), and we want to try to stay safe.
722        local $otrace  = $trace;
723        local $osingle = $single;
724        local $od      = $^D;
725
726        # Untaint the incoming eval() argument.
727        { ($evalarg) = $evalarg =~ /(.*)/s; }
728
729        # $usercontext built in DB::DB near the comment
730        # "set up the context for DB::eval ..."
731        # Evaluate and save any results.
732        @res = eval "$usercontext $evalarg;\n";  # '\n' for nice recursive debug
733
734        # Restore those old values.
735        $trace  = $otrace;
736        $single = $osingle;
737        $^D     = $od;
738    }
739
740    # Save the current value of $@, and preserve it in the debugger's copy
741    # of the saved precious globals.
742    my $at = $@;
743
744    # Since we're only saving $@, we only have to localize the array element
745    # that it will be stored in.
746    local $saved[0];    # Preserve the old value of $@
747    eval { &DB::save };
748
749    # Now see whether we need to report an error back to the user.
750    if ($at) {
751        local $\ = '';
752        print $OUT $at;
753    }
754
755    # Display as required by the caller. $onetimeDump and $onetimedumpDepth
756    # are package globals.
757    elsif ($onetimeDump) {
758        if ( $onetimeDump eq 'dump' ) {
759            local $option{dumpDepth} = $onetimedumpDepth
760              if defined $onetimedumpDepth;
761            dumpit( $OUT, \@res );
762        }
763        elsif ( $onetimeDump eq 'methods' ) {
764            methods( $res[0] );
765        }
766    } ## end elsif ($onetimeDump)
767    @res;
768} ## end sub eval
769
770############################################## End lexical danger zone
771
772# After this point it is safe to introduce lexicals.
773# The code being debugged will be executing in its own context, and
774# can't see the inside of the debugger.
775#
776# However, one should not overdo it: leave as much control from outside as
777# possible. If you make something a lexical, it's not going to be addressable
778# from outside the debugger even if you know its name.
779
780# This file is automatically included if you do perl -d.
781# It's probably not useful to include this yourself.
782#
783# Before venturing further into these twisty passages, it is
784# wise to read the perldebguts man page or risk the ire of dragons.
785#
786# (It should be noted that perldebguts will tell you a lot about
787# the underlying mechanics of how the debugger interfaces into the
788# Perl interpreter, but not a lot about the debugger itself. The new
789# comments in this code try to address this problem.)
790
791# Note that no subroutine call is possible until &DB::sub is defined
792# (for subroutines defined outside of the package DB). In fact the same is
793# true if $deep is not defined.
794
795# Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich)
796
797# modified Perl debugger, to be run from Emacs in perldb-mode
798# Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990
799# Johan Vromans -- upgrade to 4.0 pl 10
800# Ilya Zakharevich -- patches after 5.001 (and some before ;-)
801########################################################################
802
803=head1 DEBUGGER INITIALIZATION
804
805The debugger starts up in phases.
806
807=head2 BASIC SETUP
808
809First, it initializes the environment it wants to run in: turning off
810warnings during its own compilation, defining variables which it will need
811to avoid warnings later, setting itself up to not exit when the program
812terminates, and defaulting to printing return values for the C<r> command.
813
814=cut
815
816# Needed for the statement after exec():
817#
818# This BEGIN block is simply used to switch off warnings during debugger
819# compilation. Probably it would be better practice to fix the warnings,
820# but this is how it's done at the moment.
821
822BEGIN {
823    $ini_warn = $^W;
824    $^W       = 0;
825}    # Switch compilation warnings off until another BEGIN.
826
827local ($^W) = 0;    # Switch run-time warnings off during init.
828
829=head2 THREADS SUPPORT
830
831If we are running under a threaded Perl, we require threads and threads::shared
832if the environment variable C<PERL5DB_THREADED> is set, to enable proper
833threaded debugger control.  C<-dt> can also be used to set this.
834
835Each new thread will be announced and the debugger prompt will always inform
836you of each new thread created.  It will also indicate the thread id in which
837we are currently running within the prompt like this:
838
839    [tid] DB<$i>
840
841Where C<[tid]> is an integer thread id and C<$i> is the familiar debugger
842command prompt.  The prompt will show: C<[0]> when running under threads, but
843not actually in a thread.  C<[tid]> is consistent with C<gdb> usage.
844
845While running under threads, when you set or delete a breakpoint (etc.), this
846will apply to all threads, not just the currently running one.  When you are
847in a currently executing thread, you will stay there until it completes.  With
848the current implementation it is not currently possible to hop from one thread
849to another.
850
851The C<e> and C<E> commands are currently fairly minimal - see C<h e> and C<h E>.
852
853Note that threading support was built into the debugger as of Perl version
854C<5.8.6> and debugger version C<1.2.8>.
855
856=cut
857
858BEGIN {
859    # ensure we can share our non-threaded variables or no-op
860    if ($ENV{PERL5DB_THREADED}) {
861        require threads;
862        require threads::shared;
863        import threads::shared qw(share);
864        $DBGR;
865        share(\$DBGR);
866        lock($DBGR);
867        print "Threads support enabled\n";
868    } else {
869        *lock = sub(*) {};
870        *share = sub(\[$@%]) {};
871    }
872}
873
874# These variables control the execution of 'dumpvar.pl'.
875{
876    package dumpvar;
877    use vars qw(
878    $hashDepth
879    $arrayDepth
880    $dumpDBFiles
881    $dumpPackages
882    $quoteHighBit
883    $printUndef
884    $globPrint
885    $usageOnly
886    );
887}
888
889# used to control die() reporting in diesignal()
890{
891    package Carp;
892    use vars qw($CarpLevel);
893}
894
895# without threads, $filename is not defined until DB::DB is called
896share($main::{'_<'.$filename}) if defined $filename;
897
898# Command-line + PERLLIB:
899# Save the contents of @INC before they are modified elsewhere.
900@ini_INC = @INC;
901
902# This was an attempt to clear out the previous values of various
903# trapped errors. Apparently it didn't help. XXX More info needed!
904# $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?!
905
906# We set these variables to safe values. We don't want to blindly turn
907# off warnings, because other packages may still want them.
908$trace = $signal = $single = 0;    # Uninitialized warning suppression
909                                   # (local $^W cannot help - other packages!).
910
911# Default to not exiting when program finishes; print the return
912# value when the 'r' command is used to return from a subroutine.
913$inhibit_exit = $option{PrintRet} = 1;
914
915use vars qw($trace_to_depth);
916
917# Default to 1E9 so it won't be limited to a certain recursion depth.
918$trace_to_depth = 1E9;
919
920=head1 OPTION PROCESSING
921
922The debugger's options are actually spread out over the debugger itself and
923C<dumpvar.pl>; some of these are variables to be set, while others are
924subs to be called with a value. To try to make this a little easier to
925manage, the debugger uses a few data structures to define what options
926are legal and how they are to be processed.
927
928First, the C<@options> array defines the I<names> of all the options that
929are to be accepted.
930
931=cut
932
933@options = qw(
934  CommandSet   HistFile      HistSize
935  hashDepth    arrayDepth    dumpDepth
936  DumpDBFiles  DumpPackages  DumpReused
937  compactDump  veryCompact   quote
938  HighBit      undefPrint    globPrint
939  PrintRet     UsageOnly     frame
940  AutoTrace    TTY           noTTY
941  ReadLine     NonStop       LineInfo
942  maxTraceLen  recallCommand ShellBang
943  pager        tkRunning     ornaments
944  signalLevel  warnLevel     dieLevel
945  inhibit_exit ImmediateStop bareStringify
946  CreateTTY    RemotePort    windowSize
947  DollarCaretP
948);
949
950@RememberOnROptions = qw(DollarCaretP);
951
952=pod
953
954Second, C<optionVars> lists the variables that each option uses to save its
955state.
956
957=cut
958
959use vars qw(%optionVars);
960
961%optionVars = (
962    hashDepth     => \$dumpvar::hashDepth,
963    arrayDepth    => \$dumpvar::arrayDepth,
964    CommandSet    => \$CommandSet,
965    DumpDBFiles   => \$dumpvar::dumpDBFiles,
966    DumpPackages  => \$dumpvar::dumpPackages,
967    DumpReused    => \$dumpvar::dumpReused,
968    HighBit       => \$dumpvar::quoteHighBit,
969    undefPrint    => \$dumpvar::printUndef,
970    globPrint     => \$dumpvar::globPrint,
971    UsageOnly     => \$dumpvar::usageOnly,
972    CreateTTY     => \$CreateTTY,
973    bareStringify => \$dumpvar::bareStringify,
974    frame         => \$frame,
975    AutoTrace     => \$trace,
976    inhibit_exit  => \$inhibit_exit,
977    maxTraceLen   => \$maxtrace,
978    ImmediateStop => \$ImmediateStop,
979    RemotePort    => \$remoteport,
980    windowSize    => \$window,
981    HistFile      => \$histfile,
982    HistSize      => \$histsize,
983);
984
985=pod
986
987Third, C<%optionAction> defines the subroutine to be called to process each
988option.
989
990=cut
991
992use vars qw(%optionAction);
993
994%optionAction = (
995    compactDump   => \&dumpvar::compactDump,
996    veryCompact   => \&dumpvar::veryCompact,
997    quote         => \&dumpvar::quote,
998    TTY           => \&TTY,
999    noTTY         => \&noTTY,
1000    ReadLine      => \&ReadLine,
1001    NonStop       => \&NonStop,
1002    LineInfo      => \&LineInfo,
1003    recallCommand => \&recallCommand,
1004    ShellBang     => \&shellBang,
1005    pager         => \&pager,
1006    signalLevel   => \&signalLevel,
1007    warnLevel     => \&warnLevel,
1008    dieLevel      => \&dieLevel,
1009    tkRunning     => \&tkRunning,
1010    ornaments     => \&ornaments,
1011    RemotePort    => \&RemotePort,
1012    DollarCaretP  => \&DollarCaretP,
1013);
1014
1015=pod
1016
1017Last, the C<%optionRequire> notes modules that must be C<require>d if an
1018option is used.
1019
1020=cut
1021
1022# Note that this list is not complete: several options not listed here
1023# actually require that dumpvar.pl be loaded for them to work, but are
1024# not in the table. A subsequent patch will correct this problem; for
1025# the moment, we're just recommenting, and we are NOT going to change
1026# function.
1027use vars qw(%optionRequire);
1028
1029%optionRequire = (
1030    compactDump => 'dumpvar.pl',
1031    veryCompact => 'dumpvar.pl',
1032    quote       => 'dumpvar.pl',
1033);
1034
1035=pod
1036
1037There are a number of initialization-related variables which can be set
1038by putting code to set them in a BEGIN block in the C<PERL5DB> environment
1039variable. These are:
1040
1041=over 4
1042
1043=item C<$rl> - readline control XXX needs more explanation
1044
1045=item C<$warnLevel> - whether or not debugger takes over warning handling
1046
1047=item C<$dieLevel> - whether or not debugger takes over die handling
1048
1049=item C<$signalLevel> - whether or not debugger takes over signal handling
1050
1051=item C<$pre> - preprompt actions (array reference)
1052
1053=item C<$post> - postprompt actions (array reference)
1054
1055=item C<$pretype>
1056
1057=item C<$CreateTTY> - whether or not to create a new TTY for this debugger
1058
1059=item C<$CommandSet> - which command set to use (defaults to new, documented set)
1060
1061=back
1062
1063=cut
1064
1065# These guys may be defined in $ENV{PERL5DB} :
1066$rl          = 1     unless defined $rl;
1067$warnLevel   = 1     unless defined $warnLevel;
1068$dieLevel    = 1     unless defined $dieLevel;
1069$signalLevel = 1     unless defined $signalLevel;
1070$pre         = []    unless defined $pre;
1071$post        = []    unless defined $post;
1072$pretype     = []    unless defined $pretype;
1073$CreateTTY   = 3     unless defined $CreateTTY;
1074$CommandSet  = '580' unless defined $CommandSet;
1075
1076share($rl);
1077share($warnLevel);
1078share($dieLevel);
1079share($signalLevel);
1080share($pre);
1081share($post);
1082share($pretype);
1083share($rl);
1084share($CreateTTY);
1085share($CommandSet);
1086
1087=pod
1088
1089The default C<die>, C<warn>, and C<signal> handlers are set up.
1090
1091=cut
1092
1093warnLevel($warnLevel);
1094dieLevel($dieLevel);
1095signalLevel($signalLevel);
1096
1097=pod
1098
1099The pager to be used is needed next. We try to get it from the
1100environment first.  If it's not defined there, we try to find it in
1101the Perl C<Config.pm>.  If it's not there, we default to C<more>. We
1102then call the C<pager()> function to save the pager name.
1103
1104=cut
1105
1106# This routine makes sure $pager is set up so that '|' can use it.
1107pager(
1108
1109    # If PAGER is defined in the environment, use it.
1110    defined $ENV{PAGER}
1111    ? $ENV{PAGER}
1112
1113      # If not, see if Config.pm defines it.
1114    : eval { require Config }
1115      && defined $Config::Config{pager}
1116    ? $Config::Config{pager}
1117
1118      # If not, fall back to 'more'.
1119    : 'more'
1120  )
1121  unless defined $pager;
1122
1123=pod
1124
1125We set up the command to be used to access the man pages, the command
1126recall character (C<!> unless otherwise defined) and the shell escape
1127character (C<!> unless otherwise defined). Yes, these do conflict, and
1128neither works in the debugger at the moment.
1129
1130=cut
1131
1132setman();
1133
1134# Set up defaults for command recall and shell escape (note:
1135# these currently don't work in linemode debugging).
1136recallCommand("!") unless defined $prc;
1137shellBang("!")     unless defined $psh;
1138
1139=pod
1140
1141We then set up the gigantic string containing the debugger help.
1142We also set the limit on the number of arguments we'll display during a
1143trace.
1144
1145=cut
1146
1147sethelp();
1148
1149# If we didn't get a default for the length of eval/stack trace args,
1150# set it here.
1151$maxtrace = 400 unless defined $maxtrace;
1152
1153=head2 SETTING UP THE DEBUGGER GREETING
1154
1155The debugger I<greeting> helps to inform the user how many debuggers are
1156running, and whether the current debugger is the primary or a child.
1157
1158If we are the primary, we just hang onto our pid so we'll have it when
1159or if we start a child debugger. If we are a child, we'll set things up
1160so we'll have a unique greeting and so the parent will give us our own
1161TTY later.
1162
1163We save the current contents of the C<PERLDB_PIDS> environment variable
1164because we mess around with it. We'll also need to hang onto it because
1165we'll need it if we restart.
1166
1167Child debuggers make a label out of the current PID structure recorded in
1168PERLDB_PIDS plus the new PID. They also mark themselves as not having a TTY
1169yet so the parent will give them one later via C<resetterm()>.
1170
1171=cut
1172
1173# Save the current contents of the environment; we're about to
1174# much with it. We'll need this if we have to restart.
1175use vars qw($ini_pids);
1176$ini_pids = $ENV{PERLDB_PIDS};
1177
1178use vars qw ($pids $term_pid);
1179
1180if ( defined $ENV{PERLDB_PIDS} ) {
1181
1182    # We're a child. Make us a label out of the current PID structure
1183    # recorded in PERLDB_PIDS plus our (new) PID. Mark us as not having
1184    # a term yet so the parent will give us one later via resetterm().
1185
1186    my $env_pids = $ENV{PERLDB_PIDS};
1187    $pids = "[$env_pids]";
1188
1189    # Unless we are on OpenVMS, all programs under the DCL shell run under
1190    # the same PID.
1191
1192    if (($^O eq 'VMS') && ($env_pids =~ /\b$$\b/)) {
1193        $term_pid         = $$;
1194    }
1195    else {
1196        $ENV{PERLDB_PIDS} .= "->$$";
1197        $term_pid = -1;
1198    }
1199
1200} ## end if (defined $ENV{PERLDB_PIDS...
1201else {
1202
1203    # We're the parent PID. Initialize PERLDB_PID in case we end up with a
1204    # child debugger, and mark us as the parent, so we'll know to set up
1205    # more TTY's is we have to.
1206    $ENV{PERLDB_PIDS} = "$$";
1207    $pids             = "[pid=$$]";
1208    $term_pid         = $$;
1209}
1210
1211use vars qw($pidprompt);
1212$pidprompt = '';
1213
1214# Sets up $emacs as a synonym for $slave_editor.
1215our ($slave_editor);
1216*emacs = $slave_editor if $slave_editor;    # May be used in afterinit()...
1217
1218=head2 READING THE RC FILE
1219
1220The debugger will read a file of initialization options if supplied. If
1221running interactively, this is C<.perldb>; if not, it's C<perldb.ini>.
1222
1223=cut
1224
1225# As noted, this test really doesn't check accurately that the debugger
1226# is running at a terminal or not.
1227
1228use vars qw($rcfile);
1229{
1230    my $dev_tty = (($^O eq 'VMS') ? 'TT:' : '/dev/tty');
1231    # this is the wrong metric!
1232    $rcfile = ((-e $dev_tty) ? ".perldb" : "perldb.ini");
1233}
1234
1235=pod
1236
1237The debugger does a safety test of the file to be read. It must be owned
1238either by the current user or root, and must only be writable by the owner.
1239
1240=cut
1241
1242# This wraps a safety test around "do" to read and evaluate the init file.
1243#
1244# This isn't really safe, because there's a race
1245# between checking and opening.  The solution is to
1246# open and fstat the handle, but then you have to read and
1247# eval the contents.  But then the silly thing gets
1248# your lexical scope, which is unfortunate at best.
1249sub safe_do {
1250    my $file = shift;
1251
1252    # Just exactly what part of the word "CORE::" don't you understand?
1253    local $SIG{__WARN__};
1254    local $SIG{__DIE__};
1255
1256    unless ( is_safe_file($file) ) {
1257        CORE::warn <<EO_GRIPE;
1258perldb: Must not source insecure rcfile $file.
1259        You or the superuser must be the owner, and it must not
1260        be writable by anyone but its owner.
1261EO_GRIPE
1262        return;
1263    } ## end unless (is_safe_file($file...
1264
1265    do $file;
1266    CORE::warn("perldb: couldn't parse $file: $@") if $@;
1267} ## end sub safe_do
1268
1269# This is the safety test itself.
1270#
1271# Verifies that owner is either real user or superuser and that no
1272# one but owner may write to it.  This function is of limited use
1273# when called on a path instead of upon a handle, because there are
1274# no guarantees that filename (by dirent) whose file (by ino) is
1275# eventually accessed is the same as the one tested.
1276# Assumes that the file's existence is not in doubt.
1277sub is_safe_file {
1278    my $path = shift;
1279    stat($path) || return;    # mysteriously vaporized
1280    my ( $dev, $ino, $mode, $nlink, $uid, $gid ) = stat(_);
1281
1282    return 0 if $uid != 0 && $uid != $<;
1283    return 0 if $mode & 022;
1284    return 1;
1285} ## end sub is_safe_file
1286
1287# If the rcfile (whichever one we decided was the right one to read)
1288# exists, we safely do it.
1289if ( -f $rcfile ) {
1290    safe_do("./$rcfile");
1291}
1292
1293# If there isn't one here, try the user's home directory.
1294elsif ( defined $ENV{HOME} && -f "$ENV{HOME}/$rcfile" ) {
1295    safe_do("$ENV{HOME}/$rcfile");
1296}
1297
1298# Else try the login directory.
1299elsif ( defined $ENV{LOGDIR} && -f "$ENV{LOGDIR}/$rcfile" ) {
1300    safe_do("$ENV{LOGDIR}/$rcfile");
1301}
1302
1303# If the PERLDB_OPTS variable has options in it, parse those out next.
1304if ( defined $ENV{PERLDB_OPTS} ) {
1305    parse_options( $ENV{PERLDB_OPTS} );
1306}
1307
1308=pod
1309
1310The last thing we do during initialization is determine which subroutine is
1311to be used to obtain a new terminal when a new debugger is started. Right now,
1312the debugger only handles TCP sockets, X11, OS/2, amd Mac OS X
1313(darwin).
1314
1315=cut
1316
1317# Set up the get_fork_TTY subroutine to be aliased to the proper routine.
1318# Works if you're running an xterm or xterm-like window, or you're on
1319# OS/2, or on Mac OS X. This may need some expansion.
1320
1321if (not defined &get_fork_TTY)       # only if no routine exists
1322{
1323    if ( defined $remoteport ) {
1324                                                 # Expect an inetd-like server
1325        *get_fork_TTY = \&socket_get_fork_TTY;   # to listen to us
1326    }
1327    elsif (defined $ENV{TERM}                    # If we know what kind
1328                                                 # of terminal this is,
1329        and $ENV{TERM} eq 'xterm'                # and it's an xterm,
1330        and defined $ENV{DISPLAY}                # and what display it's on,
1331      )
1332    {
1333        *get_fork_TTY = \&xterm_get_fork_TTY;    # use the xterm version
1334    }
1335    elsif ( $^O eq 'os2' ) {                     # If this is OS/2,
1336        *get_fork_TTY = \&os2_get_fork_TTY;      # use the OS/2 version
1337    }
1338    elsif ( $^O eq 'darwin'                      # If this is Mac OS X
1339            and defined $ENV{TERM_PROGRAM}       # and we're running inside
1340            and $ENV{TERM_PROGRAM}
1341                eq 'Apple_Terminal'              # Terminal.app
1342            )
1343    {
1344        *get_fork_TTY = \&macosx_get_fork_TTY;   # use the Mac OS X version
1345    }
1346} ## end if (not defined &get_fork_TTY...
1347
1348# untaint $^O, which may have been tainted by the last statement.
1349# see bug [perl #24674]
1350$^O =~ m/^(.*)\z/;
1351$^O = $1;
1352
1353# Here begin the unreadable code.  It needs fixing.
1354
1355=head2 RESTART PROCESSING
1356
1357This section handles the restart command. When the C<R> command is invoked, it
1358tries to capture all of the state it can into environment variables, and
1359then sets C<PERLDB_RESTART>. When we start executing again, we check to see
1360if C<PERLDB_RESTART> is there; if so, we reload all the information that
1361the R command stuffed into the environment variables.
1362
1363  PERLDB_RESTART   - flag only, contains no restart data itself.
1364  PERLDB_HIST      - command history, if it's available
1365  PERLDB_ON_LOAD   - breakpoints set by the rc file
1366  PERLDB_POSTPONE  - subs that have been loaded/not executed,
1367                     and have actions
1368  PERLDB_VISITED   - files that had breakpoints
1369  PERLDB_FILE_...  - breakpoints for a file
1370  PERLDB_OPT       - active options
1371  PERLDB_INC       - the original @INC
1372  PERLDB_PRETYPE   - preprompt debugger actions
1373  PERLDB_PRE       - preprompt Perl code
1374  PERLDB_POST      - post-prompt Perl code
1375  PERLDB_TYPEAHEAD - typeahead captured by readline()
1376
1377We chug through all these variables and plug the values saved in them
1378back into the appropriate spots in the debugger.
1379
1380=cut
1381
1382use vars qw(%postponed_file @typeahead);
1383
1384our (@hist, @truehist);
1385
1386sub _restore_shared_globals_after_restart
1387{
1388    @hist          = get_list('PERLDB_HIST');
1389    %break_on_load = get_list("PERLDB_ON_LOAD");
1390    %postponed     = get_list("PERLDB_POSTPONE");
1391
1392    share(@hist);
1393    share(@truehist);
1394    share(%break_on_load);
1395    share(%postponed);
1396}
1397
1398sub _restore_breakpoints_and_actions {
1399
1400    my @had_breakpoints = get_list("PERLDB_VISITED");
1401
1402    for my $file_idx ( 0 .. $#had_breakpoints ) {
1403        my $filename = $had_breakpoints[$file_idx];
1404        my %pf = get_list("PERLDB_FILE_$file_idx");
1405        $postponed_file{ $filename } = \%pf if %pf;
1406        my @lines = sort {$a <=> $b} keys(%pf);
1407        my @enabled_statuses = get_list("PERLDB_FILE_ENABLED_$file_idx");
1408        for my $line_idx (0 .. $#lines) {
1409            _set_breakpoint_enabled_status(
1410                $filename,
1411                $lines[$line_idx],
1412                ($enabled_statuses[$line_idx] ? 1 : ''),
1413            );
1414        }
1415    }
1416
1417    return;
1418}
1419
1420sub _restore_options_after_restart
1421{
1422    my %options_map = get_list("PERLDB_OPT");
1423
1424    while ( my ( $opt, $val ) = each %options_map ) {
1425        $val =~ s/[\\\']/\\$1/g;
1426        parse_options("$opt'$val'");
1427    }
1428
1429    return;
1430}
1431
1432sub _restore_globals_after_restart
1433{
1434    # restore original @INC
1435    @INC     = get_list("PERLDB_INC");
1436    @ini_INC = @INC;
1437
1438    # return pre/postprompt actions and typeahead buffer
1439    $pretype   = [ get_list("PERLDB_PRETYPE") ];
1440    $pre       = [ get_list("PERLDB_PRE") ];
1441    $post      = [ get_list("PERLDB_POST") ];
1442    @typeahead = get_list( "PERLDB_TYPEAHEAD", @typeahead );
1443
1444    return;
1445}
1446
1447
1448if ( exists $ENV{PERLDB_RESTART} ) {
1449
1450    # We're restarting, so we don't need the flag that says to restart anymore.
1451    delete $ENV{PERLDB_RESTART};
1452
1453    # $restart = 1;
1454    _restore_shared_globals_after_restart();
1455
1456    _restore_breakpoints_and_actions();
1457
1458    # restore options
1459    _restore_options_after_restart();
1460
1461    _restore_globals_after_restart();
1462} ## end if (exists $ENV{PERLDB_RESTART...
1463
1464=head2 SETTING UP THE TERMINAL
1465
1466Now, we'll decide how the debugger is going to interact with the user.
1467If there's no TTY, we set the debugger to run non-stop; there's not going
1468to be anyone there to enter commands.
1469
1470=cut
1471
1472use vars qw($notty $console $tty $LINEINFO);
1473use vars qw($lineinfo $doccmd);
1474
1475our ($runnonstop);
1476
1477# Local autoflush to avoid rt#116769,
1478# as calling IO::File methods causes an unresolvable loop
1479# that results in debugger failure.
1480sub _autoflush {
1481    my $o = select($_[0]);
1482    $|++;
1483    select($o);
1484}
1485
1486if ($notty) {
1487    $runnonstop = 1;
1488    share($runnonstop);
1489}
1490
1491=pod
1492
1493If there is a TTY, we have to determine who it belongs to before we can
1494proceed. If this is a slave editor or graphical debugger (denoted by
1495the first command-line switch being '-emacs'), we shift this off and
1496set C<$rl> to 0 (XXX ostensibly to do straight reads).
1497
1498=cut
1499
1500else {
1501
1502    # Is Perl being run from a slave editor or graphical debugger?
1503    # If so, don't use readline, and set $slave_editor = 1.
1504    if ($slave_editor = ( @main::ARGV && ( $main::ARGV[0] eq '-emacs' ) )) {
1505        $rl = 0;
1506        shift(@main::ARGV);
1507    }
1508
1509    #require Term::ReadLine;
1510
1511=pod
1512
1513We then determine what the console should be on various systems:
1514
1515=over 4
1516
1517=item * Cygwin - We use C<stdin> instead of a separate device.
1518
1519=cut
1520
1521    if ( $^O eq 'cygwin' ) {
1522
1523        # /dev/tty is binary. use stdin for textmode
1524        undef $console;
1525    }
1526
1527=item * Unix - use F</dev/tty>.
1528
1529=cut
1530
1531    elsif ( -e "/dev/tty" ) {
1532        $console = "/dev/tty";
1533    }
1534
1535=item * Windows or MSDOS - use C<con>.
1536
1537=cut
1538
1539    elsif ( $^O eq 'dos' or -e "con" or $^O eq 'MSWin32' ) {
1540        $console = "con";
1541    }
1542
1543=item * VMS - use C<sys$command>.
1544
1545=cut
1546
1547    else {
1548
1549        # everything else is ...
1550        $console = "sys\$command";
1551    }
1552
1553=pod
1554
1555=back
1556
1557Several other systems don't use a specific console. We C<undef $console>
1558for those (Windows using a slave editor/graphical debugger, NetWare, OS/2
1559with a slave editor).
1560
1561=cut
1562
1563    if ( ( $^O eq 'MSWin32' ) and ( $slave_editor or defined $ENV{EMACS} ) ) {
1564
1565        # /dev/tty is binary. use stdin for textmode
1566        $console = undef;
1567    }
1568
1569    if ( $^O eq 'NetWare' ) {
1570
1571        # /dev/tty is binary. use stdin for textmode
1572        $console = undef;
1573    }
1574
1575    # In OS/2, we need to use STDIN to get textmode too, even though
1576    # it pretty much looks like Unix otherwise.
1577    if ( defined $ENV{OS2_SHELL} and ( $slave_editor or $ENV{WINDOWID} ) )
1578    {    # In OS/2
1579        $console = undef;
1580    }
1581
1582=pod
1583
1584If there is a TTY hanging around from a parent, we use that as the console.
1585
1586=cut
1587
1588    $console = $tty if defined $tty;
1589
1590=head2 SOCKET HANDLING
1591
1592The debugger is capable of opening a socket and carrying out a debugging
1593session over the socket.
1594
1595If C<RemotePort> was defined in the options, the debugger assumes that it
1596should try to start a debugging session on that port. It builds the socket
1597and then tries to connect the input and output filehandles to it.
1598
1599=cut
1600
1601    # Handle socket stuff.
1602
1603    if ( defined $remoteport ) {
1604
1605        # If RemotePort was defined in the options, connect input and output
1606        # to the socket.
1607        $IN = $OUT = connect_remoteport();
1608    } ## end if (defined $remoteport)
1609
1610=pod
1611
1612If no C<RemotePort> was defined, and we want to create a TTY on startup,
1613this is probably a situation where multiple debuggers are running (for example,
1614a backticked command that starts up another debugger). We create a new IN and
1615OUT filehandle, and do the necessary mojo to create a new TTY if we know how
1616and if we can.
1617
1618=cut
1619
1620    # Non-socket.
1621    else {
1622
1623        # Two debuggers running (probably a system or a backtick that invokes
1624        # the debugger itself under the running one). create a new IN and OUT
1625        # filehandle, and do the necessary mojo to create a new tty if we
1626        # know how, and we can.
1627        create_IN_OUT(4) if $CreateTTY & 4;
1628        if ($console) {
1629
1630            # If we have a console, check to see if there are separate ins and
1631            # outs to open. (They are assumed identical if not.)
1632
1633            my ( $i, $o ) = split /,/, $console;
1634            $o = $i unless defined $o;
1635
1636            # read/write on in, or just read, or read on STDIN.
1637            open( IN,      "+<$i" )
1638              || open( IN, "<$i" )
1639              || open( IN, "<&STDIN" );
1640
1641            # read/write/create/clobber out, or write/create/clobber out,
1642            # or merge with STDERR, or merge with STDOUT.
1643                 open( OUT, "+>$o" )
1644              || open( OUT, ">$o" )
1645              || open( OUT, ">&STDERR" )
1646              || open( OUT, ">&STDOUT" );    # so we don't dongle stdout
1647
1648        } ## end if ($console)
1649        elsif ( not defined $console ) {
1650
1651            # No console. Open STDIN.
1652            open( IN, "<&STDIN" );
1653
1654            # merge with STDERR, or with STDOUT.
1655            open( OUT,      ">&STDERR" )
1656              || open( OUT, ">&STDOUT" );    # so we don't dongle stdout
1657            $console = 'STDIN/OUT';
1658        } ## end elsif (not defined $console)
1659
1660        # Keep copies of the filehandles so that when the pager runs, it
1661        # can close standard input without clobbering ours.
1662        if ($console or (not defined($console))) {
1663            $IN = \*IN;
1664            $OUT = \*OUT;
1665        }
1666    } ## end elsif (from if(defined $remoteport))
1667
1668    # Unbuffer DB::OUT. We need to see responses right away.
1669    _autoflush($OUT);
1670
1671    # Line info goes to debugger output unless pointed elsewhere.
1672    # Pointing elsewhere makes it possible for slave editors to
1673    # keep track of file and position. We have both a filehandle
1674    # and a I/O description to keep track of.
1675    $LINEINFO = $OUT     unless defined $LINEINFO;
1676    $lineinfo = $console unless defined $lineinfo;
1677    # share($LINEINFO); # <- unable to share globs
1678    share($lineinfo);   #
1679
1680=pod
1681
1682To finish initialization, we show the debugger greeting,
1683and then call the C<afterinit()> subroutine if there is one.
1684
1685=cut
1686
1687    # Show the debugger greeting.
1688    $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/;
1689    unless ($runnonstop) {
1690        local $\ = '';
1691        local $, = '';
1692        if ( $term_pid eq '-1' ) {
1693            print $OUT "\nDaughter DB session started...\n";
1694        }
1695        else {
1696            print $OUT "\nLoading DB routines from $header\n";
1697            print $OUT (
1698                "Editor support ",
1699                $slave_editor ? "enabled" : "available", ".\n"
1700            );
1701            print $OUT
1702"\nEnter h or 'h h' for help, or '$doccmd perldebug' for more help.\n\n";
1703        } ## end else [ if ($term_pid eq '-1')
1704    } ## end unless ($runnonstop)
1705} ## end else [ if ($notty)
1706
1707# XXX This looks like a bug to me.
1708# Why copy to @ARGS and then futz with @args?
1709@ARGS = @ARGV;
1710# for (@args) {
1711    # Make sure backslashes before single quotes are stripped out, and
1712    # keep args unless they are numeric (XXX why?)
1713    # s/\'/\\\'/g;                      # removed while not justified understandably
1714    # s/(.*)/'$1'/ unless /^-?[\d.]+$/; # ditto
1715# }
1716
1717# If there was an afterinit() sub defined, call it. It will get
1718# executed in our scope, so it can fiddle with debugger globals.
1719if ( defined &afterinit ) {    # May be defined in $rcfile
1720    afterinit();
1721}
1722
1723# Inform us about "Stack dump during die enabled ..." in dieLevel().
1724use vars qw($I_m_init);
1725
1726$I_m_init = 1;
1727
1728############################################################ Subroutines
1729
1730=head1 SUBROUTINES
1731
1732=head2 DB
1733
1734This gigantic subroutine is the heart of the debugger. Called before every
1735statement, its job is to determine if a breakpoint has been reached, and
1736stop if so; read commands from the user, parse them, and execute
1737them, and then send execution off to the next statement.
1738
1739Note that the order in which the commands are processed is very important;
1740some commands earlier in the loop will actually alter the C<$cmd> variable
1741to create other commands to be executed later. This is all highly I<optimized>
1742but can be confusing. Check the comments for each C<$cmd ... && do {}> to
1743see what's happening in any given command.
1744
1745=cut
1746
1747# $cmd cannot be an our() variable unfortunately (possible perl bug?).
1748
1749use vars qw(
1750    $action
1751    $cmd
1752    $file
1753    $filename_ini
1754    $finished
1755    %had_breakpoints
1756    $level
1757    $max
1758    $package
1759    $try
1760);
1761
1762our (
1763    %alias,
1764    $doret,
1765    $end,
1766    $fall_off_end,
1767    $incr,
1768    $laststep,
1769    $rc,
1770    $sh,
1771    $stack_depth,
1772    @stack,
1773    @to_watch,
1774    @old_watch,
1775);
1776
1777sub _DB__determine_if_we_should_break
1778{
1779    # if we have something here, see if we should break.
1780    # $stop is lexical and local to this block - $action on the other hand
1781    # is global.
1782    my $stop;
1783
1784    if ( $dbline{$line}
1785        && _is_breakpoint_enabled($filename, $line)
1786        && (( $stop, $action ) = split( /\0/, $dbline{$line} ) ) )
1787    {
1788
1789        # Stop if the stop criterion says to just stop.
1790        if ( $stop eq '1' ) {
1791            $signal |= 1;
1792        }
1793
1794        # It's a conditional stop; eval it in the user's context and
1795        # see if we should stop. If so, remove the one-time sigil.
1796        elsif ($stop) {
1797            $evalarg = "\$DB::signal |= 1 if do {$stop}";
1798            # The &-call is here to ascertain the mutability of @_.
1799            &DB::eval;
1800            # If the breakpoint is temporary, then delete its enabled status.
1801            if ($dbline{$line} =~ s/;9($|\0)/$1/) {
1802                _cancel_breakpoint_temp_enabled_status($filename, $line);
1803            }
1804        }
1805    } ## end if ($dbline{$line} && ...
1806}
1807
1808sub _DB__is_finished {
1809    if ($finished and $level <= 1) {
1810        end_report();
1811        return 1;
1812    }
1813    else {
1814        return;
1815    }
1816}
1817
1818sub _DB__read_next_cmd
1819{
1820    my ($tid) = @_;
1821
1822    # We have a terminal, or can get one ...
1823    if (!$term) {
1824        setterm();
1825    }
1826
1827    # ... and it belongs to this PID or we get one for this PID ...
1828    if ($term_pid != $$) {
1829        resetterm(1);
1830    }
1831
1832    # ... and we got a line of command input ...
1833    $cmd = DB::readline(
1834        "$pidprompt $tid DB"
1835        . ( '<' x $level )
1836        . ( $#hist + 1 )
1837        . ( '>' x $level ) . " "
1838    );
1839
1840    return defined($cmd);
1841}
1842
1843sub _DB__trim_command_and_return_first_component {
1844    my ($obj) = @_;
1845
1846    $cmd =~ s/\A\s+//s;    # trim annoying leading whitespace
1847    $cmd =~ s/\s+\z//s;    # trim annoying trailing whitespace
1848
1849    my ($verb, $args) = $cmd =~ m{\A(\S*)\s*(.*)}s;
1850
1851    $obj->cmd_verb($verb);
1852    $obj->cmd_args($args);
1853
1854    return;
1855}
1856
1857sub _DB__handle_f_command {
1858    my ($obj) = @_;
1859
1860    if ($file = $obj->cmd_args) {
1861        # help for no arguments (old-style was return from sub).
1862        if ( !$file ) {
1863            print $OUT
1864            "The old f command is now the r command.\n";    # hint
1865            print $OUT "The new f command switches filenames.\n";
1866            next CMD;
1867        } ## end if (!$file)
1868
1869        # if not in magic file list, try a close match.
1870        if ( !defined $main::{ '_<' . $file } ) {
1871            if ( ($try) = grep( m#^_<.*$file#, keys %main:: ) ) {
1872                {
1873                    $try = substr( $try, 2 );
1874                    print $OUT "Choosing $try matching '$file':\n";
1875                    $file = $try;
1876                }
1877            } ## end if (($try) = grep(m#^_<.*$file#...
1878        } ## end if (!defined $main::{ ...
1879
1880        # If not successfully switched now, we failed.
1881        if ( !defined $main::{ '_<' . $file } ) {
1882            print $OUT "No file matching '$file' is loaded.\n";
1883            next CMD;
1884        }
1885
1886        # We switched, so switch the debugger internals around.
1887        elsif ( $file ne $filename ) {
1888            *dbline   = $main::{ '_<' . $file };
1889            $max      = $#dbline;
1890            $filename = $file;
1891            $start    = 1;
1892            $cmd      = "l";
1893        } ## end elsif ($file ne $filename)
1894
1895        # We didn't switch; say we didn't.
1896        else {
1897            print $OUT "Already in $file.\n";
1898            next CMD;
1899        }
1900    }
1901
1902    return;
1903}
1904
1905sub _DB__handle_dot_command {
1906    my ($obj) = @_;
1907
1908    # . command.
1909    if ($obj->_is_full('.')) {
1910        $incr = -1;    # stay at current line
1911
1912        # Reset everything to the old location.
1913        $start    = $line;
1914        $filename = $filename_ini;
1915        *dbline   = $main::{ '_<' . $filename };
1916        $max      = $#dbline;
1917
1918        # Now where are we?
1919        print_lineinfo($obj->position());
1920        next CMD;
1921    }
1922
1923    return;
1924}
1925
1926sub _DB__handle_y_command {
1927    my ($obj) = @_;
1928
1929    if (my ($match_level, $match_vars)
1930        = $obj->cmd_args =~ /\A(?:(\d*)\s*(.*))?\z/) {
1931
1932        # See if we've got the necessary support.
1933        if (!eval {
1934            local @INC = @INC;
1935            pop @INC if $INC[-1] eq '.';
1936            require PadWalker; PadWalker->VERSION(0.08) }) {
1937            my $Err = $@;
1938            _db_warn(
1939                $Err =~ /locate/
1940                ? "PadWalker module not found - please install\n"
1941                : $Err
1942            );
1943            next CMD;
1944        }
1945
1946        # Load up dumpvar if we don't have it. If we can, that is.
1947        do 'dumpvar.pl' || die $@ unless defined &main::dumpvar;
1948        defined &main::dumpvar
1949            or print $OUT "dumpvar.pl not available.\n"
1950            and next CMD;
1951
1952        # Got all the modules we need. Find them and print them.
1953        my @vars = split( ' ', $match_vars || '' );
1954
1955        # Find the pad.
1956        my $h = eval { PadWalker::peek_my( ( $match_level || 0 ) + 1 ) };
1957
1958        # Oops. Can't find it.
1959        if (my $Err = $@) {
1960            $Err =~ s/ at .*//;
1961            _db_warn($Err);
1962            next CMD;
1963        }
1964
1965        # Show the desired vars with dumplex().
1966        my $savout = select($OUT);
1967
1968        # Have dumplex dump the lexicals.
1969        foreach my $key (sort keys %$h) {
1970            dumpvar::dumplex( $key, $h->{$key},
1971                defined $option{dumpDepth} ? $option{dumpDepth} : -1,
1972                @vars );
1973        }
1974        select($savout);
1975        next CMD;
1976    }
1977}
1978
1979sub _DB__handle_c_command {
1980    my ($obj) = @_;
1981
1982    my $i = $obj->cmd_args;
1983
1984    if ($i =~ m#\A[\w:]*\z#) {
1985
1986        # Hey, show's over. The debugged program finished
1987        # executing already.
1988        next CMD if _DB__is_finished();
1989
1990        # Capture the place to put a one-time break.
1991        $subname = $i;
1992
1993        #  Probably not needed, since we finish an interactive
1994        #  sub-session anyway...
1995        # local $filename = $filename;
1996        # local *dbline = *dbline; # XXX Would this work?!
1997        #
1998        # The above question wonders if localizing the alias
1999        # to the magic array works or not. Since it's commented
2000        # out, we'll just leave that to speculation for now.
2001
2002        # If the "subname" isn't all digits, we'll assume it
2003        # is a subroutine name, and try to find it.
2004        if ( $subname =~ /\D/ ) {    # subroutine name
2005            # Qualify it to the current package unless it's
2006            # already qualified.
2007            $subname = $package . "::" . $subname
2008            unless $subname =~ /::/;
2009
2010            # find_sub will return "file:line_number" corresponding
2011            # to where the subroutine is defined; we call find_sub,
2012            # break up the return value, and assign it in one
2013            # operation.
2014            ( $file, $i ) = ( find_sub($subname) =~ /^(.*):(.*)$/ );
2015
2016            # Force the line number to be numeric.
2017            $i = $i + 0;
2018
2019            # If we got a line number, we found the sub.
2020            if ($i) {
2021
2022                # Switch all the debugger's internals around so
2023                # we're actually working with that file.
2024                $filename = $file;
2025                *dbline   = $main::{ '_<' . $filename };
2026
2027                # Mark that there's a breakpoint in this file.
2028                $had_breakpoints{$filename} |= 1;
2029
2030                # Scan forward to the first executable line
2031                # after the 'sub whatever' line.
2032                $max = $#dbline;
2033                my $_line_num = $i;
2034                while ($dbline[$_line_num] == 0 && $_line_num< $max)
2035                {
2036                    $_line_num++;
2037                }
2038                $i = $_line_num;
2039            } ## end if ($i)
2040
2041            # We didn't find a sub by that name.
2042            else {
2043                print $OUT "Subroutine $subname not found.\n";
2044                next CMD;
2045            }
2046        } ## end if ($subname =~ /\D/)
2047
2048        # At this point, either the subname was all digits (an
2049        # absolute line-break request) or we've scanned through
2050        # the code following the definition of the sub, looking
2051        # for an executable, which we may or may not have found.
2052        #
2053        # If $i (which we set $subname from) is non-zero, we
2054        # got a request to break at some line somewhere. On
2055        # one hand, if there wasn't any real subroutine name
2056        # involved, this will be a request to break in the current
2057        # file at the specified line, so we have to check to make
2058        # sure that the line specified really is breakable.
2059        #
2060        # On the other hand, if there was a subname supplied, the
2061        # preceding block has moved us to the proper file and
2062        # location within that file, and then scanned forward
2063        # looking for the next executable line. We have to make
2064        # sure that one was found.
2065        #
2066        # On the gripping hand, we can't do anything unless the
2067        # current value of $i points to a valid breakable line.
2068        # Check that.
2069        if ($i) {
2070
2071            # Breakable?
2072            if ( $dbline[$i] == 0 ) {
2073                print $OUT "Line $i not breakable.\n";
2074                next CMD;
2075            }
2076
2077            # Yes. Set up the one-time-break sigil.
2078            $dbline{$i} =~ s/($|\0)/;9$1/;  # add one-time-only b.p.
2079            _enable_breakpoint_temp_enabled_status($filename, $i);
2080        } ## end if ($i)
2081
2082        # Turn off stack tracing from here up.
2083        for my $j (0 .. $stack_depth) {
2084            $stack[ $j ] &= ~1;
2085        }
2086        last CMD;
2087    }
2088
2089    return;
2090}
2091
2092sub _DB__handle_forward_slash_command {
2093    my ($obj) = @_;
2094
2095    # The pattern as a string.
2096    use vars qw($inpat);
2097
2098    if (($inpat) = $cmd =~ m#\A/(.*)\z#) {
2099
2100        # Remove the final slash.
2101        $inpat =~ s:([^\\])/$:$1:;
2102
2103        # If the pattern isn't null ...
2104        if ( $inpat ne "" ) {
2105
2106            # Turn off warn and die processing for a bit.
2107            local $SIG{__DIE__};
2108            local $SIG{__WARN__};
2109
2110            # Create the pattern.
2111            eval 'no strict q/vars/; $inpat =~ m' . "\a$inpat\a";
2112            if ( $@ ne "" ) {
2113
2114                # Oops. Bad pattern. No biscuit.
2115                # Print the eval error and go back for more
2116                # commands.
2117                print {$OUT} "$@";
2118                next CMD;
2119            }
2120            $obj->pat($inpat);
2121        } ## end if ($inpat ne "")
2122
2123        # Set up to stop on wrap-around.
2124        $end = $start;
2125
2126        # Don't move off the current line.
2127        $incr = -1;
2128
2129        my $pat = $obj->pat;
2130
2131        # Done in eval so nothing breaks if the pattern
2132        # does something weird.
2133        eval
2134        {
2135            no strict q/vars/;
2136            for (;;) {
2137                # Move ahead one line.
2138                ++$start;
2139
2140                # Wrap if we pass the last line.
2141                if ($start > $max) {
2142                    $start = 1;
2143                }
2144
2145                # Stop if we have gotten back to this line again,
2146                last if ($start == $end);
2147
2148                # A hit! (Note, though, that we are doing
2149                # case-insensitive matching. Maybe a qr//
2150                # expression would be better, so the user could
2151                # do case-sensitive matching if desired.
2152                if ($dbline[$start] =~ m/$pat/i) {
2153                    if ($slave_editor) {
2154                        # Handle proper escaping in the slave.
2155                        print {$OUT} "\032\032$filename:$start:0\n";
2156                    }
2157                    else {
2158                        # Just print the line normally.
2159                        print {$OUT} "$start:\t",$dbline[$start],"\n";
2160                    }
2161                    # And quit since we found something.
2162                    last;
2163                }
2164            }
2165        };
2166
2167        if ($@) {
2168            warn $@;
2169        }
2170
2171        # If we wrapped, there never was a match.
2172        if ( $start == $end ) {
2173            print {$OUT} "/$pat/: not found\n";
2174        }
2175        next CMD;
2176    }
2177
2178    return;
2179}
2180
2181sub _DB__handle_question_mark_command {
2182    my ($obj) = @_;
2183
2184    # ? - backward pattern search.
2185    if (my ($inpat) = $cmd =~ m#\A\?(.*)\z#) {
2186
2187        # Get the pattern, remove trailing question mark.
2188        $inpat =~ s:([^\\])\?$:$1:;
2189
2190        # If we've got one ...
2191        if ( $inpat ne "" ) {
2192
2193            # Turn off die & warn handlers.
2194            local $SIG{__DIE__};
2195            local $SIG{__WARN__};
2196            eval '$inpat =~ m' . "\a$inpat\a";
2197
2198            if ( $@ ne "" ) {
2199
2200                # Ouch. Not good. Print the error.
2201                print $OUT $@;
2202                next CMD;
2203            }
2204            $obj->pat($inpat);
2205        } ## end if ($inpat ne "")
2206
2207        # Where we are now is where to stop after wraparound.
2208        $end = $start;
2209
2210        # Don't move away from this line.
2211        $incr = -1;
2212
2213        my $pat = $obj->pat;
2214        # Search inside the eval to prevent pattern badness
2215        # from killing us.
2216        eval {
2217            no strict q/vars/;
2218            for (;;) {
2219                # Back up a line.
2220                --$start;
2221
2222                # Wrap if we pass the first line.
2223
2224                $start = $max if ($start <= 0);
2225
2226                # Quit if we get back where we started,
2227                last if ($start == $end);
2228
2229                # Match?
2230                if ($dbline[$start] =~ m/$pat/i) {
2231                    if ($slave_editor) {
2232                        # Yep, follow slave editor requirements.
2233                        print $OUT "\032\032$filename:$start:0\n";
2234                    }
2235                    else {
2236                        # Yep, just print normally.
2237                        print $OUT "$start:\t",$dbline[$start],"\n";
2238                    }
2239
2240                    # Found, so done.
2241                    last;
2242                }
2243            }
2244        };
2245
2246        # Say we failed if the loop never found anything,
2247        if ( $start == $end ) {
2248            print {$OUT} "?$pat?: not found\n";
2249        }
2250        next CMD;
2251    }
2252
2253    return;
2254}
2255
2256sub _DB__handle_restart_and_rerun_commands {
2257    my ($obj) = @_;
2258
2259    my $cmd_cmd = $obj->cmd_verb;
2260    my $cmd_params = $obj->cmd_args;
2261    # R - restart execution.
2262    # rerun - controlled restart execution.
2263    if ($cmd_cmd eq 'rerun' or $cmd_params eq '') {
2264        my @args = ($cmd_cmd eq 'R' ? restart() : rerun($cmd_params));
2265
2266        # Close all non-system fds for a clean restart.  A more
2267        # correct method would be to close all fds that were not
2268        # open when the process started, but this seems to be
2269        # hard.  See "debugger 'R'estart and open database
2270        # connections" on p5p.
2271
2272        my $max_fd = 1024; # default if POSIX can't be loaded
2273        if (eval { require POSIX }) {
2274            eval { $max_fd = POSIX::sysconf(POSIX::_SC_OPEN_MAX()) };
2275        }
2276
2277        if (defined $max_fd) {
2278            foreach ($^F+1 .. $max_fd-1) {
2279                next unless open FD_TO_CLOSE, "<&=$_";
2280                close(FD_TO_CLOSE);
2281            }
2282        }
2283
2284        # And run Perl again.  We use exec() to keep the
2285        # PID stable (and that way $ini_pids is still valid).
2286        exec(@args) or print {$OUT} "exec failed: $!\n";
2287
2288        last CMD;
2289    }
2290
2291    return;
2292}
2293
2294sub _DB__handle_run_command_in_pager_command {
2295    my ($obj) = @_;
2296
2297    if ($cmd =~ m#\A\|\|?\s*[^|]#) {
2298        if ( $pager =~ /^\|/ ) {
2299
2300            # Default pager is into a pipe. Redirect I/O.
2301            open( SAVEOUT, ">&STDOUT" )
2302            || _db_warn("Can't save STDOUT");
2303            open( STDOUT, ">&OUT" )
2304            || _db_warn("Can't redirect STDOUT");
2305        } ## end if ($pager =~ /^\|/)
2306        else {
2307
2308            # Not into a pipe. STDOUT is safe.
2309            open( SAVEOUT, ">&OUT" ) || _db_warn("Can't save DB::OUT");
2310        }
2311
2312        # Fix up environment to record we have less if so.
2313        fix_less();
2314
2315        unless ( $obj->piped(scalar ( open( OUT, $pager ) ) ) ) {
2316
2317            # Couldn't open pipe to pager.
2318            _db_warn("Can't pipe output to '$pager'");
2319            if ( $pager =~ /^\|/ ) {
2320
2321                # Redirect I/O back again.
2322                open( OUT, ">&STDOUT" )    # XXX: lost message
2323                || _db_warn("Can't restore DB::OUT");
2324                open( STDOUT, ">&SAVEOUT" )
2325                || _db_warn("Can't restore STDOUT");
2326                close(SAVEOUT);
2327            } ## end if ($pager =~ /^\|/)
2328            else {
2329
2330                # Redirect I/O. STDOUT already safe.
2331                open( OUT, ">&STDOUT" )    # XXX: lost message
2332                || _db_warn("Can't restore DB::OUT");
2333            }
2334            next CMD;
2335        } ## end unless ($piped = open(OUT,...
2336
2337        # Set up broken-pipe handler if necessary.
2338        $SIG{PIPE} = \&DB::catch
2339        if $pager =~ /^\|/
2340        && ( "" eq $SIG{PIPE} || "DEFAULT" eq $SIG{PIPE} );
2341
2342        _autoflush(\*OUT);
2343        # Save current filehandle, and put it back.
2344        $obj->selected(scalar( select(OUT) ));
2345        # Don't put it back if pager was a pipe.
2346        if ($cmd !~ /\A\|\|/)
2347        {
2348            select($obj->selected());
2349            $obj->selected("");
2350        }
2351
2352        # Trim off the pipe symbols and run the command now.
2353        $cmd =~ s#\A\|+\s*##;
2354        redo PIPE;
2355    }
2356
2357    return;
2358}
2359
2360sub _DB__handle_m_command {
2361    my ($obj) = @_;
2362
2363    if ($cmd =~ s#\Am\s+([\w:]+)\s*\z# #) {
2364        methods($1);
2365        next CMD;
2366    }
2367
2368    # m expr - set up DB::eval to do the work
2369    if ($cmd =~ s#\Am\b# #) {    # Rest gets done by DB::eval()
2370        $onetimeDump = 'methods';   #  method output gets used there
2371    }
2372
2373    return;
2374}
2375
2376sub _DB__at_end_of_every_command {
2377    my ($obj) = @_;
2378
2379    # At the end of every command:
2380    if ($obj->piped) {
2381
2382        # Unhook the pipe mechanism now.
2383        if ( $pager =~ /^\|/ ) {
2384
2385            # No error from the child.
2386            $? = 0;
2387
2388            # we cannot warn here: the handle is missing --tchrist
2389            close(OUT) || print SAVEOUT "\nCan't close DB::OUT\n";
2390
2391            # most of the $? crud was coping with broken cshisms
2392            # $? is explicitly set to 0, so this never runs.
2393            if ($?) {
2394                print SAVEOUT "Pager '$pager' failed: ";
2395                if ( $? == -1 ) {
2396                    print SAVEOUT "shell returned -1\n";
2397                }
2398                elsif ( $? >> 8 ) {
2399                    print SAVEOUT ( $? & 127 )
2400                    ? " (SIG#" . ( $? & 127 ) . ")"
2401                    : "", ( $? & 128 ) ? " -- core dumped" : "", "\n";
2402                }
2403                else {
2404                    print SAVEOUT "status ", ( $? >> 8 ), "\n";
2405                }
2406            } ## end if ($?)
2407
2408            # Reopen filehandle for our output (if we can) and
2409            # restore STDOUT (if we can).
2410            open( OUT, ">&STDOUT" ) || _db_warn("Can't restore DB::OUT");
2411            open( STDOUT, ">&SAVEOUT" )
2412            || _db_warn("Can't restore STDOUT");
2413
2414            # Turn off pipe exception handler if necessary.
2415            $SIG{PIPE} = "DEFAULT" if $SIG{PIPE} eq \&DB::catch;
2416
2417            # Will stop ignoring SIGPIPE if done like nohup(1)
2418            # does SIGINT but Perl doesn't give us a choice.
2419        } ## end if ($pager =~ /^\|/)
2420        else {
2421
2422            # Non-piped "pager". Just restore STDOUT.
2423            open( OUT, ">&SAVEOUT" ) || _db_warn("Can't restore DB::OUT");
2424        }
2425
2426        # Let Readline know about the new filehandles.
2427        reset_IN_OUT( \*IN, \*OUT );
2428
2429        # Close filehandle pager was using, restore the normal one
2430        # if necessary,
2431        close(SAVEOUT);
2432
2433        if ($obj->selected() ne "") {
2434            select($obj->selected);
2435            $obj->selected("");
2436        }
2437
2438        # No pipes now.
2439        $obj->piped("");
2440    } ## end if ($piped)
2441
2442    return;
2443}
2444
2445sub _DB__handle_watch_expressions
2446{
2447    my $self = shift;
2448
2449    if ( $DB::trace & 2 ) {
2450        for my $n (0 .. $#DB::to_watch) {
2451            $DB::evalarg = $DB::to_watch[$n];
2452            local $DB::onetimeDump;    # Tell DB::eval() to not output results
2453
2454            # Fix context DB::eval() wants to return an array, but
2455            # we need a scalar here.
2456            my ($val) = join( "', '", DB::eval(@_) );
2457            $val = ( ( defined $val ) ? "'$val'" : 'undef' );
2458
2459            # Did it change?
2460            if ( $val ne $DB::old_watch[$n] ) {
2461
2462                # Yep! Show the difference, and fake an interrupt.
2463                $DB::signal = 1;
2464                print {$DB::OUT} <<EOP;
2465Watchpoint $n:\t$DB::to_watch[$n] changed:
2466    old value:\t$DB::old_watch[$n]
2467    new value:\t$val
2468EOP
2469                $DB::old_watch[$n] = $val;
2470            } ## end if ($val ne $old_watch...
2471        } ## end for my $n (0 ..
2472    } ## end if ($trace & 2)
2473
2474    return;
2475}
2476
2477# 't' is type.
2478# 'm' is method.
2479# 'v' is the value (i.e: method name or subroutine ref).
2480# 's' is subroutine.
2481my %cmd_lookup =
2482(
2483    '-' => { t => 'm', v => '_handle_dash_command', },
2484    '.' => { t => 's', v => \&_DB__handle_dot_command, },
2485    '=' => { t => 'm', v => '_handle_equal_sign_command', },
2486    'H' => { t => 'm', v => '_handle_H_command', },
2487    'S' => { t => 'm', v => '_handle_S_command', },
2488    'T' => { t => 'm', v => '_handle_T_command', },
2489    'W' => { t => 'm', v => '_handle_W_command', },
2490    'c' => { t => 's', v => \&_DB__handle_c_command, },
2491    'f' => { t => 's', v => \&_DB__handle_f_command, },
2492    'm' => { t => 's', v => \&_DB__handle_m_command, },
2493    'n' => { t => 'm', v => '_handle_n_command', },
2494    'p' => { t => 'm', v => '_handle_p_command', },
2495    'q' => { t => 'm', v => '_handle_q_command', },
2496    'r' => { t => 'm', v => '_handle_r_command', },
2497    's' => { t => 'm', v => '_handle_s_command', },
2498    'save' => { t => 'm', v => '_handle_save_command', },
2499    'source' => { t => 'm', v => '_handle_source_command', },
2500    't' => { t => 'm', v => '_handle_t_command', },
2501    'w' => { t => 'm', v => '_handle_w_command', },
2502    'x' => { t => 'm', v => '_handle_x_command', },
2503    'y' => { t => 's', v => \&_DB__handle_y_command, },
2504    (map { $_ => { t => 'm', v => '_handle_V_command_and_X_command', }, }
2505        ('X', 'V')),
2506    (map { $_ => { t => 'm', v => '_handle_enable_disable_commands', }, }
2507        qw(enable disable)),
2508    (map { $_ =>
2509        { t => 's', v => \&_DB__handle_restart_and_rerun_commands, },
2510        } qw(R rerun)),
2511    (map { $_ => {t => 'm', v => '_handle_cmd_wrapper_commands' }, }
2512        qw(a A b B e E h i l L M o O v w W)),
2513);
2514
2515sub DB {
2516
2517    # lock the debugger and get the thread id for the prompt
2518    lock($DBGR);
2519    my $tid;
2520    my $position;
2521    my ($prefix, $after, $infix);
2522    my $pat;
2523    my $explicit_stop;
2524    my $piped;
2525    my $selected;
2526
2527    if ($ENV{PERL5DB_THREADED}) {
2528        $tid = eval { "[".threads->tid."]" };
2529    }
2530
2531    my $cmd_verb;
2532    my $cmd_args;
2533
2534    my $obj = DB::Obj->new(
2535        {
2536            position => \$position,
2537            prefix => \$prefix,
2538            after => \$after,
2539            explicit_stop => \$explicit_stop,
2540            infix => \$infix,
2541            cmd_args => \$cmd_args,
2542            cmd_verb => \$cmd_verb,
2543            pat => \$pat,
2544            piped => \$piped,
2545            selected => \$selected,
2546        },
2547    );
2548
2549    $obj->_DB_on_init__initialize_globals(@_);
2550
2551    # Preserve current values of $@, $!, $^E, $,, $/, $\, $^W.
2552    # The code being debugged may have altered them.
2553    DB::save();
2554
2555    # Since DB::DB gets called after every line, we can use caller() to
2556    # figure out where we last were executing. Sneaky, eh? This works because
2557    # caller is returning all the extra information when called from the
2558    # debugger.
2559    local ( $package, $filename, $line ) = caller;
2560    $filename_ini = $filename;
2561
2562    # set up the context for DB::eval, so it can properly execute
2563    # code on behalf of the user. We add the package in so that the
2564    # code is eval'ed in the proper package (not in the debugger!).
2565    local $usercontext = _calc_usercontext($package);
2566
2567    # Create an alias to the active file magical array to simplify
2568    # the code here.
2569    local (*dbline) = $main::{ '_<' . $filename };
2570
2571    # Last line in the program.
2572    $max = $#dbline;
2573
2574    # The &-call is here to ascertain the mutability of @_.
2575    &_DB__determine_if_we_should_break;
2576
2577    # Preserve the current stop-or-not, and see if any of the W
2578    # (watch expressions) has changed.
2579    my $was_signal = $signal;
2580
2581    # If we have any watch expressions ...
2582    _DB__handle_watch_expressions($obj);
2583
2584=head2 C<watchfunction()>
2585
2586C<watchfunction()> is a function that can be defined by the user; it is a
2587function which will be run on each entry to C<DB::DB>; it gets the
2588current package, filename, and line as its parameters.
2589
2590The watchfunction can do anything it likes; it is executing in the
2591debugger's context, so it has access to all of the debugger's internal
2592data structures and functions.
2593
2594C<watchfunction()> can control the debugger's actions. Any of the following
2595will cause the debugger to return control to the user's program after
2596C<watchfunction()> executes:
2597
2598=over 4
2599
2600=item *
2601
2602Returning a false value from the C<watchfunction()> itself.
2603
2604=item *
2605
2606Altering C<$single> to a false value.
2607
2608=item *
2609
2610Altering C<$signal> to a false value.
2611
2612=item *
2613
2614Turning off the C<4> bit in C<$trace> (this also disables the
2615check for C<watchfunction()>. This can be done with
2616
2617    $trace &= ~4;
2618
2619=back
2620
2621=cut
2622
2623    # If there's a user-defined DB::watchfunction, call it with the
2624    # current package, filename, and line. The function executes in
2625    # the DB:: package.
2626    if ( $trace & 4 ) {    # User-installed watch
2627        return
2628          if watchfunction( $package, $filename, $line )
2629          and not $single
2630          and not $was_signal
2631          and not( $trace & ~4 );
2632    } ## end if ($trace & 4)
2633
2634    # Pick up any alteration to $signal in the watchfunction, and
2635    # turn off the signal now.
2636    $was_signal = $signal;
2637    $signal     = 0;
2638
2639=head2 GETTING READY TO EXECUTE COMMANDS
2640
2641The debugger decides to take control if single-step mode is on, the
2642C<t> command was entered, or the user generated a signal. If the program
2643has fallen off the end, we set things up so that entering further commands
2644won't cause trouble, and we say that the program is over.
2645
2646=cut
2647
2648    # Make sure that we always print if asked for explicitly regardless
2649    # of $trace_to_depth .
2650    $explicit_stop = ($single || $was_signal);
2651
2652    # Check to see if we should grab control ($single true,
2653    # trace set appropriately, or we got a signal).
2654    if ( $explicit_stop || ( $trace & 1 ) ) {
2655        $obj->_DB__grab_control(@_);
2656    } ## end if ($single || ($trace...
2657
2658=pod
2659
2660If there's an action to be executed for the line we stopped at, execute it.
2661If there are any preprompt actions, execute those as well.
2662
2663=cut
2664
2665    # If there's an action, do it now.
2666    if ($action) {
2667        $evalarg = $action;
2668        # The &-call is here to ascertain the mutability of @_.
2669        &DB::eval;
2670    }
2671
2672    # Are we nested another level (e.g., did we evaluate a function
2673    # that had a breakpoint in it at the debugger prompt)?
2674    if ( $single || $was_signal ) {
2675
2676        # Yes, go down a level.
2677        local $level = $level + 1;
2678
2679        # Do any pre-prompt actions.
2680        foreach $evalarg (@$pre) {
2681            # The &-call is here to ascertain the mutability of @_.
2682            &DB::eval;
2683        }
2684
2685        # Complain about too much recursion if we passed the limit.
2686        if ($single & 4) {
2687            print $OUT $stack_depth . " levels deep in subroutine calls!\n";
2688        }
2689
2690        # The line we're currently on. Set $incr to -1 to stay here
2691        # until we get a command that tells us to advance.
2692        $start = $line;
2693        $incr  = -1;      # for backward motion.
2694
2695        # Tack preprompt debugger actions ahead of any actual input.
2696        @typeahead = ( @$pretype, @typeahead );
2697
2698=head2 WHERE ARE WE?
2699
2700XXX Relocate this section?
2701
2702The debugger normally shows the line corresponding to the current line of
2703execution. Sometimes, though, we want to see the next line, or to move elsewhere
2704in the file. This is done via the C<$incr>, C<$start>, and C<$max> variables.
2705
2706C<$incr> controls by how many lines the I<current> line should move forward
2707after a command is executed. If set to -1, this indicates that the I<current>
2708line shouldn't change.
2709
2710C<$start> is the I<current> line. It is used for things like knowing where to
2711move forwards or backwards from when doing an C<L> or C<-> command.
2712
2713C<$max> tells the debugger where the last line of the current file is. It's
2714used to terminate loops most often.
2715
2716=head2 THE COMMAND LOOP
2717
2718Most of C<DB::DB> is actually a command parsing and dispatch loop. It comes
2719in two parts:
2720
2721=over 4
2722
2723=item *
2724
2725The outer part of the loop, starting at the C<CMD> label. This loop
2726reads a command and then executes it.
2727
2728=item *
2729
2730The inner part of the loop, starting at the C<PIPE> label. This part
2731is wholly contained inside the C<CMD> block and only executes a command.
2732Used to handle commands running inside a pager.
2733
2734=back
2735
2736So why have two labels to restart the loop? Because sometimes, it's easier to
2737have a command I<generate> another command and then re-execute the loop to do
2738the new command. This is faster, but perhaps a bit more convoluted.
2739
2740=cut
2741
2742        # The big command dispatch loop. It keeps running until the
2743        # user yields up control again.
2744        #
2745        # If we have a terminal for input, and we get something back
2746        # from readline(), keep on processing.
2747
2748      CMD:
2749        while (_DB__read_next_cmd($tid))
2750        {
2751
2752            share($cmd);
2753            # ... try to execute the input as debugger commands.
2754
2755            # Don't stop running.
2756            $single = 0;
2757
2758            # No signal is active.
2759            $signal = 0;
2760
2761            # Handle continued commands (ending with \):
2762            if ($cmd =~ s/\\\z/\n/) {
2763                $cmd .= DB::readline("  cont: ");
2764                redo CMD;
2765            }
2766
2767=head4 The null command
2768
2769A newline entered by itself means I<re-execute the last command>. We grab the
2770command out of C<$laststep> (where it was recorded previously), and copy it
2771back into C<$cmd> to be executed below. If there wasn't any previous command,
2772we'll do nothing below (no command will match). If there was, we also save it
2773in the command history and fall through to allow the command parsing to pick
2774it up.
2775
2776=cut
2777
2778            # Empty input means repeat the last command.
2779            if ($cmd eq '') {
2780                $cmd = $laststep;
2781            }
2782            chomp($cmd);    # get rid of the annoying extra newline
2783            if (length($cmd) >= 2) {
2784                push( @hist, $cmd );
2785            }
2786            push( @truehist, $cmd );
2787            share(@hist);
2788            share(@truehist);
2789
2790            # This is a restart point for commands that didn't arrive
2791            # via direct user input. It allows us to 'redo PIPE' to
2792            # re-execute command processing without reading a new command.
2793          PIPE: {
2794                _DB__trim_command_and_return_first_component($obj);
2795
2796=head3 COMMAND ALIASES
2797
2798The debugger can create aliases for commands (these are stored in the
2799C<%alias> hash). Before a command is executed, the command loop looks it up
2800in the alias hash and substitutes the contents of the alias for the command,
2801completely replacing it.
2802
2803=cut
2804
2805                # See if there's an alias for the command, and set it up if so.
2806                if ( $alias{$cmd_verb} ) {
2807
2808                    # Squelch signal handling; we want to keep control here
2809                    # if something goes loco during the alias eval.
2810                    local $SIG{__DIE__};
2811                    local $SIG{__WARN__};
2812
2813                    # This is a command, so we eval it in the DEBUGGER's
2814                    # scope! Otherwise, we can't see the special debugger
2815                    # variables, or get to the debugger's subs. (Well, we
2816                    # _could_, but why make it even more complicated?)
2817                    eval "\$cmd =~ $alias{$cmd_verb}";
2818                    if ($@) {
2819                        local $\ = '';
2820                        print $OUT "Couldn't evaluate '$cmd_verb' alias: $@";
2821                        next CMD;
2822                    }
2823                    _DB__trim_command_and_return_first_component($obj);
2824                } ## end if ($alias{$cmd_verb})
2825
2826=head3 MAIN-LINE COMMANDS
2827
2828All of these commands work up to and after the program being debugged has
2829terminated.
2830
2831=head4 C<q> - quit
2832
2833Quit the debugger. This entails setting the C<$fall_off_end> flag, so we don't
2834try to execute further, cleaning any restart-related stuff out of the
2835environment, and executing with the last value of C<$?>.
2836
2837=cut
2838
2839                # All of these commands were remapped in perl 5.8.0;
2840                # we send them off to the secondary dispatcher (see below).
2841                $obj->_handle_special_char_cmd_wrapper_commands;
2842                _DB__trim_command_and_return_first_component($obj);
2843
2844                if (my $cmd_rec = $cmd_lookup{$cmd_verb}) {
2845                    my $type = $cmd_rec->{t};
2846                    my $val = $cmd_rec->{v};
2847                    if ($type eq 'm') {
2848                        $obj->$val();
2849                    }
2850                    elsif ($type eq 's') {
2851                        $val->($obj);
2852                    }
2853                }
2854
2855=head4 C<t> - trace [n]
2856
2857Turn tracing on or off. Inverts the appropriate bit in C<$trace> (q.v.).
2858If level is specified, set C<$trace_to_depth>.
2859
2860=head4 C<S> - list subroutines matching/not matching a pattern
2861
2862Walks through C<%sub>, checking to see whether or not to print the name.
2863
2864=head4 C<X> - list variables in current package
2865
2866Since the C<V> command actually processes this, just change this to the
2867appropriate C<V> command and fall through.
2868
2869=head4 C<V> - list variables
2870
2871Uses C<dumpvar.pl> to dump out the current values for selected variables.
2872
2873=head4 C<x> - evaluate and print an expression
2874
2875Hands the expression off to C<DB::eval>, setting it up to print the value
2876via C<dumpvar.pl> instead of just printing it directly.
2877
2878=head4 C<m> - print methods
2879
2880Just uses C<DB::methods> to determine what methods are available.
2881
2882=head4 C<f> - switch files
2883
2884Switch to a different filename.
2885
2886=head4 C<.> - return to last-executed line.
2887
2888We set C<$incr> to -1 to indicate that the debugger shouldn't move ahead,
2889and then we look up the line in the magical C<%dbline> hash.
2890
2891=head4 C<-> - back one window
2892
2893We change C<$start> to be one window back; if we go back past the first line,
2894we set it to be the first line. We ser C<$incr> to put us back at the
2895currently-executing line, and then put a C<l $start +> (list one window from
2896C<$start>) in C<$cmd> to be executed later.
2897
2898=head3 PRE-580 COMMANDS VS. NEW COMMANDS: C<a, A, b, B, h, l, L, M, o, O, P, v, w, W, E<lt>, E<lt>E<lt>, E<0x7B>, E<0x7B>E<0x7B>>
2899
2900In Perl 5.8.0, a realignment of the commands was done to fix up a number of
2901problems, most notably that the default case of several commands destroying
2902the user's work in setting watchpoints, actions, etc. We wanted, however, to
2903retain the old commands for those who were used to using them or who preferred
2904them. At this point, we check for the new commands and call C<cmd_wrapper> to
2905deal with them instead of processing them in-line.
2906
2907=head4 C<y> - List lexicals in higher scope
2908
2909Uses C<PadWalker> to find the lexicals supplied as arguments in a scope
2910above the current one and then displays then using C<dumpvar.pl>.
2911
2912=head3 COMMANDS NOT WORKING AFTER PROGRAM ENDS
2913
2914All of the commands below this point don't work after the program being
2915debugged has ended. All of them check to see if the program has ended; this
2916allows the commands to be relocated without worrying about a 'line of
2917demarcation' above which commands can be entered anytime, and below which
2918they can't.
2919
2920=head4 C<n> - single step, but don't trace down into subs
2921
2922Done by setting C<$single> to 2, which forces subs to execute straight through
2923when entered (see C<DB::sub>). We also save the C<n> command in C<$laststep>,
2924so a null command knows what to re-execute.
2925
2926=head4 C<s> - single-step, entering subs
2927
2928Sets C<$single> to 1, which causes C<DB::sub> to continue tracing inside
2929subs. Also saves C<s> as C<$lastcmd>.
2930
2931=head4 C<c> - run continuously, setting an optional breakpoint
2932
2933Most of the code for this command is taken up with locating the optional
2934breakpoint, which is either a subroutine name or a line number. We set
2935the appropriate one-time-break in C<@dbline> and then turn off single-stepping
2936in this and all call levels above this one.
2937
2938=head4 C<r> - return from a subroutine
2939
2940For C<r> to work properly, the debugger has to stop execution again
2941immediately after the return is executed. This is done by forcing
2942single-stepping to be on in the call level above the current one. If
2943we are printing return values when a C<r> is executed, set C<$doret>
2944appropriately, and force us out of the command loop.
2945
2946=head4 C<T> - stack trace
2947
2948Just calls C<DB::print_trace>.
2949
2950=head4 C<w> - List window around current line.
2951
2952Just calls C<DB::cmd_w>.
2953
2954=head4 C<W> - watch-expression processing.
2955
2956Just calls C<DB::cmd_W>.
2957
2958=head4 C</> - search forward for a string in the source
2959
2960We take the argument and treat it as a pattern. If it turns out to be a
2961bad one, we return the error we got from trying to C<eval> it and exit.
2962If not, we create some code to do the search and C<eval> it so it can't
2963mess us up.
2964
2965=cut
2966
2967                _DB__handle_forward_slash_command($obj);
2968
2969=head4 C<?> - search backward for a string in the source
2970
2971Same as for C</>, except the loop runs backwards.
2972
2973=cut
2974
2975                _DB__handle_question_mark_command($obj);
2976
2977=head4 C<$rc> - Recall command
2978
2979Manages the commands in C<@hist> (which is created if C<Term::ReadLine> reports
2980that the terminal supports history). It finds the command required, puts it
2981into C<$cmd>, and redoes the loop to execute it.
2982
2983=cut
2984
2985                # $rc - recall command.
2986                $obj->_handle_rc_recall_command;
2987
2988=head4 C<$sh$sh> - C<system()> command
2989
2990Calls the C<_db_system()> to handle the command. This keeps the C<STDIN> and
2991C<STDOUT> from getting messed up.
2992
2993=cut
2994
2995                $obj->_handle_sh_command;
2996
2997=head4 C<$rc I<pattern> $rc> - Search command history
2998
2999Another command to manipulate C<@hist>: this one searches it with a pattern.
3000If a command is found, it is placed in C<$cmd> and executed via C<redo>.
3001
3002=cut
3003
3004                $obj->_handle_rc_search_history_command;
3005
3006=head4 C<$sh> - Invoke a shell
3007
3008Uses C<_db_system()> to invoke a shell.
3009
3010=cut
3011
3012=head4 C<$sh I<command>> - Force execution of a command in a shell
3013
3014Like the above, but the command is passed to the shell. Again, we use
3015C<_db_system()> to avoid problems with C<STDIN> and C<STDOUT>.
3016
3017=head4 C<H> - display commands in history
3018
3019Prints the contents of C<@hist> (if any).
3020
3021=head4 C<man, doc, perldoc> - look up documentation
3022
3023Just calls C<runman()> to print the appropriate document.
3024
3025=cut
3026
3027                $obj->_handle_doc_command;
3028
3029=head4 C<p> - print
3030
3031Builds a C<print EXPR> expression in the C<$cmd>; this will get executed at
3032the bottom of the loop.
3033
3034=head4 C<=> - define command alias
3035
3036Manipulates C<%alias> to add or list command aliases.
3037
3038=head4 C<source> - read commands from a file.
3039
3040Opens a lexical filehandle and stacks it on C<@cmdfhs>; C<DB::readline> will
3041pick it up.
3042
3043=head4 C<enable> C<disable> - enable or disable breakpoints
3044
3045This enables or disables breakpoints.
3046
3047=head4 C<save> - send current history to a file
3048
3049Takes the complete history, (not the shrunken version you see with C<H>),
3050and saves it to the given filename, so it can be replayed using C<source>.
3051
3052Note that all C<^(save|source)>'s are commented out with a view to minimise recursion.
3053
3054=head4 C<R> - restart
3055
3056Restart the debugger session.
3057
3058=head4 C<rerun> - rerun the current session
3059
3060Return to any given position in the B<true>-history list
3061
3062=head4 C<|, ||> - pipe output through the pager.
3063
3064For C<|>, we save C<OUT> (the debugger's output filehandle) and C<STDOUT>
3065(the program's standard output). For C<||>, we only save C<OUT>. We open a
3066pipe to the pager (restoring the output filehandles if this fails). If this
3067is the C<|> command, we also set up a C<SIGPIPE> handler which will simply
3068set C<$signal>, sending us back into the debugger.
3069
3070We then trim off the pipe symbols and C<redo> the command loop at the
3071C<PIPE> label, causing us to evaluate the command in C<$cmd> without
3072reading another.
3073
3074=cut
3075
3076                # || - run command in the pager, with output to DB::OUT.
3077                _DB__handle_run_command_in_pager_command($obj);
3078
3079=head3 END OF COMMAND PARSING
3080
3081Anything left in C<$cmd> at this point is a Perl expression that we want to
3082evaluate. We'll always evaluate in the user's context, and fully qualify
3083any variables we might want to address in the C<DB> package.
3084
3085=cut
3086
3087            }    # PIPE:
3088
3089            # trace an expression
3090            $cmd =~ s/^t\s/\$DB::trace |= 1;\n/;
3091
3092            # Make sure the flag that says "the debugger's running" is
3093            # still on, to make sure we get control again.
3094            $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd";
3095
3096            # Run *our* eval that executes in the caller's context.
3097            # The &-call is here to ascertain the mutability of @_.
3098            &DB::eval;
3099
3100            # Turn off the one-time-dump stuff now.
3101            if ($onetimeDump) {
3102                $onetimeDump      = undef;
3103                $onetimedumpDepth = undef;
3104            }
3105            elsif ( $term_pid == $$ ) {
3106                eval { # May run under miniperl, when not available...
3107                    STDOUT->flush();
3108                    STDERR->flush();
3109                };
3110
3111                # XXX If this is the master pid, print a newline.
3112                print {$OUT} "\n";
3113            }
3114        } ## end while (($term || &setterm...
3115
3116=head3 POST-COMMAND PROCESSING
3117
3118After each command, we check to see if the command output was piped anywhere.
3119If so, we go through the necessary code to unhook the pipe and go back to
3120our standard filehandles for input and output.
3121
3122=cut
3123
3124        continue {    # CMD:
3125            _DB__at_end_of_every_command($obj);
3126        }    # CMD:
3127
3128=head3 COMMAND LOOP TERMINATION
3129
3130When commands have finished executing, we come here. If the user closed the
3131input filehandle, we turn on C<$fall_off_end> to emulate a C<q> command. We
3132evaluate any post-prompt items. We restore C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>,
3133C<$\>, and C<$^W>, and return a null list as expected by the Perl interpreter.
3134The interpreter will then execute the next line and then return control to us
3135again.
3136
3137=cut
3138
3139        # No more commands? Quit.
3140        $fall_off_end = 1 unless defined $cmd;    # Emulate 'q' on EOF
3141
3142        # Evaluate post-prompt commands.
3143        foreach $evalarg (@$post) {
3144            # The &-call is here to ascertain the mutability of @_.
3145            &DB::eval;
3146        }
3147    }    # if ($single || $signal)
3148
3149    # Put the user's globals back where you found them.
3150    ( $@, $!, $^E, $,, $/, $\, $^W ) = @saved;
3151    ();
3152} ## end sub DB
3153
3154# Because DB::Obj is used above,
3155#
3156#   my $obj = DB::Obj->new(
3157#
3158# The following package declaration must come before that,
3159# or else runtime errors will occur with
3160#
3161#   PERLDB_OPTS="autotrace nonstop"
3162#
3163# ( rt#116771 )
3164BEGIN {
3165
3166package DB::Obj;
3167
3168sub new {
3169    my $class = shift;
3170
3171    my $self = bless {}, $class;
3172
3173    $self->_init(@_);
3174
3175    return $self;
3176}
3177
3178sub _init {
3179    my ($self, $args) = @_;
3180
3181    %{$self} = (%$self, %$args);
3182
3183    return;
3184}
3185
3186{
3187    no strict 'refs';
3188    foreach my $slot_name (qw(
3189        after explicit_stop infix pat piped position prefix selected cmd_verb
3190        cmd_args
3191        )) {
3192        my $slot = $slot_name;
3193        *{$slot} = sub {
3194            my $self = shift;
3195
3196            if (@_) {
3197                ${ $self->{$slot} } = shift;
3198            }
3199
3200            return ${ $self->{$slot} };
3201        };
3202
3203        *{"append_to_$slot"} = sub {
3204            my $self = shift;
3205            my $s = shift;
3206
3207            return $self->$slot($self->$slot . $s);
3208        };
3209    }
3210}
3211
3212sub _DB_on_init__initialize_globals
3213{
3214    my $self = shift;
3215
3216    # Check for whether we should be running continuously or not.
3217    # _After_ the perl program is compiled, $single is set to 1:
3218    if ( $single and not $second_time++ ) {
3219
3220        # Options say run non-stop. Run until we get an interrupt.
3221        if ($runnonstop) {    # Disable until signal
3222                # If there's any call stack in place, turn off single
3223                # stepping into subs throughout the stack.
3224            for my $i (0 .. $stack_depth) {
3225                $stack[ $i ] &= ~1;
3226            }
3227
3228            # And we are now no longer in single-step mode.
3229            $single = 0;
3230
3231            # If we simply returned at this point, we wouldn't get
3232            # the trace info. Fall on through.
3233            # return;
3234        } ## end if ($runnonstop)
3235
3236        elsif ($ImmediateStop) {
3237
3238            # We are supposed to stop here; XXX probably a break.
3239            $ImmediateStop = 0;    # We've processed it; turn it off
3240            $signal        = 1;    # Simulate an interrupt to force
3241                                   # us into the command loop
3242        }
3243    } ## end if ($single and not $second_time...
3244
3245    # If we're in single-step mode, or an interrupt (real or fake)
3246    # has occurred, turn off non-stop mode.
3247    $runnonstop = 0 if $single or $signal;
3248
3249    return;
3250}
3251
3252sub _my_print_lineinfo
3253{
3254    my ($self, $i, $incr_pos) = @_;
3255
3256    if ($frame) {
3257        # Print it indented if tracing is on.
3258        DB::print_lineinfo( ' ' x $stack_depth,
3259            "$i:\t$DB::dbline[$i]" . $self->after );
3260    }
3261    else {
3262        DB::depth_print_lineinfo($self->explicit_stop, $incr_pos);
3263    }
3264}
3265
3266sub _curr_line {
3267    return $DB::dbline[$line];
3268}
3269
3270sub _is_full {
3271    my ($self, $letter) = @_;
3272
3273    return ($DB::cmd eq $letter);
3274}
3275
3276sub _DB__grab_control
3277{
3278    my $self = shift;
3279
3280    # Yes, grab control.
3281    if ($slave_editor) {
3282
3283        # Tell the editor to update its position.
3284        $self->position("\032\032${DB::filename}:$line:0\n");
3285        DB::print_lineinfo($self->position());
3286    }
3287
3288=pod
3289
3290Special check: if we're in package C<DB::fake>, we've gone through the
3291C<END> block at least once. We set up everything so that we can continue
3292to enter commands and have a valid context to be in.
3293
3294=cut
3295
3296    elsif ( $DB::package eq 'DB::fake' ) {
3297
3298        # Fallen off the end already.
3299        if (!$DB::term) {
3300            DB::setterm();
3301        }
3302
3303        DB::print_help(<<EOP);
3304Debugged program terminated.  Use B<q> to quit or B<R> to restart,
3305use B<o> I<inhibit_exit> to avoid stopping after program termination,
3306B<h q>, B<h R> or B<h o> to get additional info.
3307EOP
3308
3309        # Set the DB::eval context appropriately.
3310        $DB::package     = 'main';
3311        $DB::usercontext = DB::_calc_usercontext($DB::package);
3312    } ## end elsif ($package eq 'DB::fake')
3313
3314=pod
3315
3316If the program hasn't finished executing, we scan forward to the
3317next executable line, print that out, build the prompt from the file and line
3318number information, and print that.
3319
3320=cut
3321
3322    else {
3323
3324
3325        # Still somewhere in the midst of execution. Set up the
3326        #  debugger prompt.
3327        $DB::sub =~ s/\'/::/;    # Swap Perl 4 package separators (') to
3328                             # Perl 5 ones (sorry, we don't print Klingon
3329                             #module names)
3330
3331        $self->prefix($DB::sub =~ /::/ ? "" : ($DB::package . '::'));
3332        $self->append_to_prefix( "$DB::sub(${DB::filename}:" );
3333        $self->after( $self->_curr_line =~ /\n$/ ? '' : "\n" );
3334
3335        # Break up the prompt if it's really long.
3336        if ( length($self->prefix()) > 30 ) {
3337            $self->position($self->prefix . "$line):\n$line:\t" . $self->_curr_line . $self->after);
3338            $self->prefix("");
3339            $self->infix(":\t");
3340        }
3341        else {
3342            $self->infix("):\t");
3343            $self->position(
3344                $self->prefix . $line. $self->infix
3345                . $self->_curr_line . $self->after
3346            );
3347        }
3348
3349        # Print current line info, indenting if necessary.
3350        $self->_my_print_lineinfo($line, $self->position);
3351
3352        my $i;
3353        my $line_i = sub { return $DB::dbline[$i]; };
3354
3355        # Scan forward, stopping at either the end or the next
3356        # unbreakable line.
3357        for ( $i = $line + 1 ; $i <= $DB::max && $line_i->() == 0 ; ++$i )
3358        {    #{ vi
3359
3360            # Drop out on null statements, block closers, and comments.
3361            last if $line_i->() =~ /^\s*[\;\}\#\n]/;
3362
3363            # Drop out if the user interrupted us.
3364            last if $signal;
3365
3366            # Append a newline if the line doesn't have one. Can happen
3367            # in eval'ed text, for instance.
3368            $self->after( $line_i->() =~ /\n$/ ? '' : "\n" );
3369
3370            # Next executable line.
3371            my $incr_pos = $self->prefix . $i . $self->infix . $line_i->()
3372                . $self->after;
3373            $self->append_to_position($incr_pos);
3374            $self->_my_print_lineinfo($i, $incr_pos);
3375        } ## end for ($i = $line + 1 ; $i...
3376    } ## end else [ if ($slave_editor)
3377
3378    return;
3379}
3380
3381sub _handle_t_command {
3382    my $self = shift;
3383
3384    my $levels = $self->cmd_args();
3385
3386    if ((!length($levels)) or ($levels !~ /\D/)) {
3387        $trace ^= 1;
3388        local $\ = '';
3389        $DB::trace_to_depth = $levels ? $stack_depth + $levels : 1E9;
3390        print {$OUT} "Trace = "
3391        . ( ( $trace & 1 )
3392            ? ( $levels ? "on (to level $DB::trace_to_depth)" : "on" )
3393            : "off" ) . "\n";
3394        next CMD;
3395    }
3396
3397    return;
3398}
3399
3400
3401sub _handle_S_command {
3402    my $self = shift;
3403
3404    if (my ($print_all_subs, $should_reverse, $Spatt)
3405        = $self->cmd_args =~ /\A((!)?(.+))?\z/) {
3406        # $Spatt is the pattern (if any) to use.
3407        # Reverse scan?
3408        my $Srev     = defined $should_reverse;
3409        # No args - print all subs.
3410        my $Snocheck = !defined $print_all_subs;
3411
3412        # Need to make these sane here.
3413        local $\ = '';
3414        local $, = '';
3415
3416        # Search through the debugger's magical hash of subs.
3417        # If $nocheck is true, just print the sub name.
3418        # Otherwise, check it against the pattern. We then use
3419        # the XOR trick to reverse the condition as required.
3420        foreach $subname ( sort( keys %sub ) ) {
3421            if ( $Snocheck or $Srev ^ ( $subname =~ /$Spatt/ ) ) {
3422                print $OUT $subname, "\n";
3423            }
3424        }
3425        next CMD;
3426    }
3427
3428    return;
3429}
3430
3431sub _handle_V_command_and_X_command {
3432    my $self = shift;
3433
3434    $DB::cmd =~ s/^X\b/V $DB::package/;
3435
3436    # Bare V commands get the currently-being-debugged package
3437    # added.
3438    if ($self->_is_full('V')) {
3439        $DB::cmd = "V $DB::package";
3440    }
3441
3442    # V - show variables in package.
3443    if (my ($new_packname, $new_vars_str) =
3444        $DB::cmd =~ /\AV\b\s*(\S+)\s*(.*)/) {
3445
3446        # Save the currently selected filehandle and
3447        # force output to debugger's filehandle (dumpvar
3448        # just does "print" for output).
3449        my $savout = select($OUT);
3450
3451        # Grab package name and variables to dump.
3452        $packname = $new_packname;
3453        my @vars     = split( ' ', $new_vars_str );
3454
3455        # If main::dumpvar isn't here, get it.
3456        do 'dumpvar.pl' || die $@ unless defined &main::dumpvar;
3457        if ( defined &main::dumpvar ) {
3458
3459            # We got it. Turn off subroutine entry/exit messages
3460            # for the moment, along with return values.
3461            local $frame = 0;
3462            local $doret = -2;
3463
3464            # must detect sigpipe failures  - not catching
3465            # then will cause the debugger to die.
3466            eval {
3467                main::dumpvar(
3468                    $packname,
3469                    defined $option{dumpDepth}
3470                    ? $option{dumpDepth}
3471                    : -1,    # assume -1 unless specified
3472                    @vars
3473                );
3474            };
3475
3476            # The die doesn't need to include the $@, because
3477            # it will automatically get propagated for us.
3478            if ($@) {
3479                die unless $@ =~ /dumpvar print failed/;
3480            }
3481        } ## end if (defined &main::dumpvar)
3482        else {
3483
3484            # Couldn't load dumpvar.
3485            print $OUT "dumpvar.pl not available.\n";
3486        }
3487
3488        # Restore the output filehandle, and go round again.
3489        select($savout);
3490        next CMD;
3491    }
3492
3493    return;
3494}
3495
3496sub _handle_dash_command {
3497    my $self = shift;
3498
3499    if ($self->_is_full('-')) {
3500
3501        # back up by a window; go to 1 if back too far.
3502        $start -= $incr + $window + 1;
3503        $start = 1 if $start <= 0;
3504        $incr  = $window - 1;
3505
3506        # Generate and execute a "l +" command (handled below).
3507        $DB::cmd = 'l ' . ($start) . '+';
3508        redo CMD;
3509    }
3510    return;
3511}
3512
3513sub _n_or_s_commands_generic {
3514    my ($self, $new_val) = @_;
3515    # n - next
3516    next CMD if DB::_DB__is_finished();
3517
3518    # Single step, but don't enter subs.
3519    $single = $new_val;
3520
3521    # Save for empty command (repeat last).
3522    $laststep = $DB::cmd;
3523    last CMD;
3524}
3525
3526sub _n_or_s {
3527    my ($self, $letter, $new_val) = @_;
3528
3529    if ($self->_is_full($letter)) {
3530        $self->_n_or_s_commands_generic($new_val);
3531    }
3532    else {
3533        $self->_n_or_s_and_arg_commands_generic($letter, $new_val);
3534    }
3535
3536    return;
3537}
3538
3539sub _handle_n_command {
3540    my $self = shift;
3541
3542    return $self->_n_or_s('n', 2);
3543}
3544
3545sub _handle_s_command {
3546    my $self = shift;
3547
3548    return $self->_n_or_s('s', 1);
3549}
3550
3551sub _handle_r_command {
3552    my $self = shift;
3553
3554    # r - return from the current subroutine.
3555    if ($self->_is_full('r')) {
3556
3557        # Can't do anything if the program's over.
3558        next CMD if DB::_DB__is_finished();
3559
3560        # Turn on stack trace.
3561        $stack[$stack_depth] |= 1;
3562
3563        # Print return value unless the stack is empty.
3564        $doret = $option{PrintRet} ? $stack_depth - 1 : -2;
3565        last CMD;
3566    }
3567
3568    return;
3569}
3570
3571sub _handle_T_command {
3572    my $self = shift;
3573
3574    if ($self->_is_full('T')) {
3575        DB::print_trace( $OUT, 1 );    # skip DB
3576        next CMD;
3577    }
3578
3579    return;
3580}
3581
3582sub _handle_w_command {
3583    my $self = shift;
3584
3585    DB::cmd_w( 'w', $self->cmd_args() );
3586    next CMD;
3587
3588    return;
3589}
3590
3591sub _handle_W_command {
3592    my $self = shift;
3593
3594    if (my $arg = $self->cmd_args) {
3595        DB::cmd_W( 'W', $arg );
3596        next CMD;
3597    }
3598
3599    return;
3600}
3601
3602sub _handle_rc_recall_command {
3603    my $self = shift;
3604
3605    # $rc - recall command.
3606    if (my ($minus, $arg) = $DB::cmd =~ m#\A$rc+\s*(-)?(\d+)?\z#) {
3607
3608        # No arguments, take one thing off history.
3609        pop(@hist) if length($DB::cmd) > 1;
3610
3611        # Relative (- found)?
3612        #  Y - index back from most recent (by 1 if bare minus)
3613        #  N - go to that particular command slot or the last
3614        #      thing if nothing following.
3615
3616        $self->cmd_verb(
3617            scalar($minus ? ( $#hist - ( $arg || 1 ) ) : ( $arg || $#hist ))
3618        );
3619
3620        # Pick out the command desired.
3621        $DB::cmd = $hist[$self->cmd_verb];
3622
3623        # Print the command to be executed and restart the loop
3624        # with that command in the buffer.
3625        print {$OUT} $DB::cmd, "\n";
3626        redo CMD;
3627    }
3628
3629    return;
3630}
3631
3632sub _handle_rc_search_history_command {
3633    my $self = shift;
3634
3635    # $rc pattern $rc - find a command in the history.
3636    if (my ($arg) = $DB::cmd =~ /\A$rc([^$rc].*)\z/) {
3637
3638        # Create the pattern to use.
3639        my $pat = "^$arg";
3640        $self->pat($pat);
3641
3642        # Toss off last entry if length is >1 (and it always is).
3643        pop(@hist) if length($DB::cmd) > 1;
3644
3645        my $i;
3646
3647        # Look backward through the history.
3648        SEARCH_HIST:
3649        for ( $i = $#hist ; $i ; --$i ) {
3650            # Stop if we find it.
3651            last SEARCH_HIST if $hist[$i] =~ /$pat/;
3652        }
3653
3654        if ( !$i ) {
3655
3656            # Never found it.
3657            print $OUT "No such command!\n\n";
3658            next CMD;
3659        }
3660
3661        # Found it. Put it in the buffer, print it, and process it.
3662        $DB::cmd = $hist[$i];
3663        print $OUT $DB::cmd, "\n";
3664        redo CMD;
3665    }
3666
3667    return;
3668}
3669
3670sub _handle_H_command {
3671    my $self = shift;
3672
3673    if ($self->cmd_args =~ m#\A\*#) {
3674        @hist = @truehist = ();
3675        print $OUT "History cleansed\n";
3676        next CMD;
3677    }
3678
3679    if (my ($num) = $self->cmd_args =~ /\A(?:-(\d+))?/) {
3680
3681        # Anything other than negative numbers is ignored by
3682        # the (incorrect) pattern, so this test does nothing.
3683        $end = $num ? ( $#hist - $num ) : 0;
3684
3685        # Set to the minimum if less than zero.
3686        $hist = 0 if $hist < 0;
3687
3688        # Start at the end of the array.
3689        # Stay in while we're still above the ending value.
3690        # Tick back by one each time around the loop.
3691        my $i;
3692
3693        for ( $i = $#hist ; $i > $end ; $i-- ) {
3694
3695            # Print the command  unless it has no arguments.
3696            print $OUT "$i: ", $hist[$i], "\n"
3697            unless $hist[$i] =~ /^.?$/;
3698        }
3699
3700        next CMD;
3701    }
3702
3703    return;
3704}
3705
3706sub _handle_doc_command {
3707    my $self = shift;
3708
3709    # man, perldoc, doc - show manual pages.
3710    if (my ($man_page)
3711        = $DB::cmd =~ /\A(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?\z/) {
3712        DB::runman($man_page);
3713        next CMD;
3714    }
3715
3716    return;
3717}
3718
3719sub _handle_p_command {
3720    my $self = shift;
3721
3722    my $print_cmd = 'print {$DB::OUT} ';
3723    # p - print (no args): print $_.
3724    if ($self->_is_full('p')) {
3725        $DB::cmd = $print_cmd . '$_';
3726    }
3727    else {
3728        # p - print the given expression.
3729        $DB::cmd =~ s/\Ap\b/$print_cmd /;
3730    }
3731
3732    return;
3733}
3734
3735sub _handle_equal_sign_command {
3736    my $self = shift;
3737
3738    if ($DB::cmd =~ s/\A=\s*//) {
3739        my @keys;
3740        if ( length $DB::cmd == 0 ) {
3741
3742            # No args, get current aliases.
3743            @keys = sort keys %alias;
3744        }
3745        elsif ( my ( $k, $v ) = ( $DB::cmd =~ /^(\S+)\s+(\S.*)/ ) ) {
3746
3747            # Creating a new alias. $k is alias name, $v is
3748            # alias value.
3749
3750            # can't use $_ or kill //g state
3751            for my $x ( $k, $v ) {
3752
3753                # Escape "alarm" characters.
3754                $x =~ s/\a/\\a/g;
3755            }
3756
3757            # Substitute key for value, using alarm chars
3758            # as separators (which is why we escaped them in
3759            # the command).
3760            $alias{$k} = "s\a$k\a$v\a";
3761
3762            # Turn off standard warn and die behavior.
3763            local $SIG{__DIE__};
3764            local $SIG{__WARN__};
3765
3766            # Is it valid Perl?
3767            unless ( eval "sub { s\a$k\a$v\a }; 1" ) {
3768
3769                # Nope. Bad alias. Say so and get out.
3770                print $OUT "Can't alias $k to $v: $@\n";
3771                delete $alias{$k};
3772                next CMD;
3773            }
3774
3775            # We'll only list the new one.
3776            @keys = ($k);
3777        } ## end elsif (my ($k, $v) = ($DB::cmd...
3778
3779        # The argument is the alias to list.
3780        else {
3781            @keys = ($DB::cmd);
3782        }
3783
3784        # List aliases.
3785        for my $k (@keys) {
3786
3787            # Messy metaquoting: Trim the substitution code off.
3788            # We use control-G as the delimiter because it's not
3789            # likely to appear in the alias.
3790            if ( ( my $v = $alias{$k} ) =~ ss\a$k\a(.*)\a$1 ) {
3791
3792                # Print the alias.
3793                print $OUT "$k\t= $1\n";
3794            }
3795            elsif ( defined $alias{$k} ) {
3796
3797                # Couldn't trim it off; just print the alias code.
3798                print $OUT "$k\t$alias{$k}\n";
3799            }
3800            else {
3801
3802                # No such, dude.
3803                print "No alias for $k\n";
3804            }
3805        } ## end for my $k (@keys)
3806        next CMD;
3807    }
3808
3809    return;
3810}
3811
3812sub _handle_source_command {
3813    my $self = shift;
3814
3815    # source - read commands from a file (or pipe!) and execute.
3816    if (my $sourced_fn = $self->cmd_args) {
3817        if ( open my $fh, $sourced_fn ) {
3818
3819            # Opened OK; stick it in the list of file handles.
3820            push @cmdfhs, $fh;
3821        }
3822        else {
3823
3824            # Couldn't open it.
3825            DB::_db_warn("Can't execute '$sourced_fn': $!\n");
3826        }
3827        next CMD;
3828    }
3829
3830    return;
3831}
3832
3833sub _handle_enable_disable_commands {
3834    my $self = shift;
3835
3836    my $which_cmd = $self->cmd_verb;
3837    my $position = $self->cmd_args;
3838
3839    if ($position !~ /\s/) {
3840        my ($fn, $line_num);
3841        if ($position =~ m{\A\d+\z})
3842        {
3843            $fn = $DB::filename;
3844            $line_num = $position;
3845        }
3846        elsif (my ($new_fn, $new_line_num)
3847            = $position =~ m{\A(.*):(\d+)\z}) {
3848            ($fn, $line_num) = ($new_fn, $new_line_num);
3849        }
3850        else
3851        {
3852            DB::_db_warn("Wrong spec for enable/disable argument.\n");
3853        }
3854
3855        if (defined($fn)) {
3856            if (DB::_has_breakpoint_data_ref($fn, $line_num)) {
3857                DB::_set_breakpoint_enabled_status($fn, $line_num,
3858                    ($which_cmd eq 'enable' ? 1 : '')
3859                );
3860            }
3861            else {
3862                DB::_db_warn("No breakpoint set at ${fn}:${line_num}\n");
3863            }
3864        }
3865
3866        next CMD;
3867    }
3868
3869    return;
3870}
3871
3872sub _handle_save_command {
3873    my $self = shift;
3874
3875    if (my $new_fn = $self->cmd_args) {
3876        my $filename = $new_fn || '.perl5dbrc';    # default?
3877        if ( open my $fh, '>', $filename ) {
3878
3879            # chomp to remove extraneous newlines from source'd files
3880            chomp( my @truelist =
3881                map { m/\A\s*(save|source)/ ? "#$_" : $_ }
3882                @truehist );
3883            print {$fh} join( "\n", @truelist );
3884            print "commands saved in $filename\n";
3885        }
3886        else {
3887            DB::_db_warn("Can't save debugger commands in '$new_fn': $!\n");
3888        }
3889        next CMD;
3890    }
3891
3892    return;
3893}
3894
3895sub _n_or_s_and_arg_commands_generic {
3896    my ($self, $letter, $new_val) = @_;
3897
3898    # s - single-step. Remember the last command was 's'.
3899    if ($DB::cmd =~ s#\A\Q$letter\E\s#\$DB::single = $new_val;\n#) {
3900        $laststep = $letter;
3901    }
3902
3903    return;
3904}
3905
3906sub _handle_sh_command {
3907    my $self = shift;
3908
3909    # $sh$sh - run a shell command (if it's all ASCII).
3910    # Can't run shell commands with Unicode in the debugger, hmm.
3911    my $my_cmd = $DB::cmd;
3912    if ($my_cmd =~ m#\A$sh#gms) {
3913
3914        if ($my_cmd =~ m#\G\z#cgms) {
3915            # Run the user's shell. If none defined, run Bourne.
3916            # We resume execution when the shell terminates.
3917            DB::_db_system( $ENV{SHELL} || "/bin/sh" );
3918            next CMD;
3919        }
3920        elsif ($my_cmd =~ m#\G$sh\s*(.*)#cgms) {
3921            # System it.
3922            DB::_db_system($1);
3923            next CMD;
3924        }
3925        elsif ($my_cmd =~ m#\G\s*(.*)#cgms) {
3926            DB::_db_system( $ENV{SHELL} || "/bin/sh", "-c", $1 );
3927            next CMD;
3928        }
3929    }
3930}
3931
3932sub _handle_x_command {
3933    my $self = shift;
3934
3935    if ($DB::cmd =~ s#\Ax\b# #) {    # Remainder gets done by DB::eval()
3936        $onetimeDump = 'dump';    # main::dumpvar shows the output
3937
3938        # handle special  "x 3 blah" syntax XXX propagate
3939        # doc back to special variables.
3940        if ( $DB::cmd =~ s#\A\s*(\d+)(?=\s)# #) {
3941            $onetimedumpDepth = $1;
3942        }
3943    }
3944
3945    return;
3946}
3947
3948sub _handle_q_command {
3949    my $self = shift;
3950
3951    if ($self->_is_full('q')) {
3952        $fall_off_end = 1;
3953        DB::clean_ENV();
3954        exit $?;
3955    }
3956
3957    return;
3958}
3959
3960sub _handle_cmd_wrapper_commands {
3961    my $self = shift;
3962
3963    DB::cmd_wrapper( $self->cmd_verb, $self->cmd_args, $line );
3964    next CMD;
3965}
3966
3967sub _handle_special_char_cmd_wrapper_commands {
3968    my $self = shift;
3969
3970    # All of these commands were remapped in perl 5.8.0;
3971    # we send them off to the secondary dispatcher (see below).
3972    if (my ($cmd_letter, $my_arg) = $DB::cmd =~ /\A([<>\{]{1,2})\s*(.*)/so) {
3973        DB::cmd_wrapper( $cmd_letter, $my_arg, $line );
3974        next CMD;
3975    }
3976
3977    return;
3978}
3979
3980} ## end DB::Obj
3981
3982package DB;
3983
3984# The following code may be executed now:
3985# BEGIN {warn 4}
3986
3987=head2 sub
3988
3989C<sub> is called whenever a subroutine call happens in the program being
3990debugged. The variable C<$DB::sub> contains the name of the subroutine
3991being called.
3992
3993The core function of this subroutine is to actually call the sub in the proper
3994context, capturing its output. This of course causes C<DB::DB> to get called
3995again, repeating until the subroutine ends and returns control to C<DB::sub>
3996again. Once control returns, C<DB::sub> figures out whether or not to dump the
3997return value, and returns its captured copy of the return value as its own
3998return value. The value then feeds back into the program being debugged as if
3999C<DB::sub> hadn't been there at all.
4000
4001C<sub> does all the work of printing the subroutine entry and exit messages
4002enabled by setting C<$frame>. It notes what sub the autoloader got called for,
4003and also prints the return value if needed (for the C<r> command and if
4004the 16 bit is set in C<$frame>).
4005
4006It also tracks the subroutine call depth by saving the current setting of
4007C<$single> in the C<@stack> package global; if this exceeds the value in
4008C<$deep>, C<sub> automatically turns on printing of the current depth by
4009setting the C<4> bit in C<$single>. In any case, it keeps the current setting
4010of stop/don't stop on entry to subs set as it currently is set.
4011
4012=head3 C<caller()> support
4013
4014If C<caller()> is called from the package C<DB>, it provides some
4015additional data, in the following order:
4016
4017=over 4
4018
4019=item * C<$package>
4020
4021The package name the sub was in
4022
4023=item * C<$filename>
4024
4025The filename it was defined in
4026
4027=item * C<$line>
4028
4029The line number it was defined on
4030
4031=item * C<$subroutine>
4032
4033The subroutine name; C<(eval)> if an C<eval>().
4034
4035=item * C<$hasargs>
4036
40371 if it has arguments, 0 if not
4038
4039=item * C<$wantarray>
4040
40411 if array context, 0 if scalar context
4042
4043=item * C<$evaltext>
4044
4045The C<eval>() text, if any (undefined for C<eval BLOCK>)
4046
4047=item * C<$is_require>
4048
4049frame was created by a C<use> or C<require> statement
4050
4051=item * C<$hints>
4052
4053pragma information; subject to change between versions
4054
4055=item * C<$bitmask>
4056
4057pragma information; subject to change between versions
4058
4059=item * C<@DB::args>
4060
4061arguments with which the subroutine was invoked
4062
4063=back
4064
4065=cut
4066
4067use vars qw($deep);
4068
4069# We need to fully qualify the name ("DB::sub") to make "use strict;"
4070# happy. -- Shlomi Fish
4071
4072sub _indent_print_line_info {
4073    my ($offset, $str) = @_;
4074
4075    print_lineinfo( ' ' x ($stack_depth - $offset), $str);
4076
4077    return;
4078}
4079
4080sub _print_frame_message {
4081    my ($al) = @_;
4082
4083    if ($frame) {
4084        if ($frame & 4) {   # Extended frame entry message
4085            _indent_print_line_info(-1, "in  ");
4086
4087            # Why -1? But it works! :-(
4088            # Because print_trace will call add 1 to it and then call
4089            # dump_trace; this results in our skipping -1+1 = 0 stack frames
4090            # in dump_trace.
4091            #
4092            # Now it's 0 because we extracted a function.
4093            print_trace( $LINEINFO, 0, 1, 1, "$sub$al" );
4094        }
4095        else {
4096            _indent_print_line_info(-1, "entering $sub$al\n" );
4097        }
4098    }
4099
4100    return;
4101}
4102
4103sub DB::sub {
4104    # lock ourselves under threads
4105    lock($DBGR);
4106
4107    # Whether or not the autoloader was running, a scalar to put the
4108    # sub's return value in (if needed), and an array to put the sub's
4109    # return value in (if needed).
4110    my ( $al, $ret, @ret ) = "";
4111    if ($sub eq 'threads::new' && $ENV{PERL5DB_THREADED}) {
4112        print "creating new thread\n";
4113    }
4114
4115    # If the last ten characters are '::AUTOLOAD', note we've traced
4116    # into AUTOLOAD for $sub.
4117    if ( length($sub) > 10 && substr( $sub, -10, 10 ) eq '::AUTOLOAD' ) {
4118        no strict 'refs';
4119        $al = " for $$sub" if defined $$sub;
4120    }
4121
4122    # We stack the stack pointer and then increment it to protect us
4123    # from a situation that might unwind a whole bunch of call frames
4124    # at once. Localizing the stack pointer means that it will automatically
4125    # unwind the same amount when multiple stack frames are unwound.
4126    local $stack_depth = $stack_depth + 1;    # Protect from non-local exits
4127
4128    # Expand @stack.
4129    $#stack = $stack_depth;
4130
4131    # Save current single-step setting.
4132    $stack[-1] = $single;
4133
4134    # Turn off all flags except single-stepping.
4135    $single &= 1;
4136
4137    # If we've gotten really deeply recursed, turn on the flag that will
4138    # make us stop with the 'deep recursion' message.
4139    $single |= 4 if $stack_depth == $deep;
4140
4141    # If frame messages are on ...
4142
4143    _print_frame_message($al);
4144    # standard frame entry message
4145
4146    my $print_exit_msg = sub {
4147        # Check for exit trace messages...
4148        if ($frame & 2)
4149        {
4150            if ($frame & 4)    # Extended exit message
4151            {
4152                _indent_print_line_info(0, "out ");
4153                print_trace( $LINEINFO, 0, 1, 1, "$sub$al" );
4154            }
4155            else
4156            {
4157                _indent_print_line_info(0, "exited $sub$al\n" );
4158            }
4159        }
4160        return;
4161    };
4162
4163    # Determine the sub's return type, and capture appropriately.
4164    if (wantarray) {
4165
4166        # Called in array context. call sub and capture output.
4167        # DB::DB will recursively get control again if appropriate; we'll come
4168        # back here when the sub is finished.
4169        {
4170            no strict 'refs';
4171            @ret = &$sub;
4172        }
4173
4174        # Pop the single-step value back off the stack.
4175        $single |= $stack[ $stack_depth-- ];
4176
4177        $print_exit_msg->();
4178
4179        # Print the return info if we need to.
4180        if ( $doret eq $stack_depth or $frame & 16 ) {
4181
4182            # Turn off output record separator.
4183            local $\ = '';
4184            my $fh = ( $doret eq $stack_depth ? $OUT : $LINEINFO );
4185
4186            # Indent if we're printing because of $frame tracing.
4187            if ($frame & 16)
4188            {
4189                print {$fh} ' ' x $stack_depth;
4190            }
4191
4192            # Print the return value.
4193            print {$fh} "list context return from $sub:\n";
4194            dumpit( $fh, \@ret );
4195
4196            # And don't print it again.
4197            $doret = -2;
4198        } ## end if ($doret eq $stack_depth...
4199            # And we have to return the return value now.
4200        @ret;
4201    } ## end if (wantarray)
4202
4203    # Scalar context.
4204    else {
4205        if ( defined wantarray ) {
4206            no strict 'refs';
4207            # Save the value if it's wanted at all.
4208            $ret = &$sub;
4209        }
4210        else {
4211            no strict 'refs';
4212            # Void return, explicitly.
4213            &$sub;
4214            undef $ret;
4215        }
4216
4217        # Pop the single-step value off the stack.
4218        $single |= $stack[ $stack_depth-- ];
4219
4220        # If we're doing exit messages...
4221        $print_exit_msg->();
4222
4223        # If we are supposed to show the return value... same as before.
4224        if ( $doret eq $stack_depth or $frame & 16 and defined wantarray ) {
4225            local $\ = '';
4226            my $fh = ( $doret eq $stack_depth ? $OUT : $LINEINFO );
4227            print $fh ( ' ' x $stack_depth ) if $frame & 16;
4228            print $fh (
4229                defined wantarray
4230                ? "scalar context return from $sub: "
4231                : "void context return from $sub\n"
4232            );
4233            dumpit( $fh, $ret ) if defined wantarray;
4234            $doret = -2;
4235        } ## end if ($doret eq $stack_depth...
4236
4237        # Return the appropriate scalar value.
4238        $ret;
4239    } ## end else [ if (wantarray)
4240} ## end sub _sub
4241
4242sub lsub : lvalue {
4243
4244    no strict 'refs';
4245
4246    # lock ourselves under threads
4247    lock($DBGR);
4248
4249    # Whether or not the autoloader was running, a scalar to put the
4250    # sub's return value in (if needed), and an array to put the sub's
4251    # return value in (if needed).
4252    my ( $al, $ret, @ret ) = "";
4253    if ($sub =~ /^threads::new$/ && $ENV{PERL5DB_THREADED}) {
4254        print "creating new thread\n";
4255    }
4256
4257    # If the last ten characters are C'::AUTOLOAD', note we've traced
4258    # into AUTOLOAD for $sub.
4259    if ( length($sub) > 10 && substr( $sub, -10, 10 ) eq '::AUTOLOAD' ) {
4260        $al = " for $$sub";
4261    }
4262
4263    # We stack the stack pointer and then increment it to protect us
4264    # from a situation that might unwind a whole bunch of call frames
4265    # at once. Localizing the stack pointer means that it will automatically
4266    # unwind the same amount when multiple stack frames are unwound.
4267    local $stack_depth = $stack_depth + 1;    # Protect from non-local exits
4268
4269    # Expand @stack.
4270    $#stack = $stack_depth;
4271
4272    # Save current single-step setting.
4273    $stack[-1] = $single;
4274
4275    # Turn off all flags except single-stepping.
4276    # Use local so the single-step value is popped back off the
4277    # stack for us.
4278    local $single = $single & 1;
4279
4280    # If we've gotten really deeply recursed, turn on the flag that will
4281    # make us stop with the 'deep recursion' message.
4282    $single |= 4 if $stack_depth == $deep;
4283
4284    # If frame messages are on ...
4285    _print_frame_message($al);
4286
4287    # call the original lvalue sub.
4288    &$sub;
4289}
4290
4291# Abstracting common code from multiple places elsewhere:
4292sub depth_print_lineinfo {
4293    my $always_print = shift;
4294
4295    print_lineinfo( @_ ) if ($always_print or $stack_depth < $trace_to_depth);
4296}
4297
4298=head1 EXTENDED COMMAND HANDLING AND THE COMMAND API
4299
4300In Perl 5.8.0, there was a major realignment of the commands and what they did,
4301Most of the changes were to systematize the command structure and to eliminate
4302commands that threw away user input without checking.
4303
4304The following sections describe the code added to make it easy to support
4305multiple command sets with conflicting command names. This section is a start
4306at unifying all command processing to make it simpler to develop commands.
4307
4308Note that all the cmd_[a-zA-Z] subroutines require the command name, a line
4309number, and C<$dbline> (the current line) as arguments.
4310
4311Support functions in this section which have multiple modes of failure C<die>
4312on error; the rest simply return a false value.
4313
4314The user-interface functions (all of the C<cmd_*> functions) just output
4315error messages.
4316
4317=head2 C<%set>
4318
4319The C<%set> hash defines the mapping from command letter to subroutine
4320name suffix.
4321
4322C<%set> is a two-level hash, indexed by set name and then by command name.
4323Note that trying to set the CommandSet to C<foobar> simply results in the
43245.8.0 command set being used, since there's no top-level entry for C<foobar>.
4325
4326=cut
4327
4328### The API section
4329
4330my %set = (    #
4331    'pre580' => {
4332        'a' => 'pre580_a',
4333        'A' => 'pre580_null',
4334        'b' => 'pre580_b',
4335        'B' => 'pre580_null',
4336        'd' => 'pre580_null',
4337        'D' => 'pre580_D',
4338        'h' => 'pre580_h',
4339        'M' => 'pre580_null',
4340        'O' => 'o',
4341        'o' => 'pre580_null',
4342        'v' => 'M',
4343        'w' => 'v',
4344        'W' => 'pre580_W',
4345    },
4346    'pre590' => {
4347        '<'  => 'pre590_prepost',
4348        '<<' => 'pre590_prepost',
4349        '>'  => 'pre590_prepost',
4350        '>>' => 'pre590_prepost',
4351        '{'  => 'pre590_prepost',
4352        '{{' => 'pre590_prepost',
4353    },
4354);
4355
4356my %breakpoints_data;
4357
4358sub _has_breakpoint_data_ref {
4359    my ($filename, $line) = @_;
4360
4361    return (
4362        exists( $breakpoints_data{$filename} )
4363            and
4364        exists( $breakpoints_data{$filename}{$line} )
4365    );
4366}
4367
4368sub _get_breakpoint_data_ref {
4369    my ($filename, $line) = @_;
4370
4371    return ($breakpoints_data{$filename}{$line} ||= +{});
4372}
4373
4374sub _delete_breakpoint_data_ref {
4375    my ($filename, $line) = @_;
4376
4377    delete($breakpoints_data{$filename}{$line});
4378    if (! scalar(keys( %{$breakpoints_data{$filename}} )) ) {
4379        delete($breakpoints_data{$filename});
4380    }
4381
4382    return;
4383}
4384
4385sub _set_breakpoint_enabled_status {
4386    my ($filename, $line, $status) = @_;
4387
4388    _get_breakpoint_data_ref($filename, $line)->{'enabled'} =
4389        ($status ? 1 : '')
4390        ;
4391
4392    return;
4393}
4394
4395sub _enable_breakpoint_temp_enabled_status {
4396    my ($filename, $line) = @_;
4397
4398    _get_breakpoint_data_ref($filename, $line)->{'temp_enabled'} = 1;
4399
4400    return;
4401}
4402
4403sub _cancel_breakpoint_temp_enabled_status {
4404    my ($filename, $line) = @_;
4405
4406    my $ref = _get_breakpoint_data_ref($filename, $line);
4407
4408    delete ($ref->{'temp_enabled'});
4409
4410    if (! %$ref) {
4411        _delete_breakpoint_data_ref($filename, $line);
4412    }
4413
4414    return;
4415}
4416
4417sub _is_breakpoint_enabled {
4418    my ($filename, $line) = @_;
4419
4420    my $data_ref = _get_breakpoint_data_ref($filename, $line);
4421    return ($data_ref->{'enabled'} || $data_ref->{'temp_enabled'});
4422}
4423
4424=head2 C<cmd_wrapper()> (API)
4425
4426C<cmd_wrapper()> allows the debugger to switch command sets
4427depending on the value of the C<CommandSet> option.
4428
4429It tries to look up the command in the C<%set> package-level I<lexical>
4430(which means external entities can't fiddle with it) and create the name of
4431the sub to call based on the value found in the hash (if it's there). I<All>
4432of the commands to be handled in a set have to be added to C<%set>; if they
4433aren't found, the 5.8.0 equivalent is called (if there is one).
4434
4435This code uses symbolic references.
4436
4437=cut
4438
4439sub cmd_wrapper {
4440    my $cmd      = shift;
4441    my $line     = shift;
4442    my $dblineno = shift;
4443
4444    # Assemble the command subroutine's name by looking up the
4445    # command set and command name in %set. If we can't find it,
4446    # default to the older version of the command.
4447    my $call = 'cmd_'
4448      . ( $set{$CommandSet}{$cmd}
4449          || ( $cmd =~ /\A[<>{]+/o ? 'prepost' : $cmd ) );
4450
4451    # Call the command subroutine, call it by name.
4452    return __PACKAGE__->can($call)->( $cmd, $line, $dblineno );
4453} ## end sub cmd_wrapper
4454
4455=head3 C<cmd_a> (command)
4456
4457The C<a> command handles pre-execution actions. These are associated with a
4458particular line, so they're stored in C<%dbline>. We default to the current
4459line if none is specified.
4460
4461=cut
4462
4463sub cmd_a {
4464    my $cmd    = shift;
4465    my $line   = shift || '';    # [.|line] expr
4466    my $dbline = shift;
4467
4468    # If it's dot (here), or not all digits,  use the current line.
4469    $line =~ s/\A\./$dbline/;
4470
4471    # Should be a line number followed by an expression.
4472    if ( my ($lineno, $expr) = $line =~ /^\s*(\d*)\s*(\S.+)/ ) {
4473
4474        if (! length($lineno)) {
4475            $lineno = $dbline;
4476        }
4477
4478        # If we have an expression ...
4479        if ( length $expr ) {
4480
4481            # ... but the line isn't breakable, complain.
4482            if ( $dbline[$lineno] == 0 ) {
4483                print $OUT
4484                  "Line $lineno($dbline[$lineno]) does not have an action?\n";
4485            }
4486            else {
4487
4488                # It's executable. Record that the line has an action.
4489                $had_breakpoints{$filename} |= 2;
4490
4491                # Remove any action, temp breakpoint, etc.
4492                $dbline{$lineno} =~ s/\0[^\0]*//;
4493
4494                # Add the action to the line.
4495                $dbline{$lineno} .= "\0" . action($expr);
4496
4497                _set_breakpoint_enabled_status($filename, $lineno, 1);
4498            }
4499        } ## end if (length $expr)
4500    } ## end if ($line =~ /^\s*(\d*)\s*(\S.+)/)
4501    else {
4502
4503        # Syntax wrong.
4504        print $OUT
4505          "Adding an action requires an optional lineno and an expression\n"
4506          ;    # hint
4507    }
4508} ## end sub cmd_a
4509
4510=head3 C<cmd_A> (command)
4511
4512Delete actions. Similar to above, except the delete code is in a separate
4513subroutine, C<delete_action>.
4514
4515=cut
4516
4517sub cmd_A {
4518    my $cmd    = shift;
4519    my $line   = shift || '';
4520    my $dbline = shift;
4521
4522    # Dot is this line.
4523    $line =~ s/^\./$dbline/;
4524
4525    # Call delete_action with a null param to delete them all.
4526    # The '1' forces the eval to be true. It'll be false only
4527    # if delete_action blows up for some reason, in which case
4528    # we print $@ and get out.
4529    if ( $line eq '*' ) {
4530        if (! eval { _delete_all_actions(); 1 }) {
4531            print {$OUT} $@;
4532            return;
4533        }
4534    }
4535
4536    # There's a real line  number. Pass it to delete_action.
4537    # Error trapping is as above.
4538    elsif ( $line =~ /^(\S.*)/ ) {
4539        if (! eval { delete_action($1); 1 }) {
4540            print {$OUT} $@;
4541            return;
4542        }
4543    }
4544
4545    # Swing and a miss. Bad syntax.
4546    else {
4547        print $OUT
4548          "Deleting an action requires a line number, or '*' for all\n" ; # hint
4549    }
4550} ## end sub cmd_A
4551
4552=head3 C<delete_action> (API)
4553
4554C<delete_action> accepts either a line number or C<undef>. If a line number
4555is specified, we check for the line being executable (if it's not, it
4556couldn't have had an  action). If it is, we just take the action off (this
4557will get any kind of an action, including breakpoints).
4558
4559=cut
4560
4561sub _remove_action_from_dbline {
4562    my $i = shift;
4563
4564    $dbline{$i} =~ s/\0[^\0]*//;    # \^a
4565    delete $dbline{$i} if $dbline{$i} eq '';
4566
4567    return;
4568}
4569
4570sub _delete_all_actions {
4571    print {$OUT} "Deleting all actions...\n";
4572
4573    for my $file ( keys %had_breakpoints ) {
4574        local *dbline = $main::{ '_<' . $file };
4575        $max = $#dbline;
4576        my $was;
4577        for my $i (1 .. $max) {
4578            if ( defined $dbline{$i} ) {
4579                _remove_action_from_dbline($i);
4580            }
4581        }
4582
4583        unless ( $had_breakpoints{$file} &= ~2 ) {
4584            delete $had_breakpoints{$file};
4585        }
4586    }
4587
4588    return;
4589}
4590
4591sub delete_action {
4592    my $i = shift;
4593
4594    if ( defined($i) ) {
4595        # Can there be one?
4596        die "Line $i has no action .\n" if $dbline[$i] == 0;
4597
4598        # Nuke whatever's there.
4599        _remove_action_from_dbline($i);
4600    }
4601    else {
4602        _delete_all_actions();
4603    }
4604}
4605
4606=head3 C<cmd_b> (command)
4607
4608Set breakpoints. Since breakpoints can be set in so many places, in so many
4609ways, conditionally or not, the breakpoint code is kind of complex. Mostly,
4610we try to parse the command type, and then shuttle it off to an appropriate
4611subroutine to actually do the work of setting the breakpoint in the right
4612place.
4613
4614=cut
4615
4616sub cmd_b {
4617    my $cmd    = shift;
4618    my $line   = shift;    # [.|line] [cond]
4619    my $dbline = shift;
4620
4621    my $default_cond = sub {
4622        my $cond = shift;
4623        return length($cond) ? $cond : '1';
4624    };
4625
4626    # Make . the current line number if it's there..
4627    $line =~ s/^\.(\s|\z)/$dbline$1/;
4628
4629    # No line number, no condition. Simple break on current line.
4630    if ( $line =~ /^\s*$/ ) {
4631        cmd_b_line( $dbline, 1 );
4632    }
4633
4634    # Break on load for a file.
4635    elsif ( my ($file) = $line =~ /^load\b\s*(.*)/ ) {
4636        $file =~ s/\s+\z//;
4637        cmd_b_load($file);
4638    }
4639
4640    # b compile|postpone <some sub> [<condition>]
4641    # The interpreter actually traps this one for us; we just put the
4642    # necessary condition in the %postponed hash.
4643    elsif ( my ($action, $subname, $cond)
4644        = $line =~ /^(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/ ) {
4645
4646        # De-Perl4-ify the name - ' separators to ::.
4647        $subname =~ s/'/::/g;
4648
4649        # Qualify it into the current package unless it's already qualified.
4650        $subname = "${package}::" . $subname unless $subname =~ /::/;
4651
4652        # Add main if it starts with ::.
4653        $subname = "main" . $subname if substr( $subname, 0, 2 ) eq "::";
4654
4655        # Save the break type for this sub.
4656        $postponed{$subname} = (($action eq 'postpone')
4657            ? ( "break +0 if " . $default_cond->($cond) )
4658            : "compile");
4659    } ## end elsif ($line =~ ...
4660    # b <filename>:<line> [<condition>]
4661    elsif (my ($filename, $line_num, $cond)
4662        = $line =~ /\A(\S+[^:]):(\d+)\s*(.*)/ms) {
4663        cmd_b_filename_line(
4664            $filename,
4665            $line_num,
4666            (length($cond) ? $cond : '1'),
4667        );
4668    }
4669    # b <sub name> [<condition>]
4670    elsif ( my ($new_subname, $new_cond) =
4671        $line =~ /^([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/ ) {
4672
4673        #
4674        $subname = $new_subname;
4675        cmd_b_sub( $subname, $default_cond->($new_cond) );
4676    }
4677
4678    # b <line> [<condition>].
4679    elsif ( my ($line_n, $cond) = $line =~ /^(\d*)\s*(.*)/ ) {
4680
4681        # Capture the line. If none, it's the current line.
4682        $line = $line_n || $dbline;
4683
4684        # Break on line.
4685        cmd_b_line( $line, $default_cond->($cond) );
4686    }
4687
4688    # Line didn't make sense.
4689    else {
4690        print "confused by line($line)?\n";
4691    }
4692
4693    return;
4694} ## end sub cmd_b
4695
4696=head3 C<break_on_load> (API)
4697
4698We want to break when this file is loaded. Mark this file in the
4699C<%break_on_load> hash, and note that it has a breakpoint in
4700C<%had_breakpoints>.
4701
4702=cut
4703
4704sub break_on_load {
4705    my $file = shift;
4706    $break_on_load{$file} = 1;
4707    $had_breakpoints{$file} |= 1;
4708}
4709
4710=head3 C<report_break_on_load> (API)
4711
4712Gives us an array of filenames that are set to break on load. Note that
4713only files with break-on-load are in here, so simply showing the keys
4714suffices.
4715
4716=cut
4717
4718sub report_break_on_load {
4719    sort keys %break_on_load;
4720}
4721
4722=head3 C<cmd_b_load> (command)
4723
4724We take the file passed in and try to find it in C<%INC> (which maps modules
4725to files they came from). We mark those files for break-on-load via
4726C<break_on_load> and then report that it was done.
4727
4728=cut
4729
4730sub cmd_b_load {
4731    my $file = shift;
4732    my @files;
4733
4734    # This is a block because that way we can use a redo inside it
4735    # even without there being any looping structure at all outside it.
4736    {
4737
4738        # Save short name and full path if found.
4739        push @files, $file;
4740        push @files, $::INC{$file} if $::INC{$file};
4741
4742        # Tack on .pm and do it again unless there was a '.' in the name
4743        # already.
4744        $file .= '.pm', redo unless $file =~ /\./;
4745    }
4746
4747    # Do the real work here.
4748    break_on_load($_) for @files;
4749
4750    # All the files that have break-on-load breakpoints.
4751    @files = report_break_on_load;
4752
4753    # Normalize for the purposes of our printing this.
4754    local $\ = '';
4755    local $" = ' ';
4756    print $OUT "Will stop on load of '@files'.\n";
4757} ## end sub cmd_b_load
4758
4759=head3 C<$filename_error> (API package global)
4760
4761Several of the functions we need to implement in the API need to work both
4762on the current file and on other files. We don't want to duplicate code, so
4763C<$filename_error> is used to contain the name of the file that's being
4764worked on (if it's not the current one).
4765
4766We can now build functions in pairs: the basic function works on the current
4767file, and uses C<$filename_error> as part of its error message. Since this is
4768initialized to C<"">, no filename will appear when we are working on the
4769current file.
4770
4771The second function is a wrapper which does the following:
4772
4773=over 4
4774
4775=item *
4776
4777Localizes C<$filename_error> and sets it to the name of the file to be processed.
4778
4779=item *
4780
4781Localizes the C<*dbline> glob and reassigns it to point to the file we want to process.
4782
4783=item *
4784
4785Calls the first function.
4786
4787The first function works on the I<current> file (i.e., the one we changed to),
4788and prints C<$filename_error> in the error message (the name of the other file)
4789if it needs to. When the functions return, C<*dbline> is restored to point
4790to the actual current file (the one we're executing in) and
4791C<$filename_error> is restored to C<"">. This restores everything to
4792the way it was before the second function was called at all.
4793
4794See the comments in C<breakable_line> and C<breakable_line_in_file> for more
4795details.
4796
4797=back
4798
4799=cut
4800
4801use vars qw($filename_error);
4802$filename_error = '';
4803
4804=head3 breakable_line(from, to) (API)
4805
4806The subroutine decides whether or not a line in the current file is breakable.
4807It walks through C<@dbline> within the range of lines specified, looking for
4808the first line that is breakable.
4809
4810If C<$to> is greater than C<$from>, the search moves forwards, finding the
4811first line I<after> C<$to> that's breakable, if there is one.
4812
4813If C<$from> is greater than C<$to>, the search goes I<backwards>, finding the
4814first line I<before> C<$to> that's breakable, if there is one.
4815
4816=cut
4817
4818sub breakable_line {
4819
4820    my ( $from, $to ) = @_;
4821
4822    # $i is the start point. (Where are the FORTRAN programs of yesteryear?)
4823    my $i = $from;
4824
4825    # If there are at least 2 arguments, we're trying to search a range.
4826    if ( @_ >= 2 ) {
4827
4828        # $delta is positive for a forward search, negative for a backward one.
4829        my $delta = $from < $to ? +1 : -1;
4830
4831        # Keep us from running off the ends of the file.
4832        my $limit = $delta > 0 ? $#dbline : 1;
4833
4834        # Clever test. If you're a mathematician, it's obvious why this
4835        # test works. If not:
4836        # If $delta is positive (going forward), $limit will be $#dbline.
4837        #    If $to is less than $limit, ($limit - $to) will be positive, times
4838        #    $delta of 1 (positive), so the result is > 0 and we should use $to
4839        #    as the stopping point.
4840        #
4841        #    If $to is greater than $limit, ($limit - $to) is negative,
4842        #    times $delta of 1 (positive), so the result is < 0 and we should
4843        #    use $limit ($#dbline) as the stopping point.
4844        #
4845        # If $delta is negative (going backward), $limit will be 1.
4846        #    If $to is zero, ($limit - $to) will be 1, times $delta of -1
4847        #    (negative) so the result is > 0, and we use $to as the stopping
4848        #    point.
4849        #
4850        #    If $to is less than zero, ($limit - $to) will be positive,
4851        #    times $delta of -1 (negative), so the result is not > 0, and
4852        #    we use $limit (1) as the stopping point.
4853        #
4854        #    If $to is 1, ($limit - $to) will zero, times $delta of -1
4855        #    (negative), still giving zero; the result is not > 0, and
4856        #    we use $limit (1) as the stopping point.
4857        #
4858        #    if $to is >1, ($limit - $to) will be negative, times $delta of -1
4859        #    (negative), giving a positive (>0) value, so we'll set $limit to
4860        #    $to.
4861
4862        $limit = $to if ( $limit - $to ) * $delta > 0;
4863
4864        # The real search loop.
4865        # $i starts at $from (the point we want to start searching from).
4866        # We move through @dbline in the appropriate direction (determined
4867        # by $delta: either -1 (back) or +1 (ahead).
4868        # We stay in as long as we haven't hit an executable line
4869        # ($dbline[$i] == 0 means not executable) and we haven't reached
4870        # the limit yet (test similar to the above).
4871        $i += $delta while $dbline[$i] == 0 and ( $limit - $i ) * $delta > 0;
4872
4873    } ## end if (@_ >= 2)
4874
4875    # If $i points to a line that is executable, return that.
4876    return $i unless $dbline[$i] == 0;
4877
4878    # Format the message and print it: no breakable lines in range.
4879    my ( $pl, $upto ) = ( '', '' );
4880    ( $pl, $upto ) = ( 's', "..$to" ) if @_ >= 2 and $from != $to;
4881
4882    # If there's a filename in filename_error, we'll see it.
4883    # If not, not.
4884    die "Line$pl $from$upto$filename_error not breakable\n";
4885} ## end sub breakable_line
4886
4887=head3 breakable_line_in_filename(file, from, to) (API)
4888
4889Like C<breakable_line>, but look in another file.
4890
4891=cut
4892
4893sub breakable_line_in_filename {
4894
4895    # Capture the file name.
4896    my ($f) = shift;
4897
4898    # Swap the magic line array over there temporarily.
4899    local *dbline = $main::{ '_<' . $f };
4900
4901    # If there's an error, it's in this other file.
4902    local $filename_error = " of '$f'";
4903
4904    # Find the breakable line.
4905    breakable_line(@_);
4906
4907    # *dbline and $filename_error get restored when this block ends.
4908
4909} ## end sub breakable_line_in_filename
4910
4911=head3 break_on_line(lineno, [condition]) (API)
4912
4913Adds a breakpoint with the specified condition (or 1 if no condition was
4914specified) to the specified line. Dies if it can't.
4915
4916=cut
4917
4918sub break_on_line {
4919    my $i = shift;
4920    my $cond = @_ ? shift(@_) : 1;
4921
4922    my $inii  = $i;
4923    my $after = '';
4924    my $pl    = '';
4925
4926    # Woops, not a breakable line. $filename_error allows us to say
4927    # if it was in a different file.
4928    die "Line $i$filename_error not breakable.\n" if $dbline[$i] == 0;
4929
4930    # Mark this file as having breakpoints in it.
4931    $had_breakpoints{$filename} |= 1;
4932
4933    # If there is an action or condition here already ...
4934    if ( $dbline{$i} ) {
4935
4936        # ... swap this condition for the existing one.
4937        $dbline{$i} =~ s/^[^\0]*/$cond/;
4938    }
4939    else {
4940
4941        # Nothing here - just add the condition.
4942        $dbline{$i} = $cond;
4943
4944        _set_breakpoint_enabled_status($filename, $i, 1);
4945    }
4946
4947    return;
4948} ## end sub break_on_line
4949
4950=head3 cmd_b_line(line, [condition]) (command)
4951
4952Wrapper for C<break_on_line>. Prints the failure message if it
4953doesn't work.
4954
4955=cut
4956
4957sub cmd_b_line {
4958    if (not eval { break_on_line(@_); 1 }) {
4959        local $\ = '';
4960        print $OUT $@ and return;
4961    }
4962
4963    return;
4964} ## end sub cmd_b_line
4965
4966=head3 cmd_b_filename_line(line, [condition]) (command)
4967
4968Wrapper for C<break_on_filename_line>. Prints the failure message if it
4969doesn't work.
4970
4971=cut
4972
4973sub cmd_b_filename_line {
4974    if (not eval { break_on_filename_line(@_); 1 }) {
4975        local $\ = '';
4976        print $OUT $@ and return;
4977    }
4978
4979    return;
4980}
4981
4982=head3 break_on_filename_line(file, line, [condition]) (API)
4983
4984Switches to the file specified and then calls C<break_on_line> to set
4985the breakpoint.
4986
4987=cut
4988
4989sub break_on_filename_line {
4990    my $f = shift;
4991    my $i = shift;
4992    my $cond = @_ ? shift(@_) : 1;
4993
4994    # Switch the magical hash temporarily.
4995    local *dbline = $main::{ '_<' . $f };
4996
4997    # Localize the variables that break_on_line uses to make its message.
4998    local $filename_error = " of '$f'";
4999    local $filename       = $f;
5000
5001    # Add the breakpoint.
5002    break_on_line( $i, $cond );
5003
5004    return;
5005} ## end sub break_on_filename_line
5006
5007=head3 break_on_filename_line_range(file, from, to, [condition]) (API)
5008
5009Switch to another file, search the range of lines specified for an
5010executable one, and put a breakpoint on the first one you find.
5011
5012=cut
5013
5014sub break_on_filename_line_range {
5015    my $f = shift;
5016    my $from = shift;
5017    my $to = shift;
5018    my $cond = @_ ? shift(@_) : 1;
5019
5020    # Find a breakable line if there is one.
5021    my $i = breakable_line_in_filename( $f, $from, $to );
5022
5023    # Add the breakpoint.
5024    break_on_filename_line( $f, $i, $cond );
5025
5026    return;
5027} ## end sub break_on_filename_line_range
5028
5029=head3 subroutine_filename_lines(subname, [condition]) (API)
5030
5031Search for a subroutine within a given file. The condition is ignored.
5032Uses C<find_sub> to locate the desired subroutine.
5033
5034=cut
5035
5036sub subroutine_filename_lines {
5037    my ( $subname ) = @_;
5038
5039    # Returned value from find_sub() is fullpathname:startline-endline.
5040    # The match creates the list (fullpathname, start, end).
5041    return (find_sub($subname) =~ /^(.*):(\d+)-(\d+)$/);
5042} ## end sub subroutine_filename_lines
5043
5044=head3 break_subroutine(subname) (API)
5045
5046Places a break on the first line possible in the specified subroutine. Uses
5047C<subroutine_filename_lines> to find the subroutine, and
5048C<break_on_filename_line_range> to place the break.
5049
5050=cut
5051
5052sub break_subroutine {
5053    my $subname = shift;
5054
5055    # Get filename, start, and end.
5056    my ( $file, $s, $e ) = subroutine_filename_lines($subname)
5057      or die "Subroutine $subname not found.\n";
5058
5059
5060    # Null condition changes to '1' (always true).
5061    my $cond = @_ ? shift(@_) : 1;
5062
5063    # Put a break the first place possible in the range of lines
5064    # that make up this subroutine.
5065    break_on_filename_line_range( $file, $s, $e, $cond );
5066
5067    return;
5068} ## end sub break_subroutine
5069
5070=head3 cmd_b_sub(subname, [condition]) (command)
5071
5072We take the incoming subroutine name and fully-qualify it as best we can.
5073
5074=over 4
5075
5076=item 1. If it's already fully-qualified, leave it alone.
5077
5078=item 2. Try putting it in the current package.
5079
5080=item 3. If it's not there, try putting it in CORE::GLOBAL if it exists there.
5081
5082=item 4. If it starts with '::', put it in 'main::'.
5083
5084=back
5085
5086After all this cleanup, we call C<break_subroutine> to try to set the
5087breakpoint.
5088
5089=cut
5090
5091sub cmd_b_sub {
5092    my $subname = shift;
5093    my $cond = @_ ? shift : 1;
5094
5095    # If the subname isn't a code reference, qualify it so that
5096    # break_subroutine() will work right.
5097    if ( ref($subname) ne 'CODE' ) {
5098
5099        # Not Perl 4.
5100        $subname =~ s/'/::/g;
5101        my $s = $subname;
5102
5103        # Put it in this package unless it's already qualified.
5104        if ($subname !~ /::/)
5105        {
5106            $subname = $package . '::' . $subname;
5107        };
5108
5109        # Requalify it into CORE::GLOBAL if qualifying it into this
5110        # package resulted in its not being defined, but only do so
5111        # if it really is in CORE::GLOBAL.
5112        my $core_name = "CORE::GLOBAL::$s";
5113        if ((!defined(&$subname))
5114                and ($s !~ /::/)
5115                and (defined &{$core_name}))
5116        {
5117            $subname = $core_name;
5118        }
5119
5120        # Put it in package 'main' if it has a leading ::.
5121        if ($subname =~ /\A::/)
5122        {
5123            $subname = "main" . $subname;
5124        }
5125    } ## end if ( ref($subname) ne 'CODE' ) {
5126
5127    # Try to set the breakpoint.
5128    if (not eval { break_subroutine( $subname, $cond ); 1 }) {
5129        local $\ = '';
5130        print {$OUT} $@;
5131        return;
5132    }
5133
5134    return;
5135} ## end sub cmd_b_sub
5136
5137=head3 C<cmd_B> - delete breakpoint(s) (command)
5138
5139The command mostly parses the command line and tries to turn the argument
5140into a line spec. If it can't, it uses the current line. It then calls
5141C<delete_breakpoint> to actually do the work.
5142
5143If C<*> is  specified, C<cmd_B> calls C<delete_breakpoint> with no arguments,
5144thereby deleting all the breakpoints.
5145
5146=cut
5147
5148sub cmd_B {
5149    my $cmd = shift;
5150
5151    # No line spec? Use dbline.
5152    # If there is one, use it if it's non-zero, or wipe it out if it is.
5153    my $line   = ( $_[0] =~ /\A\./ ) ? $dbline : (shift || '');
5154    my $dbline = shift;
5155
5156    # If the line was dot, make the line the current one.
5157    $line =~ s/^\./$dbline/;
5158
5159    # If it's * we're deleting all the breakpoints.
5160    if ( $line eq '*' ) {
5161        if (not eval { delete_breakpoint(); 1 }) {
5162            print {$OUT} $@;
5163        }
5164    }
5165
5166    # If there is a line spec, delete the breakpoint on that line.
5167    elsif ( $line =~ /\A(\S.*)/ ) {
5168        if (not eval { delete_breakpoint( $line || $dbline ); 1 }) {
5169            local $\ = '';
5170            print {$OUT} $@;
5171        }
5172    } ## end elsif ($line =~ /^(\S.*)/)
5173
5174    # No line spec.
5175    else {
5176        print {$OUT}
5177          "Deleting a breakpoint requires a line number, or '*' for all\n"
5178          ;    # hint
5179    }
5180
5181    return;
5182} ## end sub cmd_B
5183
5184=head3 delete_breakpoint([line]) (API)
5185
5186This actually does the work of deleting either a single breakpoint, or all
5187of them.
5188
5189For a single line, we look for it in C<@dbline>. If it's nonbreakable, we
5190just drop out with a message saying so. If it is, we remove the condition
5191part of the 'condition\0action' that says there's a breakpoint here. If,
5192after we've done that, there's nothing left, we delete the corresponding
5193line in C<%dbline> to signal that no action needs to be taken for this line.
5194
5195For all breakpoints, we iterate through the keys of C<%had_breakpoints>,
5196which lists all currently-loaded files which have breakpoints. We then look
5197at each line in each of these files, temporarily switching the C<%dbline>
5198and C<@dbline> structures to point to the files in question, and do what
5199we did in the single line case: delete the condition in C<@dbline>, and
5200delete the key in C<%dbline> if nothing's left.
5201
5202We then wholesale delete C<%postponed>, C<%postponed_file>, and
5203C<%break_on_load>, because these structures contain breakpoints for files
5204and code that haven't been loaded yet. We can just kill these off because there
5205are no magical debugger structures associated with them.
5206
5207=cut
5208
5209sub _remove_breakpoint_entry {
5210    my ($fn, $i) = @_;
5211
5212    delete $dbline{$i};
5213    _delete_breakpoint_data_ref($fn, $i);
5214
5215    return;
5216}
5217
5218sub _delete_all_breakpoints {
5219    print {$OUT} "Deleting all breakpoints...\n";
5220
5221    # %had_breakpoints lists every file that had at least one
5222    # breakpoint in it.
5223    for my $fn ( keys %had_breakpoints ) {
5224
5225        # Switch to the desired file temporarily.
5226        local *dbline = $main::{ '_<' . $fn };
5227
5228        $max = $#dbline;
5229
5230        # For all lines in this file ...
5231        for my $i (1 .. $max) {
5232
5233            # If there's a breakpoint or action on this line ...
5234            if ( defined $dbline{$i} ) {
5235
5236                # ... remove the breakpoint.
5237                $dbline{$i} =~ s/\A[^\0]+//;
5238                if ( $dbline{$i} =~ s/\A\0?\z// ) {
5239                    # Remove the entry altogether if no action is there.
5240                    _remove_breakpoint_entry($fn, $i);
5241                }
5242            } ## end if (defined $dbline{$i...
5243        } ## end for $i (1 .. $max)
5244
5245        # If, after we turn off the "there were breakpoints in this file"
5246        # bit, the entry in %had_breakpoints for this file is zero,
5247        # we should remove this file from the hash.
5248        if ( not $had_breakpoints{$fn} &= (~1) ) {
5249            delete $had_breakpoints{$fn};
5250        }
5251    } ## end for my $fn (keys %had_breakpoints)
5252
5253    # Kill off all the other breakpoints that are waiting for files that
5254    # haven't been loaded yet.
5255    undef %postponed;
5256    undef %postponed_file;
5257    undef %break_on_load;
5258
5259    return;
5260}
5261
5262sub _delete_breakpoint_from_line {
5263    my ($i) = @_;
5264
5265    # Woops. This line wasn't breakable at all.
5266    die "Line $i not breakable.\n" if $dbline[$i] == 0;
5267
5268    # Kill the condition, but leave any action.
5269    $dbline{$i} =~ s/\A[^\0]*//;
5270
5271    # Remove the entry entirely if there's no action left.
5272    if ($dbline{$i} eq '') {
5273        _remove_breakpoint_entry($filename, $i);
5274    }
5275
5276    return;
5277}
5278
5279sub delete_breakpoint {
5280    my $i = shift;
5281
5282    # If we got a line, delete just that one.
5283    if ( defined($i) ) {
5284        _delete_breakpoint_from_line($i);
5285    }
5286    # No line; delete them all.
5287    else {
5288        _delete_all_breakpoints();
5289    }
5290
5291    return;
5292}
5293
5294=head3 cmd_stop (command)
5295
5296This is meant to be part of the new command API, but it isn't called or used
5297anywhere else in the debugger. XXX It is probably meant for use in development
5298of new commands.
5299
5300=cut
5301
5302sub cmd_stop {    # As on ^C, but not signal-safy.
5303    $signal = 1;
5304}
5305
5306=head3 C<cmd_e> - threads
5307
5308Display the current thread id:
5309
5310    e
5311
5312This could be how (when implemented) to send commands to this thread id (e cmd)
5313or that thread id (e tid cmd).
5314
5315=cut
5316
5317sub cmd_e {
5318    my $cmd  = shift;
5319    my $line = shift;
5320    unless (exists($INC{'threads.pm'})) {
5321        print "threads not loaded($ENV{PERL5DB_THREADED})
5322        please run the debugger with PERL5DB_THREADED=1 set in the environment\n";
5323    } else {
5324        my $tid = threads->tid;
5325        print "thread id: $tid\n";
5326    }
5327} ## end sub cmd_e
5328
5329=head3 C<cmd_E> - list of thread ids
5330
5331Display the list of available thread ids:
5332
5333    E
5334
5335This could be used (when implemented) to send commands to all threads (E cmd).
5336
5337=cut
5338
5339sub cmd_E {
5340    my $cmd  = shift;
5341    my $line = shift;
5342    unless (exists($INC{'threads.pm'})) {
5343        print "threads not loaded($ENV{PERL5DB_THREADED})
5344        please run the debugger with PERL5DB_THREADED=1 set in the environment\n";
5345    } else {
5346        my $tid = threads->tid;
5347        print "thread ids: ".join(', ',
5348            map { ($tid == $_->tid ? '<'.$_->tid.'>' : $_->tid) } threads->list
5349        )."\n";
5350    }
5351} ## end sub cmd_E
5352
5353=head3 C<cmd_h> - help command (command)
5354
5355Does the work of either
5356
5357=over 4
5358
5359=item *
5360
5361Showing all the debugger help
5362
5363=item *
5364
5365Showing help for a specific command
5366
5367=back
5368
5369=cut
5370
5371use vars qw($help);
5372use vars qw($summary);
5373
5374sub cmd_h {
5375    my $cmd = shift;
5376
5377    # If we have no operand, assume null.
5378    my $line = shift || '';
5379
5380    # 'h h'. Print the long-format help.
5381    if ( $line =~ /\Ah\s*\z/ ) {
5382        print_help($help);
5383    }
5384
5385    # 'h <something>'. Search for the command and print only its help.
5386    elsif ( my ($asked) = $line =~ /\A(\S.*)\z/ ) {
5387
5388        # support long commands; otherwise bogus errors
5389        # happen when you ask for h on <CR> for example
5390        my $qasked = quotemeta($asked);    # for searching; we don't
5391                                           # want to use it as a pattern.
5392                                           # XXX: finds CR but not <CR>
5393
5394        # Search the help string for the command.
5395        if (
5396            $help =~ /^                    # Start of a line
5397                      <?                   # Optional '<'
5398                      (?:[IB]<)            # Optional markup
5399                      $qasked              # The requested command
5400                     /mx
5401          )
5402        {
5403
5404            # It's there; pull it out and print it.
5405            while (
5406                $help =~ /^
5407                              (<?            # Optional '<'
5408                                 (?:[IB]<)   # Optional markup
5409                                 $qasked     # The command
5410                                 ([\s\S]*?)  # Description line(s)
5411                              \n)            # End of last description line
5412                              (?!\s)         # Next line not starting with
5413                                             # whitespace
5414                             /mgx
5415              )
5416            {
5417                print_help($1);
5418            }
5419        }
5420
5421        # Not found; not a debugger command.
5422        else {
5423            print_help("B<$asked> is not a debugger command.\n");
5424        }
5425    } ## end elsif ($line =~ /^(\S.*)$/)
5426
5427    # 'h' - print the summary help.
5428    else {
5429        print_help($summary);
5430    }
5431} ## end sub cmd_h
5432
5433=head3 C<cmd_i> - inheritance display
5434
5435Display the (nested) parentage of the module or object given.
5436
5437=cut
5438
5439sub cmd_i {
5440    my $cmd  = shift;
5441    my $line = shift;
5442    foreach my $isa ( split( /\s+/, $line ) ) {
5443        $evalarg = $isa;
5444        # The &-call is here to ascertain the mutability of @_.
5445        ($isa) = &DB::eval;
5446        no strict 'refs';
5447        print join(
5448            ', ',
5449            map {
5450                "$_"
5451                  . (
5452                    defined( ${"$_\::VERSION"} )
5453                    ? ' ' . ${"$_\::VERSION"}
5454                    : undef )
5455              } @{mro::get_linear_isa(ref($isa) || $isa)}
5456        );
5457        print "\n";
5458    }
5459} ## end sub cmd_i
5460
5461=head3 C<cmd_l> - list lines (command)
5462
5463Most of the command is taken up with transforming all the different line
5464specification syntaxes into 'start-stop'. After that is done, the command
5465runs a loop over C<@dbline> for the specified range of lines. It handles
5466the printing of each line and any markers (C<==E<gt>> for current line,
5467C<b> for break on this line, C<a> for action on this line, C<:> for this
5468line breakable).
5469
5470We save the last line listed in the C<$start> global for further listing
5471later.
5472
5473=cut
5474
5475sub _min {
5476    my $min = shift;
5477    foreach my $v (@_) {
5478        if ($min > $v) {
5479            $min = $v;
5480        }
5481    }
5482    return $min;
5483}
5484
5485sub _max {
5486    my $max = shift;
5487    foreach my $v (@_) {
5488        if ($max < $v) {
5489            $max = $v;
5490        }
5491    }
5492    return $max;
5493}
5494
5495sub _minify_to_max {
5496    my $ref = shift;
5497
5498    $$ref = _min($$ref, $max);
5499
5500    return;
5501}
5502
5503sub _cmd_l_handle_var_name {
5504    my $var_name = shift;
5505
5506    $evalarg = $var_name;
5507
5508    my ($s) = DB::eval();
5509
5510    # Ooops. Bad scalar.
5511    if ($@) {
5512        print {$OUT} "Error: $@\n";
5513        next CMD;
5514    }
5515
5516    # Good scalar. If it's a reference, find what it points to.
5517    $s = CvGV_name($s);
5518    print {$OUT} "Interpreted as: $1 $s\n";
5519    $line = "$1 $s";
5520
5521    # Call self recursively to really do the command.
5522    return _cmd_l_main( $s );
5523}
5524
5525sub _cmd_l_handle_subname {
5526
5527    my $s = $subname;
5528
5529    # De-Perl4.
5530    $subname =~ s/\'/::/;
5531
5532    # Put it in this package unless it starts with ::.
5533    $subname = $package . "::" . $subname unless $subname =~ /::/;
5534
5535    # Put it in CORE::GLOBAL if t doesn't start with :: and
5536    # it doesn't live in this package and it lives in CORE::GLOBAL.
5537    $subname = "CORE::GLOBAL::$s"
5538    if not defined &$subname
5539        and $s !~ /::/
5540        and defined &{"CORE::GLOBAL::$s"};
5541
5542    # Put leading '::' names into 'main::'.
5543    $subname = "main" . $subname if substr( $subname, 0, 2 ) eq "::";
5544
5545    # Get name:start-stop from find_sub, and break this up at
5546    # colons.
5547    my @pieces = split( /:/, find_sub($subname) || $sub{$subname} );
5548
5549    # Pull off start-stop.
5550    my $subrange = pop @pieces;
5551
5552    # If the name contained colons, the split broke it up.
5553    # Put it back together.
5554    $file = join( ':', @pieces );
5555
5556    # If we're not in that file, switch over to it.
5557    if ( $file ne $filename ) {
5558        if (! $slave_editor) {
5559            print {$OUT} "Switching to file '$file'.\n";
5560        }
5561
5562        # Switch debugger's magic structures.
5563        *dbline   = $main::{ '_<' . $file };
5564        $max      = $#dbline;
5565        $filename = $file;
5566    } ## end if ($file ne $filename)
5567
5568    # Subrange is 'start-stop'. If this is less than a window full,
5569    # swap it to 'start+', which will list a window from the start point.
5570    if ($subrange) {
5571        if ( eval($subrange) < -$window ) {
5572            $subrange =~ s/-.*/+/;
5573        }
5574
5575        # Call self recursively to list the range.
5576        return _cmd_l_main( $subrange );
5577    } ## end if ($subrange)
5578
5579    # Couldn't find it.
5580    else {
5581        print {$OUT} "Subroutine $subname not found.\n";
5582        return;
5583    }
5584}
5585
5586sub _cmd_l_empty {
5587    # Compute new range to list.
5588    $incr = $window - 1;
5589
5590    # Recurse to do it.
5591    return _cmd_l_main( $start . '-' . ( $start + $incr ) );
5592}
5593
5594sub _cmd_l_plus {
5595    my ($new_start, $new_incr) = @_;
5596
5597    # Don't reset start for 'l +nnn'.
5598    $start = $new_start if $new_start;
5599
5600    # Increment for list. Use window size if not specified.
5601    # (Allows 'l +' to work.)
5602    $incr = $new_incr || ($window - 1);
5603
5604    # Create a line range we'll understand, and recurse to do it.
5605    return _cmd_l_main( $start . '-' . ( $start + $incr ) );
5606}
5607
5608sub _cmd_l_calc_initial_end_and_i {
5609    my ($spec, $start_match, $end_match) = @_;
5610
5611    # Determine end point; use end of file if not specified.
5612    my $end = ( !defined $start_match ) ? $max :
5613    ( $end_match ? $end_match : $start_match );
5614
5615    # Go on to the end, and then stop.
5616    _minify_to_max(\$end);
5617
5618    # Determine start line.
5619    my $i = $start_match;
5620
5621    if ($i eq '.') {
5622        $i = $spec;
5623    }
5624
5625    $i = _max($i, 1);
5626
5627    $incr = $end - $i;
5628
5629    return ($end, $i);
5630}
5631
5632sub _cmd_l_range {
5633    my ($spec, $current_line, $start_match, $end_match) = @_;
5634
5635    my ($end, $i) =
5636        _cmd_l_calc_initial_end_and_i($spec, $start_match, $end_match);
5637
5638    # If we're running under a slave editor, force it to show the lines.
5639    if ($slave_editor) {
5640        print {$OUT} "\032\032$filename:$i:0\n";
5641        $i = $end;
5642    }
5643    # We're doing it ourselves. We want to show the line and special
5644    # markers for:
5645    # - the current line in execution
5646    # - whether a line is breakable or not
5647    # - whether a line has a break or not
5648    # - whether a line has an action or not
5649    else {
5650        I_TO_END:
5651        for ( ; $i <= $end ; $i++ ) {
5652
5653            # Check for breakpoints and actions.
5654            my ( $stop, $action );
5655            if ($dbline{$i}) {
5656                ( $stop, $action ) = split( /\0/, $dbline{$i} );
5657            }
5658
5659            # ==> if this is the current line in execution,
5660            # : if it's breakable.
5661            my $arrow =
5662            ( $i == $current_line and $filename eq $filename_ini )
5663            ? '==>'
5664            : ( $dbline[$i] + 0 ? ':' : ' ' );
5665
5666            # Add break and action indicators.
5667            $arrow .= 'b' if $stop;
5668            $arrow .= 'a' if $action;
5669
5670            # Print the line.
5671            print {$OUT} "$i$arrow\t", $dbline[$i];
5672
5673            # Move on to the next line. Drop out on an interrupt.
5674            if ($signal) {
5675                $i++;
5676                last I_TO_END;
5677            }
5678        } ## end for (; $i <= $end ; $i++)
5679
5680        # Line the prompt up; print a newline if the last line listed
5681        # didn't have a newline.
5682        if ($dbline[ $i - 1 ] !~ /\n\z/) {
5683            print {$OUT} "\n";
5684        }
5685    } ## end else [ if ($slave_editor)
5686
5687    # Save the point we last listed to in case another relative 'l'
5688    # command is desired. Don't let it run off the end.
5689    $start = $i;
5690    _minify_to_max(\$start);
5691
5692    return;
5693}
5694
5695sub _cmd_l_main {
5696    my $spec = shift;
5697
5698    # If this is '-something', delete any spaces after the dash.
5699    $spec =~ s/\A-\s*\z/-/;
5700
5701    # If the line is '$something', assume this is a scalar containing a
5702    # line number.
5703    # Set up for DB::eval() - evaluate in *user* context.
5704    if ( my ($var_name) = $spec =~ /\A(\$.*)/s ) {
5705        return _cmd_l_handle_var_name($var_name);
5706    }
5707    # l name. Try to find a sub by that name.
5708    elsif ( ($subname) = $spec =~ /\A([\':A-Za-z_][\':\w]*(?:\[.*\])?)/s ) {
5709        return _cmd_l_handle_subname();
5710    }
5711    # Bare 'l' command.
5712    elsif ( $spec !~ /\S/ ) {
5713        return _cmd_l_empty();
5714    }
5715    # l [start]+number_of_lines
5716    elsif ( my ($new_start, $new_incr) = $spec =~ /\A(\d*)\+(\d*)\z/ ) {
5717        return _cmd_l_plus($new_start, $new_incr);
5718    }
5719    # l start-stop or l start,stop
5720    elsif (my ($s, $e) = $spec =~ /^(?:(-?[\d\$\.]+)(?:[-,]([\d\$\.]+))?)?/ ) {
5721        return _cmd_l_range($spec, $line, $s, $e);
5722    }
5723
5724    return;
5725} ## end sub cmd_l
5726
5727sub cmd_l {
5728    my (undef, $line) = @_;
5729
5730    return _cmd_l_main($line);
5731}
5732
5733=head3 C<cmd_L> - list breakpoints, actions, and watch expressions (command)
5734
5735To list breakpoints, the command has to look determine where all of them are
5736first. It starts a C<%had_breakpoints>, which tells us what all files have
5737breakpoints and/or actions. For each file, we switch the C<*dbline> glob (the
5738magic source and breakpoint data structures) to the file, and then look
5739through C<%dbline> for lines with breakpoints and/or actions, listing them
5740out. We look through C<%postponed> not-yet-compiled subroutines that have
5741breakpoints, and through C<%postponed_file> for not-yet-C<require>'d files
5742that have breakpoints.
5743
5744Watchpoints are simpler: we just list the entries in C<@to_watch>.
5745
5746=cut
5747
5748sub _cmd_L_calc_arg {
5749    # If no argument, list everything. Pre-5.8.0 version always lists
5750    # everything
5751    my $arg = shift || 'abw';
5752    if ($CommandSet ne '580')
5753    {
5754        $arg = 'abw';
5755    }
5756
5757    return $arg;
5758}
5759
5760sub _cmd_L_calc_wanted_flags {
5761    my $arg = _cmd_L_calc_arg(shift);
5762
5763    return (map { index($arg, $_) >= 0 ? 1 : 0 } qw(a b w));
5764}
5765
5766
5767sub _cmd_L_handle_breakpoints {
5768    my ($handle_db_line) = @_;
5769
5770    BREAKPOINTS_SCAN:
5771    # Look in all the files with breakpoints...
5772    for my $file ( keys %had_breakpoints ) {
5773
5774        # Temporary switch to this file.
5775        local *dbline = $main::{ '_<' . $file };
5776
5777        # Set up to look through the whole file.
5778        $max = $#dbline;
5779        my $was;    # Flag: did we print something
5780        # in this file?
5781
5782        # For each line in the file ...
5783        for my $i (1 .. $max) {
5784
5785            # We've got something on this line.
5786            if ( defined $dbline{$i} ) {
5787
5788                # Print the header if we haven't.
5789                if (not $was++) {
5790                    print {$OUT} "$file:\n";
5791                }
5792
5793                # Print the line.
5794                print {$OUT} " $i:\t", $dbline[$i];
5795
5796                $handle_db_line->($dbline{$i});
5797
5798                # Quit if the user hit interrupt.
5799                if ($signal) {
5800                    last BREAKPOINTS_SCAN;
5801                }
5802            } ## end if (defined $dbline{$i...
5803        } ## end for my $i (1 .. $max)
5804    } ## end for my $file (keys %had_breakpoints)
5805
5806    return;
5807}
5808
5809sub _cmd_L_handle_postponed_breakpoints {
5810    my ($handle_db_line) = @_;
5811
5812    print {$OUT} "Postponed breakpoints in files:\n";
5813
5814    POSTPONED_SCANS:
5815    for my $file ( keys %postponed_file ) {
5816        my $db = $postponed_file{$file};
5817        print {$OUT} " $file:\n";
5818        for my $line ( sort { $a <=> $b } keys %$db ) {
5819            print {$OUT} "  $line:\n";
5820
5821            $handle_db_line->($db->{$line});
5822
5823            if ($signal) {
5824                last POSTPONED_SCANS;
5825            }
5826        }
5827        if ($signal) {
5828            last POSTPONED_SCANS;
5829        }
5830    }
5831
5832    return;
5833}
5834
5835
5836sub cmd_L {
5837    my $cmd = shift;
5838
5839    my ($action_wanted, $break_wanted, $watch_wanted) =
5840        _cmd_L_calc_wanted_flags(shift);
5841
5842    my $handle_db_line = sub {
5843        my ($l) = @_;
5844
5845        my ( $stop, $action ) = split( /\0/, $l );
5846
5847        if ($stop and $break_wanted) {
5848            print {$OUT} "    break if (", $stop, ")\n"
5849        }
5850
5851        if ($action && $action_wanted) {
5852            print {$OUT} "    action:  ", $action, "\n"
5853        }
5854
5855        return;
5856    };
5857
5858    # Breaks and actions are found together, so we look in the same place
5859    # for both.
5860    if ( $break_wanted or $action_wanted ) {
5861        _cmd_L_handle_breakpoints($handle_db_line);
5862    }
5863
5864    # Look for breaks in not-yet-compiled subs:
5865    if ( %postponed and $break_wanted ) {
5866        print {$OUT} "Postponed breakpoints in subroutines:\n";
5867        my $subname;
5868        SUBS_SCAN:
5869        for $subname ( keys %postponed ) {
5870            print {$OUT} " $subname\t$postponed{$subname}\n";
5871            if ($signal) {
5872                last SUBS_SCAN;
5873            }
5874        }
5875    } ## end if (%postponed and $break_wanted)
5876
5877    # Find files that have not-yet-loaded breaks:
5878    my @have = map {    # Combined keys
5879        keys %{ $postponed_file{$_} }
5880    } keys %postponed_file;
5881
5882    # If there are any, list them.
5883    if ( @have and ( $break_wanted or $action_wanted ) ) {
5884        _cmd_L_handle_postponed_breakpoints($handle_db_line);
5885    } ## end if (@have and ($break_wanted...
5886
5887    if ( %break_on_load and $break_wanted ) {
5888        print {$OUT} "Breakpoints on load:\n";
5889        BREAK_ON_LOAD: for my $filename ( keys %break_on_load ) {
5890            print {$OUT} " $filename\n";
5891            last BREAK_ON_LOAD if $signal;
5892        }
5893    } ## end if (%break_on_load and...
5894
5895    if ($watch_wanted and ( $trace & 2 )) {
5896        print {$OUT} "Watch-expressions:\n" if @to_watch;
5897        TO_WATCH: for my $expr (@to_watch) {
5898            print {$OUT} " $expr\n";
5899            last TO_WATCH if $signal;
5900        }
5901    }
5902
5903    return;
5904} ## end sub cmd_L
5905
5906=head3 C<cmd_M> - list modules (command)
5907
5908Just call C<list_modules>.
5909
5910=cut
5911
5912sub cmd_M {
5913    list_modules();
5914
5915    return;
5916}
5917
5918=head3 C<cmd_o> - options (command)
5919
5920If this is just C<o> by itself, we list the current settings via
5921C<dump_option>. If there's a nonblank value following it, we pass that on to
5922C<parse_options> for processing.
5923
5924=cut
5925
5926sub cmd_o {
5927    my $cmd = shift;
5928    my $opt = shift || '';    # opt[=val]
5929
5930    # Nonblank. Try to parse and process.
5931    if ( $opt =~ /^(\S.*)/ ) {
5932        parse_options($1);
5933    }
5934
5935    # Blank. List the current option settings.
5936    else {
5937        for (@options) {
5938            dump_option($_);
5939        }
5940    }
5941} ## end sub cmd_o
5942
5943=head3 C<cmd_O> - nonexistent in 5.8.x (command)
5944
5945Advises the user that the O command has been renamed.
5946
5947=cut
5948
5949sub cmd_O {
5950    print $OUT "The old O command is now the o command.\n";             # hint
5951    print $OUT "Use 'h' to get current command help synopsis or\n";     #
5952    print $OUT "use 'o CommandSet=pre580' to revert to old usage\n";    #
5953}
5954
5955=head3 C<cmd_v> - view window (command)
5956
5957Uses the C<$preview> variable set in the second C<BEGIN> block (q.v.) to
5958move back a few lines to list the selected line in context. Uses C<cmd_l>
5959to do the actual listing after figuring out the range of line to request.
5960
5961=cut
5962
5963use vars qw($preview);
5964
5965sub cmd_v {
5966    my $cmd  = shift;
5967    my $line = shift;
5968
5969    # Extract the line to list around. (Astute readers will have noted that
5970    # this pattern will match whether or not a numeric line is specified,
5971    # which means that we'll always enter this loop (though a non-numeric
5972    # argument results in no action at all)).
5973    if ( $line =~ /^(\d*)$/ ) {
5974
5975        # Total number of lines to list (a windowful).
5976        $incr = $window - 1;
5977
5978        # Set the start to the argument given (if there was one).
5979        $start = $1 if $1;
5980
5981        # Back up by the context amount.
5982        $start -= $preview;
5983
5984        # Put together a linespec that cmd_l will like.
5985        $line = $start . '-' . ( $start + $incr );
5986
5987        # List the lines.
5988        cmd_l( 'l', $line );
5989    } ## end if ($line =~ /^(\d*)$/)
5990} ## end sub cmd_v
5991
5992=head3 C<cmd_w> - add a watch expression (command)
5993
5994The 5.8 version of this command adds a watch expression if one is specified;
5995it does nothing if entered with no operands.
5996
5997We extract the expression, save it, evaluate it in the user's context, and
5998save the value. We'll re-evaluate it each time the debugger passes a line,
5999and will stop (see the code at the top of the command loop) if the value
6000of any of the expressions changes.
6001
6002=cut
6003
6004sub _add_watch_expr {
6005    my $expr = shift;
6006
6007    # ... save it.
6008    push @to_watch, $expr;
6009
6010    # Parameterize DB::eval and call it to get the expression's value
6011    # in the user's context. This version can handle expressions which
6012    # return a list value.
6013    $evalarg = $expr;
6014    # The &-call is here to ascertain the mutability of @_.
6015    my ($val) = join( ' ', &DB::eval);
6016    $val = ( defined $val ) ? "'$val'" : 'undef';
6017
6018    # Save the current value of the expression.
6019    push @old_watch, $val;
6020
6021    # We are now watching expressions.
6022    $trace |= 2;
6023
6024    return;
6025}
6026
6027sub cmd_w {
6028    my $cmd = shift;
6029
6030    # Null expression if no arguments.
6031    my $expr = shift || '';
6032
6033    # If expression is not null ...
6034    if ( $expr =~ /\A\S/ ) {
6035        _add_watch_expr($expr);
6036    } ## end if ($expr =~ /^(\S.*)/)
6037
6038    # You have to give one to get one.
6039    else {
6040        print $OUT "Adding a watch-expression requires an expression\n";  # hint
6041    }
6042
6043    return;
6044}
6045
6046=head3 C<cmd_W> - delete watch expressions (command)
6047
6048This command accepts either a watch expression to be removed from the list
6049of watch expressions, or C<*> to delete them all.
6050
6051If C<*> is specified, we simply empty the watch expression list and the
6052watch expression value list. We also turn off the bit that says we've got
6053watch expressions.
6054
6055If an expression (or partial expression) is specified, we pattern-match
6056through the expressions and remove the ones that match. We also discard
6057the corresponding values. If no watch expressions are left, we turn off
6058the I<watching expressions> bit.
6059
6060=cut
6061
6062sub cmd_W {
6063    my $cmd  = shift;
6064    my $expr = shift || '';
6065
6066    # Delete them all.
6067    if ( $expr eq '*' ) {
6068
6069        # Not watching now.
6070        $trace &= ~2;
6071
6072        print $OUT "Deleting all watch expressions ...\n";
6073
6074        # And all gone.
6075        @to_watch = @old_watch = ();
6076    }
6077
6078    # Delete one of them.
6079    elsif ( $expr =~ /^(\S.*)/ ) {
6080
6081        # Where we are in the list.
6082        my $i_cnt = 0;
6083
6084        # For each expression ...
6085        foreach (@to_watch) {
6086            my $val = $to_watch[$i_cnt];
6087
6088            # Does this one match the command argument?
6089            if ( $val eq $expr ) {    # =~ m/^\Q$i$/) {
6090                                      # Yes. Turn it off, and its value too.
6091                splice( @to_watch,  $i_cnt, 1 );
6092                splice( @old_watch, $i_cnt, 1 );
6093            }
6094            $i_cnt++;
6095        } ## end foreach (@to_watch)
6096
6097        # We don't bother to turn watching off because
6098        #  a) we don't want to stop calling watchfunction() if it exists
6099        #  b) foreach over a null list doesn't do anything anyway
6100
6101    } ## end elsif ($expr =~ /^(\S.*)/)
6102
6103    # No command arguments entered.
6104    else {
6105        print $OUT
6106          "Deleting a watch-expression requires an expression, or '*' for all\n"
6107          ;    # hint
6108    }
6109} ## end sub cmd_W
6110
6111### END of the API section
6112
6113=head1 SUPPORT ROUTINES
6114
6115These are general support routines that are used in a number of places
6116throughout the debugger.
6117
6118=head2 save
6119
6120save() saves the user's versions of globals that would mess us up in C<@saved>,
6121and installs the versions we like better.
6122
6123=cut
6124
6125sub save {
6126
6127    # Save eval failure, command failure, extended OS error, output field
6128    # separator, input record separator, output record separator and
6129    # the warning setting.
6130    @saved = ( $@, $!, $^E, $,, $/, $\, $^W );
6131
6132    $,  = "";      # output field separator is null string
6133    $/  = "\n";    # input record separator is newline
6134    $\  = "";      # output record separator is null string
6135    $^W = 0;       # warnings are off
6136} ## end sub save
6137
6138=head2 C<print_lineinfo> - show where we are now
6139
6140print_lineinfo prints whatever it is that it is handed; it prints it to the
6141C<$LINEINFO> filehandle instead of just printing it to STDOUT. This allows
6142us to feed line information to a slave editor without messing up the
6143debugger output.
6144
6145=cut
6146
6147sub print_lineinfo {
6148
6149    # Make the terminal sensible if we're not the primary debugger.
6150    resetterm(1) if $LINEINFO eq $OUT and $term_pid != $$;
6151    local $\ = '';
6152    local $, = '';
6153    # $LINEINFO may be undef if $noTTY is set or some other issue.
6154    if ($LINEINFO)
6155    {
6156        print {$LINEINFO} @_;
6157    }
6158} ## end sub print_lineinfo
6159
6160=head2 C<postponed_sub>
6161
6162Handles setting postponed breakpoints in subroutines once they're compiled.
6163For breakpoints, we use C<DB::find_sub> to locate the source file and line
6164range for the subroutine, then mark the file as having a breakpoint,
6165temporarily switch the C<*dbline> glob over to the source file, and then
6166search the given range of lines to find a breakable line. If we find one,
6167we set the breakpoint on it, deleting the breakpoint from C<%postponed>.
6168
6169=cut
6170
6171# The following takes its argument via $evalarg to preserve current @_
6172
6173sub postponed_sub {
6174
6175    # Get the subroutine name.
6176    my $subname = shift;
6177
6178    # If this is a 'break +<n> if <condition>' ...
6179    if ( $postponed{$subname} =~ s/^break\s([+-]?\d+)\s+if\s// ) {
6180
6181        # If there's no offset, use '+0'.
6182        my $offset = $1 || 0;
6183
6184        # find_sub's value is 'fullpath-filename:start-stop'. It's
6185        # possible that the filename might have colons in it too.
6186        my ( $file, $i ) = ( find_sub($subname) =~ /^(.*):(\d+)-.*$/ );
6187        if ($i) {
6188
6189            # We got the start line. Add the offset '+<n>' from
6190            # $postponed{subname}.
6191            $i += $offset;
6192
6193            # Switch to the file this sub is in, temporarily.
6194            local *dbline = $main::{ '_<' . $file };
6195
6196            # No warnings, please.
6197            local $^W = 0;    # != 0 is magical below
6198
6199            # This file's got a breakpoint in it.
6200            $had_breakpoints{$file} |= 1;
6201
6202            # Last line in file.
6203            $max = $#dbline;
6204
6205            # Search forward until we hit a breakable line or get to
6206            # the end of the file.
6207            ++$i until $dbline[$i] != 0 or $i >= $max;
6208
6209            # Copy the breakpoint in and delete it from %postponed.
6210            $dbline{$i} = delete $postponed{$subname};
6211        } ## end if ($i)
6212
6213        # find_sub didn't find the sub.
6214        else {
6215            local $\ = '';
6216            print $OUT "Subroutine $subname not found.\n";
6217        }
6218        return;
6219    } ## end if ($postponed{$subname...
6220    elsif ( $postponed{$subname} eq 'compile' ) { $signal = 1 }
6221
6222    #print $OUT "In postponed_sub for '$subname'.\n";
6223} ## end sub postponed_sub
6224
6225=head2 C<postponed>
6226
6227Called after each required file is compiled, but before it is executed;
6228also called if the name of a just-compiled subroutine is a key of
6229C<%postponed>. Propagates saved breakpoints (from C<b compile>, C<b load>,
6230etc.) into the just-compiled code.
6231
6232If this is a C<require>'d file, the incoming parameter is the glob
6233C<*{"_<$filename"}>, with C<$filename> the name of the C<require>'d file.
6234
6235If it's a subroutine, the incoming parameter is the subroutine name.
6236
6237=cut
6238
6239sub postponed {
6240
6241    # If there's a break, process it.
6242    if ($ImmediateStop) {
6243
6244        # Right, we've stopped. Turn it off.
6245        $ImmediateStop = 0;
6246
6247        # Enter the command loop when DB::DB gets called.
6248        $signal = 1;
6249    }
6250
6251    # If this is a subroutine, let postponed_sub() deal with it.
6252    if (ref(\$_[0]) ne 'GLOB') {
6253        return postponed_sub(@_);
6254    }
6255
6256    # Not a subroutine. Deal with the file.
6257    local *dbline = shift;
6258    my $filename = $dbline;
6259    $filename =~ s/^_<//;
6260    local $\ = '';
6261    $signal = 1, print $OUT "'$filename' loaded...\n"
6262      if $break_on_load{$filename};
6263    print_lineinfo( ' ' x $stack_depth, "Package $filename.\n" ) if $frame;
6264
6265    # Do we have any breakpoints to put in this file?
6266    return unless $postponed_file{$filename};
6267
6268    # Yes. Mark this file as having breakpoints.
6269    $had_breakpoints{$filename} |= 1;
6270
6271    # "Cannot be done: insufficient magic" - we can't just put the
6272    # breakpoints saved in %postponed_file into %dbline by assigning
6273    # the whole hash; we have to do it one item at a time for the
6274    # breakpoints to be set properly.
6275    #%dbline = %{$postponed_file{$filename}};
6276
6277    # Set the breakpoints, one at a time.
6278    my $key;
6279
6280    for $key ( keys %{ $postponed_file{$filename} } ) {
6281
6282        # Stash the saved breakpoint into the current file's magic line array.
6283        $dbline{$key} = ${ $postponed_file{$filename} }{$key};
6284    }
6285
6286    # This file's been compiled; discard the stored breakpoints.
6287    delete $postponed_file{$filename};
6288
6289} ## end sub postponed
6290
6291=head2 C<dumpit>
6292
6293C<dumpit> is the debugger's wrapper around dumpvar.pl.
6294
6295It gets a filehandle (to which C<dumpvar.pl>'s output will be directed) and
6296a reference to a variable (the thing to be dumped) as its input.
6297
6298The incoming filehandle is selected for output (C<dumpvar.pl> is printing to
6299the currently-selected filehandle, thank you very much). The current
6300values of the package globals C<$single> and C<$trace> are backed up in
6301lexicals, and they are turned off (this keeps the debugger from trying
6302to single-step through C<dumpvar.pl> (I think.)). C<$frame> is localized to
6303preserve its current value and it is set to zero to prevent entry/exit
6304messages from printing, and C<$doret> is localized as well and set to -2 to
6305prevent return values from being shown.
6306
6307C<dumpit()> then checks to see if it needs to load C<dumpvar.pl> and
6308tries to load it (note: if you have a C<dumpvar.pl>  ahead of the
6309installed version in C<@INC>, yours will be used instead. Possible security
6310problem?).
6311
6312It then checks to see if the subroutine C<main::dumpValue> is now defined
6313it should have been defined by C<dumpvar.pl>). If it has, C<dumpit()>
6314localizes the globals necessary for things to be sane when C<main::dumpValue()>
6315is called, and picks up the variable to be dumped from the parameter list.
6316
6317It checks the package global C<%options> to see if there's a C<dumpDepth>
6318specified. If not, -1 is assumed; if so, the supplied value gets passed on to
6319C<dumpvar.pl>. This tells C<dumpvar.pl> where to leave off when dumping a
6320structure: -1 means dump everything.
6321
6322C<dumpValue()> is then called if possible; if not, C<dumpit()>just prints a
6323warning.
6324
6325In either case, C<$single>, C<$trace>, C<$frame>, and C<$doret> are restored
6326and we then return to the caller.
6327
6328=cut
6329
6330sub dumpit {
6331
6332    # Save the current output filehandle and switch to the one
6333    # passed in as the first parameter.
6334    my $savout = select(shift);
6335
6336    # Save current settings of $single and $trace, and then turn them off.
6337    my $osingle = $single;
6338    my $otrace  = $trace;
6339    $single = $trace = 0;
6340
6341    # XXX Okay, what do $frame and $doret do, again?
6342    local $frame = 0;
6343    local $doret = -2;
6344
6345    # Load dumpvar.pl unless we've already got the sub we need from it.
6346    unless ( defined &main::dumpValue ) {
6347        do 'dumpvar.pl' or die $@;
6348    }
6349
6350    # If the load succeeded (or we already had dumpvalue()), go ahead
6351    # and dump things.
6352    if ( defined &main::dumpValue ) {
6353        local $\ = '';
6354        local $, = '';
6355        local $" = ' ';
6356        my $v = shift;
6357        my $maxdepth = shift || $option{dumpDepth};
6358        $maxdepth = -1 unless defined $maxdepth;    # -1 means infinite depth
6359        main::dumpValue( $v, $maxdepth );
6360    } ## end if (defined &main::dumpValue)
6361
6362    # Oops, couldn't load dumpvar.pl.
6363    else {
6364        local $\ = '';
6365        print $OUT "dumpvar.pl not available.\n";
6366    }
6367
6368    # Reset $single and $trace to their old values.
6369    $single = $osingle;
6370    $trace  = $otrace;
6371
6372    # Restore the old filehandle.
6373    select($savout);
6374} ## end sub dumpit
6375
6376=head2 C<print_trace>
6377
6378C<print_trace>'s job is to print a stack trace. It does this via the
6379C<dump_trace> routine, which actually does all the ferreting-out of the
6380stack trace data. C<print_trace> takes care of formatting it nicely and
6381printing it to the proper filehandle.
6382
6383Parameters:
6384
6385=over 4
6386
6387=item *
6388
6389The filehandle to print to.
6390
6391=item *
6392
6393How many frames to skip before starting trace.
6394
6395=item *
6396
6397How many frames to print.
6398
6399=item *
6400
6401A flag: if true, print a I<short> trace without filenames, line numbers, or arguments
6402
6403=back
6404
6405The original comment below seems to be noting that the traceback may not be
6406correct if this routine is called in a tied method.
6407
6408=cut
6409
6410# Tied method do not create a context, so may get wrong message:
6411
6412sub print_trace {
6413    local $\ = '';
6414    my $fh = shift;
6415
6416    # If this is going to a slave editor, but we're not the primary
6417    # debugger, reset it first.
6418    resetterm(1)
6419      if $fh        eq $LINEINFO    # slave editor
6420      and $LINEINFO eq $OUT         # normal output
6421      and $term_pid != $$;          # not the primary
6422
6423    # Collect the actual trace information to be formatted.
6424    # This is an array of hashes of subroutine call info.
6425    my @sub = dump_trace( $_[0] + 1, $_[1] );
6426
6427    # Grab the "short report" flag from @_.
6428    my $short = $_[2];              # Print short report, next one for sub name
6429
6430    # Run through the traceback info, format it, and print it.
6431    my $s;
6432    for my $i (0 .. $#sub) {
6433
6434        # Drop out if the user has lost interest and hit control-C.
6435        last if $signal;
6436
6437        # Set the separator so arrays print nice.
6438        local $" = ', ';
6439
6440        # Grab and stringify the arguments if they are there.
6441        my $args =
6442          defined $sub[$i]{args}
6443          ? "(@{ $sub[$i]{args} })"
6444          : '';
6445
6446        # Shorten them up if $maxtrace says they're too long.
6447        $args = ( substr $args, 0, $maxtrace - 3 ) . '...'
6448          if length $args > $maxtrace;
6449
6450        # Get the file name.
6451        my $file = $sub[$i]{file};
6452
6453        # Put in a filename header if short is off.
6454        $file = $file eq '-e' ? $file : "file '$file'" unless $short;
6455
6456        # Get the actual sub's name, and shorten to $maxtrace's requirement.
6457        $s = $sub[$i]{'sub'};
6458        $s = ( substr $s, 0, $maxtrace - 3 ) . '...' if length $s > $maxtrace;
6459
6460        # Short report uses trimmed file and sub names.
6461        if ($short) {
6462            my $sub = @_ >= 4 ? $_[3] : $s;
6463            print $fh "$sub[$i]{context}=$sub$args from $file:$sub[$i]{line}\n";
6464        } ## end if ($short)
6465
6466        # Non-short report includes full names.
6467        else {
6468            print $fh "$sub[$i]{context} = $s$args"
6469              . " called from $file"
6470              . " line $sub[$i]{line}\n";
6471        }
6472    } ## end for my $i (0 .. $#sub)
6473} ## end sub print_trace
6474
6475=head2 dump_trace(skip[,count])
6476
6477Actually collect the traceback information available via C<caller()>. It does
6478some filtering and cleanup of the data, but mostly it just collects it to
6479make C<print_trace()>'s job easier.
6480
6481C<skip> defines the number of stack frames to be skipped, working backwards
6482from the most current. C<count> determines the total number of frames to
6483be returned; all of them (well, the first 10^9) are returned if C<count>
6484is omitted.
6485
6486This routine returns a list of hashes, from most-recent to least-recent
6487stack frame. Each has the following keys and values:
6488
6489=over 4
6490
6491=item * C<context> - C<.> (null), C<$> (scalar), or C<@> (array)
6492
6493=item * C<sub> - subroutine name, or C<eval> information
6494
6495=item * C<args> - undef, or a reference to an array of arguments
6496
6497=item * C<file> - the file in which this item was defined (if any)
6498
6499=item * C<line> - the line on which it was defined
6500
6501=back
6502
6503=cut
6504
6505sub _dump_trace_calc_saved_single_arg
6506{
6507    my ($nothard, $arg) = @_;
6508
6509    my $type;
6510    if ( not defined $arg ) {    # undefined parameter
6511        return "undef";
6512    }
6513
6514    elsif ( $nothard and tied $arg ) {    # tied parameter
6515        return "tied";
6516    }
6517    elsif ( $nothard and $type = ref $arg ) {    # reference
6518        return "ref($type)";
6519    }
6520    else {                                       # can be stringified
6521        local $_ =
6522        "$arg";    # Safe to stringify now - should not call f().
6523
6524        # Backslash any single-quotes or backslashes.
6525        s/([\'\\])/\\$1/g;
6526
6527        # Single-quote it unless it's a number or a colon-separated
6528        # name.
6529        s/(.*)/'$1'/s
6530        unless /^(?: -?[\d.]+ | \*[\w:]* )$/x;
6531
6532        # Turn high-bit characters into meta-whatever.
6533        s/([\200-\377])/sprintf("M-%c",ord($1)&0177)/eg;
6534
6535        # Turn control characters into ^-whatever.
6536        s/([\0-\37\177])/sprintf("^%c",ord($1)^64)/eg;
6537
6538        return $_;
6539    }
6540}
6541
6542sub _dump_trace_calc_save_args {
6543    my ($nothard) = @_;
6544
6545    return [
6546        map { _dump_trace_calc_saved_single_arg($nothard, $_) } @args
6547    ];
6548}
6549
6550sub dump_trace {
6551
6552    # How many levels to skip.
6553    my $skip = shift;
6554
6555    # How many levels to show. (1e9 is a cheap way of saying "all of them";
6556    # it's unlikely that we'll have more than a billion stack frames. If you
6557    # do, you've got an awfully big machine...)
6558    my $count = shift || 1e9;
6559
6560    # We increment skip because caller(1) is the first level *back* from
6561    # the current one.  Add $skip to the count of frames so we have a
6562    # simple stop criterion, counting from $skip to $count+$skip.
6563    $skip++;
6564    $count += $skip;
6565
6566    # These variables are used to capture output from caller();
6567    my ( $p, $file, $line, $sub, $h, $context );
6568
6569    my ( $e, $r, @sub, $args );
6570
6571    # XXX Okay... why'd we do that?
6572    my $nothard = not $frame & 8;
6573    local $frame = 0;
6574
6575    # Do not want to trace this.
6576    my $otrace = $trace;
6577    $trace = 0;
6578
6579    # Start out at the skip count.
6580    # If we haven't reached the number of frames requested, and caller() is
6581    # still returning something, stay in the loop. (If we pass the requested
6582    # number of stack frames, or we run out - caller() returns nothing - we
6583    # quit.
6584    # Up the stack frame index to go back one more level each time.
6585    for (
6586        my $i = $skip ;
6587        $i < $count
6588        and ( $p, $file, $line, $sub, $h, $context, $e, $r ) = caller($i) ;
6589        $i++
6590    )
6591    {
6592
6593        # Go through the arguments and save them for later.
6594        my $save_args = _dump_trace_calc_save_args($nothard);
6595
6596        # If context is true, this is array (@)context.
6597        # If context is false, this is scalar ($) context.
6598        # If neither, context isn't defined. (This is apparently a 'can't
6599        # happen' trap.)
6600        $context = $context ? '@' : ( defined $context ? "\$" : '.' );
6601
6602        # if the sub has args ($h true), make an anonymous array of the
6603        # dumped args.
6604        $args = $h ? $save_args : undef;
6605
6606        # remove trailing newline-whitespace-semicolon-end of line sequence
6607        # from the eval text, if any.
6608        $e =~ s/\n\s*\;\s*\Z// if $e;
6609
6610        # Escape backslashed single-quotes again if necessary.
6611        $e =~ s/([\\\'])/\\$1/g if $e;
6612
6613        # if the require flag is true, the eval text is from a require.
6614        if ($r) {
6615            $sub = "require '$e'";
6616        }
6617
6618        # if it's false, the eval text is really from an eval.
6619        elsif ( defined $r ) {
6620            $sub = "eval '$e'";
6621        }
6622
6623        # If the sub is '(eval)', this is a block eval, meaning we don't
6624        # know what the eval'ed text actually was.
6625        elsif ( $sub eq '(eval)' ) {
6626            $sub = "eval {...}";
6627        }
6628
6629        # Stick the collected information into @sub as an anonymous hash.
6630        push(
6631            @sub,
6632            {
6633                context => $context,
6634                sub     => $sub,
6635                args    => $args,
6636                file    => $file,
6637                line    => $line
6638            }
6639        );
6640
6641        # Stop processing frames if the user hit control-C.
6642        last if $signal;
6643    } ## end for ($i = $skip ; $i < ...
6644
6645    # Restore the trace value again.
6646    $trace = $otrace;
6647    @sub;
6648} ## end sub dump_trace
6649
6650=head2 C<action()>
6651
6652C<action()> takes input provided as the argument to an add-action command,
6653either pre- or post-, and makes sure it's a complete command. It doesn't do
6654any fancy parsing; it just keeps reading input until it gets a string
6655without a trailing backslash.
6656
6657=cut
6658
6659sub action {
6660    my $action = shift;
6661
6662    while ( $action =~ s/\\$// ) {
6663
6664        # We have a backslash on the end. Read more.
6665        $action .= gets();
6666    } ## end while ($action =~ s/\\$//)
6667
6668    # Return the assembled action.
6669    $action;
6670} ## end sub action
6671
6672=head2 unbalanced
6673
6674This routine mostly just packages up a regular expression to be used
6675to check that the thing it's being matched against has properly-matched
6676curly braces.
6677
6678Of note is the definition of the C<$balanced_brace_re> global via C<||=>, which
6679speeds things up by only creating the qr//'ed expression once; if it's
6680already defined, we don't try to define it again. A speed hack.
6681
6682=cut
6683
6684use vars qw($balanced_brace_re);
6685
6686sub unbalanced {
6687
6688    # I hate using globals!
6689    $balanced_brace_re ||= qr{
6690        ^ \{
6691             (?:
6692                 (?> [^{}] + )              # Non-parens without backtracking
6693                |
6694                 (??{ $balanced_brace_re }) # Group with matching parens
6695              ) *
6696          \} $
6697   }x;
6698    return $_[0] !~ m/$balanced_brace_re/;
6699} ## end sub unbalanced
6700
6701=head2 C<gets()>
6702
6703C<gets()> is a primitive (very primitive) routine to read continuations.
6704It was devised for reading continuations for actions.
6705it just reads more input with C<readline()> and returns it.
6706
6707=cut
6708
6709sub gets {
6710    return DB::readline("cont: ");
6711}
6712
6713=head2 C<_db_system()> - handle calls to<system()> without messing up the debugger
6714
6715The C<system()> function assumes that it can just go ahead and use STDIN and
6716STDOUT, but under the debugger, we want it to use the debugger's input and
6717outout filehandles.
6718
6719C<_db_system()> socks away the program's STDIN and STDOUT, and then substitutes
6720the debugger's IN and OUT filehandles for them. It does the C<system()> call,
6721and then puts everything back again.
6722
6723=cut
6724
6725sub _db_system {
6726
6727    # We save, change, then restore STDIN and STDOUT to avoid fork() since
6728    # some non-Unix systems can do system() but have problems with fork().
6729    open( SAVEIN,  "<&STDIN" )  || db_warn("Can't save STDIN");
6730    open( SAVEOUT, ">&STDOUT" ) || db_warn("Can't save STDOUT");
6731    open( STDIN,   "<&IN" )     || db_warn("Can't redirect STDIN");
6732    open( STDOUT,  ">&OUT" )    || db_warn("Can't redirect STDOUT");
6733
6734    # XXX: using csh or tcsh destroys sigint retvals!
6735    system(@_);
6736    open( STDIN,  "<&SAVEIN" )  || db_warn("Can't restore STDIN");
6737    open( STDOUT, ">&SAVEOUT" ) || db_warn("Can't restore STDOUT");
6738    close(SAVEIN);
6739    close(SAVEOUT);
6740
6741    # most of the $? crud was coping with broken cshisms
6742    if ( $? >> 8 ) {
6743        db_warn( "(Command exited ", ( $? >> 8 ), ")\n" );
6744    }
6745    elsif ($?) {
6746        db_warn(
6747            "(Command died of SIG#",
6748            ( $? & 127 ),
6749            ( ( $? & 128 ) ? " -- core dumped" : "" ),
6750            ")", "\n"
6751        );
6752    } ## end elsif ($?)
6753
6754    return $?;
6755
6756} ## end sub system
6757
6758*system = \&_db_system;
6759
6760=head1 TTY MANAGEMENT
6761
6762The subs here do some of the terminal management for multiple debuggers.
6763
6764=head2 setterm
6765
6766Top-level function called when we want to set up a new terminal for use
6767by the debugger.
6768
6769If the C<noTTY> debugger option was set, we'll either use the terminal
6770supplied (the value of the C<noTTY> option), or we'll use C<Term::Rendezvous>
6771to find one. If we're a forked debugger, we call C<resetterm> to try to
6772get a whole new terminal if we can.
6773
6774In either case, we set up the terminal next. If the C<ReadLine> option was
6775true, we'll get a C<Term::ReadLine> object for the current terminal and save
6776the appropriate attributes. We then
6777
6778=cut
6779
6780use vars qw($ornaments);
6781use vars qw($rl_attribs);
6782
6783sub setterm {
6784
6785    # Load Term::Readline, but quietly; don't debug it and don't trace it.
6786    local $frame = 0;
6787    local $doret = -2;
6788    require Term::ReadLine;
6789
6790    # If noTTY is set, but we have a TTY name, go ahead and hook up to it.
6791    if ($notty) {
6792        if ($tty) {
6793            my ( $i, $o ) = split $tty, /,/;
6794            $o = $i unless defined $o;
6795            open( IN,  "<$i" ) or die "Cannot open TTY '$i' for read: $!";
6796            open( OUT, ">$o" ) or die "Cannot open TTY '$o' for write: $!";
6797            $IN  = \*IN;
6798            $OUT = \*OUT;
6799            _autoflush($OUT);
6800        } ## end if ($tty)
6801
6802        # We don't have a TTY - try to find one via Term::Rendezvous.
6803        else {
6804            require Term::Rendezvous;
6805
6806            # See if we have anything to pass to Term::Rendezvous.
6807            # Use $HOME/.perldbtty$$ if not.
6808            my $rv = $ENV{PERLDB_NOTTY} || "$ENV{HOME}/.perldbtty$$";
6809
6810            # Rendezvous and get the filehandles.
6811            my $term_rv = Term::Rendezvous->new( $rv );
6812            $IN  = $term_rv->IN;
6813            $OUT = $term_rv->OUT;
6814        } ## end else [ if ($tty)
6815    } ## end if ($notty)
6816
6817    # We're a daughter debugger. Try to fork off another TTY.
6818    if ( $term_pid eq '-1' ) {    # In a TTY with another debugger
6819        resetterm(2);
6820    }
6821
6822    # If we shouldn't use Term::ReadLine, don't.
6823    if ( !$rl ) {
6824        $term = Term::ReadLine::Stub->new( 'perldb', $IN, $OUT );
6825    }
6826
6827    # We're using Term::ReadLine. Get all the attributes for this terminal.
6828    else {
6829        $term = Term::ReadLine->new( 'perldb', $IN, $OUT );
6830
6831        $rl_attribs = $term->Attribs;
6832        $rl_attribs->{basic_word_break_characters} .= '-:+/*,[])}'
6833          if defined $rl_attribs->{basic_word_break_characters}
6834          and index( $rl_attribs->{basic_word_break_characters}, ":" ) == -1;
6835        $rl_attribs->{special_prefixes} = '$@&%';
6836        $rl_attribs->{completer_word_break_characters} .= '$@&%';
6837        $rl_attribs->{completion_function} = \&db_complete;
6838    } ## end else [ if (!$rl)
6839
6840    # Set up the LINEINFO filehandle.
6841    $LINEINFO = $OUT     unless defined $LINEINFO;
6842    $lineinfo = $console unless defined $lineinfo;
6843
6844    $term->MinLine(2);
6845
6846    load_hist();
6847
6848    if ( $term->Features->{setHistory} and "@hist" ne "?" ) {
6849        $term->SetHistory(@hist);
6850    }
6851
6852    # XXX Ornaments are turned on unconditionally, which is not
6853    # always a good thing.
6854    ornaments($ornaments) if defined $ornaments;
6855    $term_pid = $$;
6856} ## end sub setterm
6857
6858sub load_hist {
6859    $histfile //= option_val("HistFile", undef);
6860    return unless defined $histfile;
6861    open my $fh, "<", $histfile or return;
6862    local $/ = "\n";
6863    @hist = ();
6864    while (<$fh>) {
6865        chomp;
6866        push @hist, $_;
6867    }
6868    close $fh;
6869}
6870
6871sub save_hist {
6872    return unless defined $histfile;
6873    eval { require File::Path } or return;
6874    eval { require File::Basename } or return;
6875    File::Path::mkpath(File::Basename::dirname($histfile));
6876    open my $fh, ">", $histfile or die "Could not open '$histfile': $!";
6877    $histsize //= option_val("HistSize",100);
6878    my @copy = grep { $_ ne '?' } @hist;
6879    my $start = scalar(@copy) > $histsize ? scalar(@copy)-$histsize : 0;
6880    for ($start .. $#copy) {
6881        print $fh "$copy[$_]\n";
6882    }
6883    close $fh or die "Could not write '$histfile': $!";
6884}
6885
6886=head1 GET_FORK_TTY EXAMPLE FUNCTIONS
6887
6888When the process being debugged forks, or the process invokes a command
6889via C<system()> which starts a new debugger, we need to be able to get a new
6890C<IN> and C<OUT> filehandle for the new debugger. Otherwise, the two processes
6891fight over the terminal, and you can never quite be sure who's going to get the
6892input you're typing.
6893
6894C<get_fork_TTY> is a glob-aliased function which calls the real function that
6895is tasked with doing all the necessary operating system mojo to get a new
6896TTY (and probably another window) and to direct the new debugger to read and
6897write there.
6898
6899The debugger provides C<get_fork_TTY> functions which work for TCP
6900socket servers, X11, OS/2, and Mac OS X. Other systems are not
6901supported. You are encouraged to write C<get_fork_TTY> functions which
6902work for I<your> platform and contribute them.
6903
6904=head3 C<socket_get_fork_TTY>
6905
6906=cut
6907
6908sub connect_remoteport {
6909    require IO::Socket;
6910
6911    my $socket = IO::Socket::INET->new(
6912        Timeout  => '10',
6913        PeerAddr => $remoteport,
6914        Proto    => 'tcp',
6915    );
6916    if ( ! $socket ) {
6917        die "Unable to connect to remote host: $remoteport\n";
6918    }
6919    return $socket;
6920}
6921
6922sub socket_get_fork_TTY {
6923    $tty = $LINEINFO = $IN = $OUT = connect_remoteport();
6924
6925    # Do I need to worry about setting $term?
6926
6927    reset_IN_OUT( $IN, $OUT );
6928    return '';
6929}
6930
6931=head3 C<xterm_get_fork_TTY>
6932
6933This function provides the C<get_fork_TTY> function for X11. If a
6934program running under the debugger forks, a new <xterm> window is opened and
6935the subsidiary debugger is directed there.
6936
6937The C<open()> call is of particular note here. We have the new C<xterm>
6938we're spawning route file number 3 to STDOUT, and then execute the C<tty>
6939command (which prints the device name of the TTY we'll want to use for input
6940and output to STDOUT, then C<sleep> for a very long time, routing this output
6941to file number 3. This way we can simply read from the <XT> filehandle (which
6942is STDOUT from the I<commands> we ran) to get the TTY we want to use.
6943
6944Only works if C<xterm> is in your path and C<$ENV{DISPLAY}>, etc. are
6945properly set up.
6946
6947=cut
6948
6949sub xterm_get_fork_TTY {
6950    ( my $name = $0 ) =~ s,^.*[/\\],,s;
6951    open XT,
6952qq[3>&1 xterm -title "Daughter Perl debugger $pids $name" -e sh -c 'tty 1>&3;\
6953 sleep 10000000' |];
6954
6955    # Get the output from 'tty' and clean it up a little.
6956    my $tty = <XT>;
6957    chomp $tty;
6958
6959    $pidprompt = '';    # Shown anyway in titlebar
6960
6961    # We need $term defined or we can not switch to the newly created xterm
6962    if ($tty ne '' && !defined $term) {
6963        require Term::ReadLine;
6964        if ( !$rl ) {
6965            $term = Term::ReadLine::Stub->new( 'perldb', $IN, $OUT );
6966        }
6967        else {
6968            $term = Term::ReadLine->new( 'perldb', $IN, $OUT );
6969        }
6970    }
6971    # There's our new TTY.
6972    return $tty;
6973} ## end sub xterm_get_fork_TTY
6974
6975=head3 C<os2_get_fork_TTY>
6976
6977XXX It behooves an OS/2 expert to write the necessary documentation for this!
6978
6979=cut
6980
6981# This example function resets $IN, $OUT itself
6982my $c_pipe = 0;
6983sub os2_get_fork_TTY { # A simplification of the following (and works without):
6984    local $\  = '';
6985    ( my $name = $0 ) =~ s,^.*[/\\],,s;
6986    my %opt = ( title => "Daughter Perl debugger $pids $name",
6987        ($rl ? (read_by_key => 1) : ()) );
6988    require OS2::Process;
6989    my ($in, $out, $pid) = eval { OS2::Process::io_term(related => 0, %opt) }
6990      or return;
6991    $pidprompt = '';    # Shown anyway in titlebar
6992    reset_IN_OUT($in, $out);
6993    $tty = '*reset*';
6994    return '';          # Indicate that reset_IN_OUT is called
6995} ## end sub os2_get_fork_TTY
6996
6997=head3 C<macosx_get_fork_TTY>
6998
6999The Mac OS X version uses AppleScript to tell Terminal.app to create
7000a new window.
7001
7002=cut
7003
7004# Notes about Terminal.app's AppleScript support,
7005# (aka things that might break in future OS versions).
7006#
7007# The "do script" command doesn't return a reference to the new window
7008# it creates, but since it appears frontmost and windows are enumerated
7009# front to back, we can use "first window" === "window 1".
7010#
7011# Since "do script" is implemented by supplying the argument (plus a
7012# return character) as terminal input, there's a potential race condition
7013# where the debugger could beat the shell to reading the command.
7014# To prevent this, we wait for the screen to clear before proceeding.
7015#
7016# 10.3 and 10.4:
7017# There's no direct accessor for the tty device name, so we fiddle
7018# with the window title options until it says what we want.
7019#
7020# 10.5:
7021# There _is_ a direct accessor for the tty device name, _and_ there's
7022# a new possible component of the window title (the name of the settings
7023# set).  A separate version is needed.
7024
7025my @script_versions=
7026
7027    ([237, <<'__LEOPARD__'],
7028tell application "Terminal"
7029    do script "clear;exec sleep 100000"
7030    tell first tab of first window
7031        copy tty to thetty
7032        set custom title to "forked perl debugger"
7033        set title displays custom title to true
7034        repeat while (length of first paragraph of (get contents)) > 0
7035            delay 0.1
7036        end repeat
7037    end tell
7038end tell
7039thetty
7040__LEOPARD__
7041
7042     [100, <<'__JAGUAR_TIGER__'],
7043tell application "Terminal"
7044    do script "clear;exec sleep 100000"
7045    tell first window
7046        set title displays shell path to false
7047        set title displays window size to false
7048        set title displays file name to false
7049        set title displays device name to true
7050        set title displays custom title to true
7051        set custom title to ""
7052        copy "/dev/" & name to thetty
7053        set custom title to "forked perl debugger"
7054        repeat while (length of first paragraph of (get contents)) > 0
7055            delay 0.1
7056        end repeat
7057    end tell
7058end tell
7059thetty
7060__JAGUAR_TIGER__
7061
7062);
7063
7064sub macosx_get_fork_TTY
7065{
7066    my($version,$script,$pipe,$tty);
7067
7068    return unless $version=$ENV{TERM_PROGRAM_VERSION};
7069    foreach my $entry (@script_versions) {
7070        if ($version>=$entry->[0]) {
7071            $script=$entry->[1];
7072            last;
7073        }
7074    }
7075    return unless defined($script);
7076    return unless open($pipe,'-|','/usr/bin/osascript','-e',$script);
7077    $tty=readline($pipe);
7078    close($pipe);
7079    return unless defined($tty) && $tty =~ m(^/dev/);
7080    chomp $tty;
7081    return $tty;
7082}
7083
7084=head2 C<create_IN_OUT($flags)>
7085
7086Create a new pair of filehandles, pointing to a new TTY. If impossible,
7087try to diagnose why.
7088
7089Flags are:
7090
7091=over 4
7092
7093=item * 1 - Don't know how to create a new TTY.
7094
7095=item * 2 - Debugger has forked, but we can't get a new TTY.
7096
7097=item * 4 - standard debugger startup is happening.
7098
7099=back
7100
7101=cut
7102
7103use vars qw($fork_TTY);
7104
7105sub create_IN_OUT {    # Create a window with IN/OUT handles redirected there
7106
7107    # If we know how to get a new TTY, do it! $in will have
7108    # the TTY name if get_fork_TTY works.
7109    my $in = get_fork_TTY(@_) if defined &get_fork_TTY;
7110
7111    # It used to be that
7112    $in = $fork_TTY if defined $fork_TTY;    # Backward compatibility
7113
7114    if ( not defined $in ) {
7115        my $why = shift;
7116
7117        # We don't know how.
7118        print_help(<<EOP) if $why == 1;
7119I<#########> Forked, but do not know how to create a new B<TTY>. I<#########>
7120EOP
7121
7122        # Forked debugger.
7123        print_help(<<EOP) if $why == 2;
7124I<#########> Daughter session, do not know how to change a B<TTY>. I<#########>
7125  This may be an asynchronous session, so the parent debugger may be active.
7126EOP
7127
7128        # Note that both debuggers are fighting over the same input.
7129        print_help(<<EOP) if $why != 4;
7130  Since two debuggers fight for the same TTY, input is severely entangled.
7131
7132EOP
7133        print_help(<<EOP);
7134  I know how to switch the output to a different window in xterms, OS/2
7135  consoles, and Mac OS X Terminal.app only.  For a manual switch, put the name
7136  of the created I<TTY> in B<\$DB::fork_TTY>, or define a function
7137  B<DB::get_fork_TTY()> returning this.
7138
7139  On I<UNIX>-like systems one can get the name of a I<TTY> for the given window
7140  by typing B<tty>, and disconnect the I<shell> from I<TTY> by B<sleep 1000000>.
7141
7142EOP
7143    } ## end if (not defined $in)
7144    elsif ( $in ne '' ) {
7145        TTY($in);
7146    }
7147    else {
7148        $console = '';    # Indicate no need to open-from-the-console
7149    }
7150    undef $fork_TTY;
7151} ## end sub create_IN_OUT
7152
7153=head2 C<resetterm>
7154
7155Handles rejiggering the prompt when we've forked off a new debugger.
7156
7157If the new debugger happened because of a C<system()> that invoked a
7158program under the debugger, the arrow between the old pid and the new
7159in the prompt has I<two> dashes instead of one.
7160
7161We take the current list of pids and add this one to the end. If there
7162isn't any list yet, we make one up out of the initial pid associated with
7163the terminal and our new pid, sticking an arrow (either one-dashed or
7164two dashed) in between them.
7165
7166If C<CreateTTY> is off, or C<resetterm> was called with no arguments,
7167we don't try to create a new IN and OUT filehandle. Otherwise, we go ahead
7168and try to do that.
7169
7170=cut
7171
7172sub resetterm {    # We forked, so we need a different TTY
7173
7174    # Needs to be passed to create_IN_OUT() as well.
7175    my $in = shift;
7176
7177    # resetterm(2): got in here because of a system() starting a debugger.
7178    # resetterm(1): just forked.
7179    my $systemed = $in > 1 ? '-' : '';
7180
7181    # If there's already a list of pids, add this to the end.
7182    if ($pids) {
7183        $pids =~ s/\]/$systemed->$$]/;
7184    }
7185
7186    # No pid list. Time to make one.
7187    else {
7188        $pids = "[$term_pid->$$]";
7189    }
7190
7191    # The prompt we're going to be using for this debugger.
7192    $pidprompt = $pids;
7193
7194    # We now 0wnz this terminal.
7195    $term_pid = $$;
7196
7197    # Just return if we're not supposed to try to create a new TTY.
7198    return unless $CreateTTY & $in;
7199
7200    # Try to create a new IN/OUT pair.
7201    create_IN_OUT($in);
7202} ## end sub resetterm
7203
7204=head2 C<readline>
7205
7206First, we handle stuff in the typeahead buffer. If there is any, we shift off
7207the next line, print a message saying we got it, add it to the terminal
7208history (if possible), and return it.
7209
7210If there's nothing in the typeahead buffer, check the command filehandle stack.
7211If there are any filehandles there, read from the last one, and return the line
7212if we got one. If not, we pop the filehandle off and close it, and try the
7213next one up the stack.
7214
7215If we've emptied the filehandle stack, we check to see if we've got a socket
7216open, and we read that and return it if we do. If we don't, we just call the
7217core C<readline()> and return its value.
7218
7219=cut
7220
7221sub readline {
7222
7223    # Localize to prevent it from being smashed in the program being debugged.
7224    local $.;
7225
7226    # If there are stacked filehandles to read from ...
7227    # (Handle it before the typeahead, because we may call source/etc. from
7228    # the typeahead.)
7229    while (@cmdfhs) {
7230
7231        # Read from the last one in the stack.
7232        my $line = CORE::readline( $cmdfhs[-1] );
7233
7234        # If we got a line ...
7235        defined $line
7236          ? ( print $OUT ">> $line" and return $line )    # Echo and return
7237          : close pop @cmdfhs;                            # Pop and close
7238    } ## end while (@cmdfhs)
7239
7240    # Pull a line out of the typeahead if there's stuff there.
7241    if (@typeahead) {
7242
7243        # How many lines left.
7244        my $left = @typeahead;
7245
7246        # Get the next line.
7247        my $got = shift @typeahead;
7248
7249        # Print a message saying we got input from the typeahead.
7250        local $\ = '';
7251        print $OUT "auto(-$left)", shift, $got, "\n";
7252
7253        # Add it to the terminal history (if possible).
7254        $term->AddHistory($got)
7255          if length($got) > 1
7256          and defined $term->Features->{addHistory};
7257        return $got;
7258    } ## end if (@typeahead)
7259
7260    # We really need to read some input. Turn off entry/exit trace and
7261    # return value printing.
7262    local $frame = 0;
7263    local $doret = -2;
7264
7265    # Nothing on the filehandle stack. Socket?
7266    if ( ref $OUT and UNIVERSAL::isa( $OUT, 'IO::Socket::INET' ) ) {
7267
7268        # Send anything we have to send.
7269        $OUT->write( join( '', @_ ) );
7270
7271        # Receive anything there is to receive.
7272        my $stuff = '';
7273        my $buf;
7274        my $first_time = 1;
7275
7276        while ($first_time or (length($buf) && ($stuff .= $buf) !~ /\n/))
7277        {
7278            $first_time = 0;
7279            $IN->recv( $buf = '', 2048 );   # XXX "what's wrong with sysread?"
7280                                            # XXX Don't know. You tell me.
7281        }
7282
7283        # What we got.
7284        return $stuff;
7285    } ## end if (ref $OUT and UNIVERSAL::isa...
7286
7287    # No socket. Just read from the terminal.
7288    else {
7289        return $term->readline(@_);
7290    }
7291} ## end sub readline
7292
7293=head1 OPTIONS SUPPORT ROUTINES
7294
7295These routines handle listing and setting option values.
7296
7297=head2 C<dump_option> - list the current value of an option setting
7298
7299This routine uses C<option_val> to look up the value for an option.
7300It cleans up escaped single-quotes and then displays the option and
7301its value.
7302
7303=cut
7304
7305sub dump_option {
7306    my ( $opt, $val ) = @_;
7307    $val = option_val( $opt, 'N/A' );
7308    $val =~ s/([\\\'])/\\$1/g;
7309    printf $OUT "%20s = '%s'\n", $opt, $val;
7310} ## end sub dump_option
7311
7312sub options2remember {
7313    foreach my $k (@RememberOnROptions) {
7314        $option{$k} = option_val( $k, 'N/A' );
7315    }
7316    return %option;
7317}
7318
7319=head2 C<option_val> - find the current value of an option
7320
7321This can't just be a simple hash lookup because of the indirect way that
7322the option values are stored. Some are retrieved by calling a subroutine,
7323some are just variables.
7324
7325You must supply a default value to be used in case the option isn't set.
7326
7327=cut
7328
7329sub option_val {
7330    my ( $opt, $default ) = @_;
7331    my $val;
7332
7333    # Does this option exist, and is it a variable?
7334    # If so, retrieve the value via the value in %optionVars.
7335    if (    defined $optionVars{$opt}
7336        and defined ${ $optionVars{$opt} } )
7337    {
7338        $val = ${ $optionVars{$opt} };
7339    }
7340
7341    # Does this option exist, and it's a subroutine?
7342    # If so, call the subroutine via the ref in %optionAction
7343    # and capture the value.
7344    elsif ( defined $optionAction{$opt}
7345        and defined &{ $optionAction{$opt} } )
7346    {
7347        $val = &{ $optionAction{$opt} }();
7348    }
7349
7350    # If there's an action or variable for the supplied option,
7351    # but no value was set, use the default.
7352    elsif (defined $optionAction{$opt} and not defined $option{$opt}
7353        or defined $optionVars{$opt} and not defined ${ $optionVars{$opt} } )
7354    {
7355        $val = $default;
7356    }
7357
7358    # Otherwise, do the simple hash lookup.
7359    else {
7360        $val = $option{$opt};
7361    }
7362
7363    # If the value isn't defined, use the default.
7364    # Then return whatever the value is.
7365    $val = $default unless defined $val;
7366    $val;
7367} ## end sub option_val
7368
7369=head2 C<parse_options>
7370
7371Handles the parsing and execution of option setting/displaying commands.
7372
7373An option entered by itself is assumed to be I<set me to 1> (the default value)
7374if the option is a boolean one. If not, the user is prompted to enter a valid
7375value or to query the current value (via C<option? >).
7376
7377If C<option=value> is entered, we try to extract a quoted string from the
7378value (if it is quoted). If it's not, we just use the whole value as-is.
7379
7380We load any modules required to service this option, and then we set it: if
7381it just gets stuck in a variable, we do that; if there's a subroutine to
7382handle setting the option, we call that.
7383
7384Finally, if we're running in interactive mode, we display the effect of the
7385user's command back to the terminal, skipping this if we're setting things
7386during initialization.
7387
7388=cut
7389
7390sub parse_options {
7391    my ($s) = @_;
7392    local $\ = '';
7393
7394    my $option;
7395
7396    # These options need a value. Don't allow them to be clobbered by accident.
7397    my %opt_needs_val = map { ( $_ => 1 ) } qw{
7398      dumpDepth arrayDepth hashDepth LineInfo maxTraceLen ornaments windowSize
7399      pager quote ReadLine recallCommand RemotePort ShellBang TTY CommandSet
7400    };
7401
7402    while (length($s)) {
7403        my $val_defaulted;
7404
7405        # Clean off excess leading whitespace.
7406        $s =~ s/^\s+// && next;
7407
7408        # Options are always all word characters, followed by a non-word
7409        # separator.
7410        if ($s !~ s/^(\w+)(\W?)//) {
7411            print {$OUT} "Invalid option '$s'\n";
7412            last;
7413        }
7414        my ( $opt, $sep ) = ( $1, $2 );
7415
7416        # Make sure that such an option exists.
7417        my $matches = ( grep { /^\Q$opt/ && ( $option = $_ ) } @options )
7418          || ( grep { /^\Q$opt/i && ( $option = $_ ) } @options );
7419
7420        unless ($matches) {
7421            print {$OUT} "Unknown option '$opt'\n";
7422            next;
7423        }
7424        if ($matches > 1) {
7425            print {$OUT} "Ambiguous option '$opt'\n";
7426            next;
7427        }
7428        my $val;
7429
7430        # '?' as separator means query, but must have whitespace after it.
7431        if ( "?" eq $sep ) {
7432            if ($s =~ /\A\S/) {
7433                print {$OUT} "Option query '$opt?' followed by non-space '$s'\n" ;
7434
7435                last;
7436            }
7437
7438            #&dump_option($opt);
7439        } ## end if ("?" eq $sep)
7440
7441        # Separator is whitespace (or just a carriage return).
7442        # They're going for a default, which we assume is 1.
7443        elsif ( $sep !~ /\S/ ) {
7444            $val_defaulted = 1;
7445            $val           = "1";   #  this is an evil default; make 'em set it!
7446        }
7447
7448        # Separator is =. Trying to set a value.
7449        elsif ( $sep eq "=" ) {
7450
7451            # If quoted, extract a quoted string.
7452            if ($s =~ s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x) {
7453                my $quote = $1;
7454                ( $val = $2 ) =~ s/\\([$quote\\])/$1/g;
7455            }
7456
7457            # Not quoted. Use the whole thing. Warn about 'option='.
7458            else {
7459                $s =~ s/^(\S*)//;
7460                $val = $1;
7461                print OUT qq(Option better cleared using $opt=""\n)
7462                  unless length $val;
7463            } ## end else [ if (s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x)
7464
7465        } ## end elsif ($sep eq "=")
7466
7467        # "Quoted" with [], <>, or {}.
7468        else {    #{ to "let some poor schmuck bounce on the % key in B<vi>."
7469            my ($end) =
7470              "\\" . substr( ")]>}$sep", index( "([<{", $sep ), 1 );    #}
7471            $s =~ s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)//
7472              or print( $OUT "Unclosed option value '$opt$sep$_'\n" ), last;
7473            ( $val = $1 ) =~ s/\\([\\$end])/$1/g;
7474        } ## end else [ if ("?" eq $sep)
7475
7476        # Exclude non-booleans from getting set to 1 by default.
7477        if ( $opt_needs_val{$option} && $val_defaulted ) {
7478            my $cmd = ( $CommandSet eq '580' ) ? 'o' : 'O';
7479            print {$OUT}
7480"Option '$opt' is non-boolean.  Use '$cmd $option=VAL' to set, '$cmd $option?' to query\n";
7481            next;
7482        } ## end if ($opt_needs_val{$option...
7483
7484        # Save the option value.
7485        $option{$option} = $val if defined $val;
7486
7487        # Load any module that this option requires.
7488        if ( defined($optionRequire{$option}) && defined($val) ) {
7489            eval qq{
7490            local \$frame = 0;
7491            local \$doret = -2;
7492            require '$optionRequire{$option}';
7493            1;
7494            } || die $@   # XXX: shouldn't happen
7495        }
7496
7497        # Set it.
7498        # Stick it in the proper variable if it goes in a variable.
7499        if (defined($optionVars{$option}) && defined($val)) {
7500            ${ $optionVars{$option} } = $val;
7501        }
7502
7503        # Call the appropriate sub if it gets set via sub.
7504        if (defined($optionAction{$option})
7505          && defined (&{ $optionAction{$option} })
7506          && defined ($val))
7507        {
7508          &{ $optionAction{$option} }($val);
7509        }
7510
7511        # Not initialization - echo the value we set it to.
7512        dump_option($option) if ($OUT ne \*STDERR);
7513    } ## end while (length)
7514} ## end sub parse_options
7515
7516=head1 RESTART SUPPORT
7517
7518These routines are used to store (and restore) lists of items in environment
7519variables during a restart.
7520
7521=head2 set_list
7522
7523Set_list packages up items to be stored in a set of environment variables
7524(VAR_n, containing the number of items, and VAR_0, VAR_1, etc., containing
7525the values). Values outside the standard ASCII charset are stored by encoding
7526then as hexadecimal values.
7527
7528=cut
7529
7530sub set_list {
7531    my ( $stem, @list ) = @_;
7532    my $val;
7533
7534    # VAR_n: how many we have. Scalar assignment gets the number of items.
7535    $ENV{"${stem}_n"} = @list;
7536
7537    # Grab each item in the list, escape the backslashes, encode the non-ASCII
7538    # as hex, and then save in the appropriate VAR_0, VAR_1, etc.
7539    for my $i ( 0 .. $#list ) {
7540        $val = $list[$i];
7541        $val =~ s/\\/\\\\/g;
7542        $val =~ s/([\0-\37\177\200-\377])/"\\0x" . unpack('H2',$1)/eg;
7543        $ENV{"${stem}_$i"} = $val;
7544    } ## end for $i (0 .. $#list)
7545} ## end sub set_list
7546
7547=head2 get_list
7548
7549Reverse the set_list operation: grab VAR_n to see how many we should be getting
7550back, and then pull VAR_0, VAR_1. etc. back out.
7551
7552=cut
7553
7554sub get_list {
7555    my $stem = shift;
7556    my @list;
7557    my $n = delete $ENV{"${stem}_n"};
7558    my $val;
7559    for my $i ( 0 .. $n - 1 ) {
7560        $val = delete $ENV{"${stem}_$i"};
7561        $val =~ s/\\((\\)|0x(..))/ $2 ? $2 : pack('H2', $3) /ge;
7562        push @list, $val;
7563    }
7564    @list;
7565} ## end sub get_list
7566
7567=head1 MISCELLANEOUS SIGNAL AND I/O MANAGEMENT
7568
7569=head2 catch()
7570
7571The C<catch()> subroutine is the essence of fast and low-impact. We simply
7572set an already-existing global scalar variable to a constant value. This
7573avoids allocating any memory possibly in the middle of something that will
7574get all confused if we do, particularly under I<unsafe signals>.
7575
7576=cut
7577
7578sub catch {
7579    $signal = 1;
7580    return;    # Put nothing on the stack - malloc/free land!
7581}
7582
7583=head2 C<warn()>
7584
7585C<warn> emits a warning, by joining together its arguments and printing
7586them, with couple of fillips.
7587
7588If the composited message I<doesn't> end with a newline, we automatically
7589add C<$!> and a newline to the end of the message. The subroutine expects $OUT
7590to be set to the filehandle to be used to output warnings; it makes no
7591assumptions about what filehandles are available.
7592
7593=cut
7594
7595sub _db_warn {
7596    my ($msg) = join( "", @_ );
7597    $msg .= ": $!\n" unless $msg =~ /\n$/;
7598    local $\ = '';
7599    print $OUT $msg;
7600} ## end sub warn
7601
7602*warn = \&_db_warn;
7603
7604=head1 INITIALIZATION TTY SUPPORT
7605
7606=head2 C<reset_IN_OUT>
7607
7608This routine handles restoring the debugger's input and output filehandles
7609after we've tried and failed to move them elsewhere.  In addition, it assigns
7610the debugger's output filehandle to $LINEINFO if it was already open there.
7611
7612=cut
7613
7614sub reset_IN_OUT {
7615    my $switch_li = $LINEINFO eq $OUT;
7616
7617    # If there's a term and it's able to get a new tty, try to get one.
7618    if ( $term and $term->Features->{newTTY} ) {
7619        ( $IN, $OUT ) = ( shift, shift );
7620        $term->newTTY( $IN, $OUT );
7621    }
7622
7623    # This term can't get a new tty now. Better luck later.
7624    elsif ($term) {
7625        _db_warn("Too late to set IN/OUT filehandles, enabled on next 'R'!\n");
7626    }
7627
7628    # Set the filehndles up as they were.
7629    else {
7630        ( $IN, $OUT ) = ( shift, shift );
7631    }
7632
7633    # Unbuffer the output filehandle.
7634    _autoflush($OUT);
7635
7636    # Point LINEINFO to the same output filehandle if it was there before.
7637    $LINEINFO = $OUT if $switch_li;
7638} ## end sub reset_IN_OUT
7639
7640=head1 OPTION SUPPORT ROUTINES
7641
7642The following routines are used to process some of the more complicated
7643debugger options.
7644
7645=head2 C<TTY>
7646
7647Sets the input and output filehandles to the specified files or pipes.
7648If the terminal supports switching, we go ahead and do it. If not, and
7649there's already a terminal in place, we save the information to take effect
7650on restart.
7651
7652If there's no terminal yet (for instance, during debugger initialization),
7653we go ahead and set C<$console> and C<$tty> to the file indicated.
7654
7655=cut
7656
7657sub TTY {
7658
7659    if ( @_ and $term and $term->Features->{newTTY} ) {
7660
7661        # This terminal supports switching to a new TTY.
7662        # Can be a list of two files, or on string containing both names,
7663        # comma-separated.
7664        # XXX Should this perhaps be an assignment from @_?
7665        my ( $in, $out ) = shift;
7666        if ( $in =~ /,/ ) {
7667
7668            # Split list apart if supplied.
7669            ( $in, $out ) = split /,/, $in, 2;
7670        }
7671        else {
7672
7673            # Use the same file for both input and output.
7674            $out = $in;
7675        }
7676
7677        # Open file onto the debugger's filehandles, if you can.
7678        open IN,  $in     or die "cannot open '$in' for read: $!";
7679        open OUT, ">$out" or die "cannot open '$out' for write: $!";
7680
7681        # Swap to the new filehandles.
7682        reset_IN_OUT( \*IN, \*OUT );
7683
7684        # Save the setting for later.
7685        return $tty = $in;
7686    } ## end if (@_ and $term and $term...
7687
7688    # Terminal doesn't support new TTY, or doesn't support readline.
7689    # Can't do it now, try restarting.
7690    if ($term and @_) {
7691        _db_warn("Too late to set TTY, enabled on next 'R'!\n");
7692    }
7693
7694    # Useful if done through PERLDB_OPTS:
7695    $console = $tty = shift if @_;
7696
7697    # Return whatever the TTY is.
7698    $tty or $console;
7699} ## end sub TTY
7700
7701=head2 C<noTTY>
7702
7703Sets the C<$notty> global, controlling whether or not the debugger tries to
7704get a terminal to read from. If called after a terminal is already in place,
7705we save the value to use it if we're restarted.
7706
7707=cut
7708
7709sub noTTY {
7710    if ($term) {
7711        _db_warn("Too late to set noTTY, enabled on next 'R'!\n") if @_;
7712    }
7713    $notty = shift if @_;
7714    $notty;
7715} ## end sub noTTY
7716
7717=head2 C<ReadLine>
7718
7719Sets the C<$rl> option variable. If 0, we use C<Term::ReadLine::Stub>
7720(essentially, no C<readline> processing on this I<terminal>). Otherwise, we
7721use C<Term::ReadLine>. Can't be changed after a terminal's in place; we save
7722the value in case a restart is done so we can change it then.
7723
7724=cut
7725
7726sub ReadLine {
7727    if ($term) {
7728        _db_warn("Too late to set ReadLine, enabled on next 'R'!\n") if @_;
7729    }
7730    $rl = shift if @_;
7731    $rl;
7732} ## end sub ReadLine
7733
7734=head2 C<RemotePort>
7735
7736Sets the port that the debugger will try to connect to when starting up.
7737If the terminal's already been set up, we can't do it, but we remember the
7738setting in case the user does a restart.
7739
7740=cut
7741
7742sub RemotePort {
7743    if ($term) {
7744        _db_warn("Too late to set RemotePort, enabled on next 'R'!\n") if @_;
7745    }
7746    $remoteport = shift if @_;
7747    $remoteport;
7748} ## end sub RemotePort
7749
7750=head2 C<tkRunning>
7751
7752Checks with the terminal to see if C<Tk> is running, and returns true or
7753false. Returns false if the current terminal doesn't support C<readline>.
7754
7755=cut
7756
7757sub tkRunning {
7758    if ( ${ $term->Features }{tkRunning} ) {
7759        return $term->tkRunning(@_);
7760    }
7761    else {
7762        local $\ = '';
7763        print $OUT "tkRunning not supported by current ReadLine package.\n";
7764        0;
7765    }
7766} ## end sub tkRunning
7767
7768=head2 C<NonStop>
7769
7770Sets nonstop mode. If a terminal's already been set up, it's too late; the
7771debugger remembers the setting in case you restart, though.
7772
7773=cut
7774
7775sub NonStop {
7776    if ($term) {
7777        _db_warn("Too late to set up NonStop mode, enabled on next 'R'!\n")
7778          if @_;
7779    }
7780    $runnonstop = shift if @_;
7781    $runnonstop;
7782} ## end sub NonStop
7783
7784sub DollarCaretP {
7785    if ($term) {
7786        _db_warn("Some flag changes could not take effect until next 'R'!\n")
7787          if @_;
7788    }
7789    $^P = parse_DollarCaretP_flags(shift) if @_;
7790    expand_DollarCaretP_flags($^P);
7791}
7792
7793=head2 C<pager>
7794
7795Set up the C<$pager> variable. Adds a pipe to the front unless there's one
7796there already.
7797
7798=cut
7799
7800sub pager {
7801    if (@_) {
7802        $pager = shift;
7803        $pager = "|" . $pager unless $pager =~ /^(\+?\>|\|)/;
7804    }
7805    $pager;
7806} ## end sub pager
7807
7808=head2 C<shellBang>
7809
7810Sets the shell escape command, and generates a printable copy to be used
7811in the help.
7812
7813=cut
7814
7815sub shellBang {
7816
7817    # If we got an argument, meta-quote it, and add '\b' if it
7818    # ends in a word character.
7819    if (@_) {
7820        $sh = quotemeta shift;
7821        $sh .= "\\b" if $sh =~ /\w$/;
7822    }
7823
7824    # Generate the printable version for the help:
7825    $psh = $sh;    # copy it
7826    $psh =~ s/\\b$//;        # Take off trailing \b if any
7827    $psh =~ s/\\(.)/$1/g;    # De-escape
7828    $psh;                    # return the printable version
7829} ## end sub shellBang
7830
7831=head2 C<ornaments>
7832
7833If the terminal has its own ornaments, fetch them. Otherwise accept whatever
7834was passed as the argument. (This means you can't override the terminal's
7835ornaments.)
7836
7837=cut
7838
7839sub ornaments {
7840    if ( defined $term ) {
7841
7842        # We don't want to show warning backtraces, but we do want die() ones.
7843        local $warnLevel = 0;
7844        local $dieLevel = 1;
7845
7846        # No ornaments if the terminal doesn't support them.
7847        if (not $term->Features->{ornaments}) {
7848            return '';
7849        }
7850
7851        return (eval { $term->ornaments(@_) } || '');
7852    }
7853
7854    # Use what was passed in if we can't determine it ourselves.
7855    else {
7856        $ornaments = shift;
7857
7858        return $ornaments;
7859    }
7860
7861} ## end sub ornaments
7862
7863=head2 C<recallCommand>
7864
7865Sets the recall command, and builds a printable version which will appear in
7866the help text.
7867
7868=cut
7869
7870sub recallCommand {
7871
7872    # If there is input, metaquote it. Add '\b' if it ends with a word
7873    # character.
7874    if (@_) {
7875        $rc = quotemeta shift;
7876        $rc .= "\\b" if $rc =~ /\w$/;
7877    }
7878
7879    # Build it into a printable version.
7880    $prc = $rc;              # Copy it
7881    $prc =~ s/\\b$//;        # Remove trailing \b
7882    $prc =~ s/\\(.)/$1/g;    # Remove escapes
7883    return $prc;             # Return the printable version
7884} ## end sub recallCommand
7885
7886=head2 C<LineInfo> - where the line number information goes
7887
7888Called with no arguments, returns the file or pipe that line info should go to.
7889
7890Called with an argument (a file or a pipe), it opens that onto the
7891C<LINEINFO> filehandle, unbuffers the filehandle, and then returns the
7892file or pipe again to the caller.
7893
7894=cut
7895
7896sub LineInfo {
7897    if (@_) {
7898        $lineinfo = shift;
7899
7900        #  If this is a valid "thing to be opened for output", tack a
7901        # '>' onto the front.
7902        my $stream = ( $lineinfo =~ /^(\+?\>|\|)/ ) ? $lineinfo : ">$lineinfo";
7903
7904        # If this is a pipe, the stream points to a slave editor.
7905        $slave_editor = ( $stream =~ /^\|/ );
7906
7907        my $new_lineinfo_fh;
7908        # Open it up and unbuffer it.
7909        open ($new_lineinfo_fh , $stream )
7910            or _db_warn("Cannot open '$stream' for write");
7911        $LINEINFO = $new_lineinfo_fh;
7912        _autoflush($LINEINFO);
7913    }
7914
7915    return $lineinfo;
7916} ## end sub LineInfo
7917
7918=head1 COMMAND SUPPORT ROUTINES
7919
7920These subroutines provide functionality for various commands.
7921
7922=head2 C<list_modules>
7923
7924For the C<M> command: list modules loaded and their versions.
7925Essentially just runs through the keys in %INC, picks each package's
7926C<$VERSION> variable, gets the file name, and formats the information
7927for output.
7928
7929=cut
7930
7931sub list_modules {    # versions
7932    my %version;
7933    my $file;
7934
7935    # keys are the "as-loaded" name, values are the fully-qualified path
7936    # to the file itself.
7937    for ( keys %INC ) {
7938        $file = $_;                                # get the module name
7939        s,\.p[lm]$,,i;                             # remove '.pl' or '.pm'
7940        s,/,::,g;                                  # change '/' to '::'
7941        s/^perl5db$/DB/;                           # Special case: debugger
7942                                                   # moves to package DB
7943        s/^Term::ReadLine::readline$/readline/;    # simplify readline
7944
7945        # If the package has a $VERSION package global (as all good packages
7946        # should!) decode it and save as partial message.
7947        my $pkg_version = do { no strict 'refs'; ${ $_ . '::VERSION' } };
7948        if ( defined $pkg_version ) {
7949            $version{$file} = "$pkg_version from ";
7950        }
7951
7952        # Finish up the message with the file the package came from.
7953        $version{$file} .= $INC{$file};
7954    } ## end for (keys %INC)
7955
7956    # Hey, dumpit() formats a hash nicely, so why not use it?
7957    dumpit( $OUT, \%version );
7958} ## end sub list_modules
7959
7960=head2 C<sethelp()>
7961
7962Sets up the monster string used to format and print the help.
7963
7964=head3 HELP MESSAGE FORMAT
7965
7966The help message is a peculiar format unto itself; it mixes C<pod> I<ornaments>
7967(C<< B<> >> C<< I<> >>) with tabs to come up with a format that's fairly
7968easy to parse and portable, but which still allows the help to be a little
7969nicer than just plain text.
7970
7971Essentially, you define the command name (usually marked up with C<< B<> >>
7972and C<< I<> >>), followed by a tab, and then the descriptive text, ending in a
7973newline. The descriptive text can also be marked up in the same way. If you
7974need to continue the descriptive text to another line, start that line with
7975just tabs and then enter the marked-up text.
7976
7977If you are modifying the help text, I<be careful>. The help-string parser is
7978not very sophisticated, and if you don't follow these rules it will mangle the
7979help beyond hope until you fix the string.
7980
7981=cut
7982
7983use vars qw($pre580_help);
7984use vars qw($pre580_summary);
7985
7986sub sethelp {
7987
7988    # XXX: make sure there are tabs between the command and explanation,
7989    #      or print_help will screw up your formatting if you have
7990    #      eeevil ornaments enabled.  This is an insane mess.
7991
7992    $help = "
7993Help is currently only available for the new 5.8 command set.
7994No help is available for the old command set.
7995We assume you know what you're doing if you switch to it.
7996
7997B<T>        Stack trace.
7998B<s> [I<expr>]    Single step [in I<expr>].
7999B<n> [I<expr>]    Next, steps over subroutine calls [in I<expr>].
8000<B<CR>>        Repeat last B<n> or B<s> command.
8001B<r>        Return from current subroutine.
8002B<c> [I<line>|I<sub>]    Continue; optionally inserts a one-time-only breakpoint
8003        at the specified position.
8004B<l> I<min>B<+>I<incr>    List I<incr>+1 lines starting at I<min>.
8005B<l> I<min>B<->I<max>    List lines I<min> through I<max>.
8006B<l> I<line>        List single I<line>.
8007B<l> I<subname>    List first window of lines from subroutine.
8008B<l> I<\$var>        List first window of lines from subroutine referenced by I<\$var>.
8009B<l>        List next window of lines.
8010B<->        List previous window of lines.
8011B<v> [I<line>]    View window around I<line>.
8012B<.>        Return to the executed line.
8013B<f> I<filename>    Switch to viewing I<filename>. File must be already loaded.
8014        I<filename> may be either the full name of the file, or a regular
8015        expression matching the full file name:
8016        B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
8017        Evals (with saved bodies) are considered to be filenames:
8018        B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
8019        (in the order of execution).
8020B</>I<pattern>B</>    Search forwards for I<pattern>; final B</> is optional.
8021B<?>I<pattern>B<?>    Search backwards for I<pattern>; final B<?> is optional.
8022B<L> [I<a|b|w>]        List actions and or breakpoints and or watch-expressions.
8023B<S> [[B<!>]I<pattern>]    List subroutine names [not] matching I<pattern>.
8024B<t> [I<n>]       Toggle trace mode (to max I<n> levels below current stack depth).
8025B<t> [I<n>] I<expr>        Trace through execution of I<expr>.
8026B<b>        Sets breakpoint on current line)
8027B<b> [I<line>] [I<condition>]
8028        Set breakpoint; I<line> defaults to the current execution line;
8029        I<condition> breaks if it evaluates to true, defaults to '1'.
8030B<b> I<subname> [I<condition>]
8031        Set breakpoint at first line of subroutine.
8032B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
8033B<b> B<load> I<filename> Set breakpoint on 'require'ing the given file.
8034B<b> B<postpone> I<subname> [I<condition>]
8035        Set breakpoint at first line of subroutine after
8036        it is compiled.
8037B<b> B<compile> I<subname>
8038        Stop after the subroutine is compiled.
8039B<B> [I<line>]    Delete the breakpoint for I<line>.
8040B<B> I<*>             Delete all breakpoints.
8041B<a> [I<line>] I<command>
8042        Set an action to be done before the I<line> is executed;
8043        I<line> defaults to the current execution line.
8044        Sequence is: check for breakpoint/watchpoint, print line
8045        if necessary, do action, prompt user if necessary,
8046        execute line.
8047B<a>        Does nothing
8048B<A> [I<line>]    Delete the action for I<line>.
8049B<A> I<*>             Delete all actions.
8050B<w> I<expr>        Add a global watch-expression.
8051B<w>             Does nothing
8052B<W> I<expr>        Delete a global watch-expression.
8053B<W> I<*>             Delete all watch-expressions.
8054B<V> [I<pkg> [I<vars>]]    List some (default all) variables in package (default current).
8055        Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
8056B<X> [I<vars>]    Same as \"B<V> I<currentpackage> [I<vars>]\".
8057B<x> I<expr>        Evals expression in list context, dumps the result.
8058B<m> I<expr>        Evals expression in list context, prints methods callable
8059        on the first element of the result.
8060B<m> I<class>        Prints methods callable via the given class.
8061B<M>        Show versions of loaded modules.
8062B<i> I<class>       Prints nested parents of given class.
8063B<e>         Display current thread id.
8064B<E>         Display all thread ids the current one will be identified: <n>.
8065B<y> [I<n> [I<Vars>]]   List lexicals in higher scope <n>.  Vars same as B<V>.
8066
8067B<<> ?            List Perl commands to run before each prompt.
8068B<<> I<expr>        Define Perl command to run before each prompt.
8069B<<<> I<expr>        Add to the list of Perl commands to run before each prompt.
8070B<< *>                Delete the list of perl commands to run before each prompt.
8071B<>> ?            List Perl commands to run after each prompt.
8072B<>> I<expr>        Define Perl command to run after each prompt.
8073B<>>B<>> I<expr>        Add to the list of Perl commands to run after each prompt.
8074B<>>B< *>        Delete the list of Perl commands to run after each prompt.
8075B<{> I<db_command>    Define debugger command to run before each prompt.
8076B<{> ?            List debugger commands to run before each prompt.
8077B<{{> I<db_command>    Add to the list of debugger commands to run before each prompt.
8078B<{ *>             Delete the list of debugger commands to run before each prompt.
8079B<$prc> I<number>    Redo a previous command (default previous command).
8080B<$prc> I<-number>    Redo number'th-to-last command.
8081B<$prc> I<pattern>    Redo last command that started with I<pattern>.
8082        See 'B<O> I<recallCommand>' too.
8083B<$psh$psh> I<cmd>      Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
8084      . (
8085        $rc eq $sh
8086        ? ""
8087        : "
8088B<$psh> [I<cmd>] Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")."
8089      ) . "
8090        See 'B<O> I<shellBang>' too.
8091B<source> I<file>     Execute I<file> containing debugger commands (may nest).
8092B<save> I<file>       Save current debugger session (actual history) to I<file>.
8093B<rerun>           Rerun session to current position.
8094B<rerun> I<n>         Rerun session to numbered command.
8095B<rerun> I<-n>        Rerun session to number'th-to-last command.
8096B<H> I<-number>    Display last number commands (default all).
8097B<H> I<*>          Delete complete history.
8098B<p> I<expr>        Same as \"I<print {DB::OUT} expr>\" in current package.
8099B<|>I<dbcmd>        Run debugger command, piping DB::OUT to current pager.
8100B<||>I<dbcmd>        Same as B<|>I<dbcmd> but DB::OUT is temporarily select()ed as well.
8101B<\=> [I<alias> I<value>]    Define a command alias, or list current aliases.
8102I<command>        Execute as a perl statement in current package.
8103B<R>        Pure-man-restart of debugger, some of debugger state
8104        and command-line options may be lost.
8105        Currently the following settings are preserved:
8106        history, breakpoints and actions, debugger B<O>ptions
8107        and the following command-line options: I<-w>, I<-I>, I<-e>.
8108
8109B<o> [I<opt>] ...    Set boolean option to true
8110B<o> [I<opt>B<?>]    Query options
8111B<o> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ...
8112        Set options.  Use quotes if spaces in value.
8113    I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
8114    I<pager>            program for output of \"|cmd\";
8115    I<tkRunning>            run Tk while prompting (with ReadLine);
8116    I<signalLevel> I<warnLevel> I<dieLevel>    level of verbosity;
8117    I<inhibit_exit>        Allows stepping off the end of the script.
8118    I<ImmediateStop>        Debugger should stop as early as possible.
8119    I<RemotePort>            Remote hostname:port for remote debugging
8120  The following options affect what happens with B<V>, B<X>, and B<x> commands:
8121    I<arrayDepth>, I<hashDepth>     print only first N elements ('' for all);
8122    I<compactDump>, I<veryCompact>     change style of array and hash dump;
8123    I<globPrint>             whether to print contents of globs;
8124    I<DumpDBFiles>         dump arrays holding debugged files;
8125    I<DumpPackages>         dump symbol tables of packages;
8126    I<DumpReused>             dump contents of \"reused\" addresses;
8127    I<quote>, I<HighBit>, I<undefPrint>     change style of string dump;
8128    I<bareStringify>         Do not print the overload-stringified value;
8129  Other options include:
8130    I<PrintRet>        affects printing of return value after B<r> command,
8131    I<frame>        affects printing messages on subroutine entry/exit.
8132    I<AutoTrace>    affects printing messages on possible breaking points.
8133    I<maxTraceLen>    gives max length of evals/args listed in stack trace.
8134    I<ornaments>     affects screen appearance of the command line.
8135    I<CreateTTY>     bits control attempts to create a new TTY on events:
8136            1: on fork()    2: debugger is started inside debugger
8137            4: on startup
8138    During startup options are initialized from \$ENV{PERLDB_OPTS}.
8139    You can put additional initialization options I<TTY>, I<noTTY>,
8140    I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
8141    B<R> after you set them).
8142
8143B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction.
8144B<h>        Summary of debugger commands.
8145B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
8146B<h h>        Long help for debugger commands
8147B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the
8148        named Perl I<manpage>, or on B<$doccmd> itself if omitted.
8149        Set B<\$DB::doccmd> to change viewer.
8150
8151Type '|h h' for a paged display if this was too hard to read.
8152
8153";    # Fix balance of vi % matching: }}}}
8154
8155    #  note: tabs in the following section are not-so-helpful
8156    $summary = <<"END_SUM";
8157I<List/search source lines:>               I<Control script execution:>
8158  B<l> [I<ln>|I<sub>]  List source code            B<T>           Stack trace
8159  B<-> or B<.>      List previous/current line  B<s> [I<expr>]    Single step [in expr]
8160  B<v> [I<line>]    View around line            B<n> [I<expr>]    Next, steps over subs
8161  B<f> I<filename>  View source in file         <B<CR>/B<Enter>>  Repeat last B<n> or B<s>
8162  B</>I<pattern>B</> B<?>I<patt>B<?>   Search forw/backw    B<r>           Return from subroutine
8163  B<M>           Show module versions        B<c> [I<ln>|I<sub>]  Continue until position
8164I<Debugger controls:>                        B<L>           List break/watch/actions
8165  B<o> [...]     Set debugger options        B<t> [I<n>] [I<expr>] Toggle trace [max depth] ][trace expr]
8166  B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
8167  B<$prc> [I<N>|I<pat>]   Redo a previous command     B<B> I<ln|*>      Delete a/all breakpoints
8168  B<H> [I<-num>]    Display last num commands   B<a> [I<ln>] I<cmd>  Do cmd before line
8169  B<=> [I<a> I<val>]   Define/list an alias        B<A> I<ln|*>      Delete a/all actions
8170  B<h> [I<db_cmd>]  Get help on command         B<w> I<expr>      Add a watch expression
8171  B<h h>         Complete help page          B<W> I<expr|*>    Delete a/all watch exprs
8172  B<|>[B<|>]I<db_cmd>  Send output to pager        B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
8173  B<q> or B<^D>     Quit                        B<R>           Attempt a restart
8174I<Data Examination:>     B<expr>     Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
8175  B<x>|B<m> I<expr>       Evals expr in list context, dumps the result or lists methods.
8176  B<p> I<expr>         Print expression (uses script's current package).
8177  B<S> [[B<!>]I<pat>]     List subroutine names [not] matching pattern
8178  B<V> [I<Pk> [I<Vars>]]  List Variables in Package.  Vars can be ~pattern or !pattern.
8179  B<X> [I<Vars>]       Same as \"B<V> I<current_package> [I<Vars>]\".  B<i> I<class> inheritance tree.
8180  B<y> [I<n> [I<Vars>]]   List lexicals in higher scope <n>.  Vars same as B<V>.
8181  B<e>     Display thread id     B<E> Display all thread ids.
8182For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
8183END_SUM
8184
8185    # ')}}; # Fix balance of vi % matching
8186
8187    # and this is really numb...
8188    $pre580_help = "
8189B<T>        Stack trace.
8190B<s> [I<expr>]    Single step [in I<expr>].
8191B<n> [I<expr>]    Next, steps over subroutine calls [in I<expr>].
8192B<CR>>        Repeat last B<n> or B<s> command.
8193B<r>        Return from current subroutine.
8194B<c> [I<line>|I<sub>]    Continue; optionally inserts a one-time-only breakpoint
8195        at the specified position.
8196B<l> I<min>B<+>I<incr>    List I<incr>+1 lines starting at I<min>.
8197B<l> I<min>B<->I<max>    List lines I<min> through I<max>.
8198B<l> I<line>        List single I<line>.
8199B<l> I<subname>    List first window of lines from subroutine.
8200B<l> I<\$var>        List first window of lines from subroutine referenced by I<\$var>.
8201B<l>        List next window of lines.
8202B<->        List previous window of lines.
8203B<w> [I<line>]    List window around I<line>.
8204B<.>        Return to the executed line.
8205B<f> I<filename>    Switch to viewing I<filename>. File must be already loaded.
8206        I<filename> may be either the full name of the file, or a regular
8207        expression matching the full file name:
8208        B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
8209        Evals (with saved bodies) are considered to be filenames:
8210        B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
8211        (in the order of execution).
8212B</>I<pattern>B</>    Search forwards for I<pattern>; final B</> is optional.
8213B<?>I<pattern>B<?>    Search backwards for I<pattern>; final B<?> is optional.
8214B<L>        List all breakpoints and actions.
8215B<S> [[B<!>]I<pattern>]    List subroutine names [not] matching I<pattern>.
8216B<t> [I<n>]       Toggle trace mode (to max I<n> levels below current stack depth) .
8217B<t> [I<n>] I<expr>        Trace through execution of I<expr>.
8218B<b> [I<line>] [I<condition>]
8219        Set breakpoint; I<line> defaults to the current execution line;
8220        I<condition> breaks if it evaluates to true, defaults to '1'.
8221B<b> I<subname> [I<condition>]
8222        Set breakpoint at first line of subroutine.
8223B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
8224B<b> B<load> I<filename> Set breakpoint on 'require'ing the given file.
8225B<b> B<postpone> I<subname> [I<condition>]
8226        Set breakpoint at first line of subroutine after
8227        it is compiled.
8228B<b> B<compile> I<subname>
8229        Stop after the subroutine is compiled.
8230B<d> [I<line>]    Delete the breakpoint for I<line>.
8231B<D>        Delete all breakpoints.
8232B<a> [I<line>] I<command>
8233        Set an action to be done before the I<line> is executed;
8234        I<line> defaults to the current execution line.
8235        Sequence is: check for breakpoint/watchpoint, print line
8236        if necessary, do action, prompt user if necessary,
8237        execute line.
8238B<a> [I<line>]    Delete the action for I<line>.
8239B<A>        Delete all actions.
8240B<W> I<expr>        Add a global watch-expression.
8241B<W>        Delete all watch-expressions.
8242B<V> [I<pkg> [I<vars>]]    List some (default all) variables in package (default current).
8243        Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
8244B<X> [I<vars>]    Same as \"B<V> I<currentpackage> [I<vars>]\".
8245B<x> I<expr>        Evals expression in list context, dumps the result.
8246B<m> I<expr>        Evals expression in list context, prints methods callable
8247        on the first element of the result.
8248B<m> I<class>        Prints methods callable via the given class.
8249
8250B<<> ?            List Perl commands to run before each prompt.
8251B<<> I<expr>        Define Perl command to run before each prompt.
8252B<<<> I<expr>        Add to the list of Perl commands to run before each prompt.
8253B<>> ?            List Perl commands to run after each prompt.
8254B<>> I<expr>        Define Perl command to run after each prompt.
8255B<>>B<>> I<expr>        Add to the list of Perl commands to run after each prompt.
8256B<{> I<db_command>    Define debugger command to run before each prompt.
8257B<{> ?            List debugger commands to run before each prompt.
8258B<{{> I<db_command>    Add to the list of debugger commands to run before each prompt.
8259B<$prc> I<number>    Redo a previous command (default previous command).
8260B<$prc> I<-number>    Redo number'th-to-last command.
8261B<$prc> I<pattern>    Redo last command that started with I<pattern>.
8262        See 'B<O> I<recallCommand>' too.
8263B<$psh$psh> I<cmd>      Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
8264      . (
8265        $rc eq $sh
8266        ? ""
8267        : "
8268B<$psh> [I<cmd>]     Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")."
8269      ) . "
8270        See 'B<O> I<shellBang>' too.
8271B<source> I<file>        Execute I<file> containing debugger commands (may nest).
8272B<H> I<-number>    Display last number commands (default all).
8273B<p> I<expr>        Same as \"I<print {DB::OUT} expr>\" in current package.
8274B<|>I<dbcmd>        Run debugger command, piping DB::OUT to current pager.
8275B<||>I<dbcmd>        Same as B<|>I<dbcmd> but DB::OUT is temporarilly select()ed as well.
8276B<\=> [I<alias> I<value>]    Define a command alias, or list current aliases.
8277I<command>        Execute as a perl statement in current package.
8278B<v>        Show versions of loaded modules.
8279B<R>        Pure-man-restart of debugger, some of debugger state
8280        and command-line options may be lost.
8281        Currently the following settings are preserved:
8282        history, breakpoints and actions, debugger B<O>ptions
8283        and the following command-line options: I<-w>, I<-I>, I<-e>.
8284
8285B<O> [I<opt>] ...    Set boolean option to true
8286B<O> [I<opt>B<?>]    Query options
8287B<O> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ...
8288        Set options.  Use quotes if spaces in value.
8289    I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
8290    I<pager>            program for output of \"|cmd\";
8291    I<tkRunning>            run Tk while prompting (with ReadLine);
8292    I<signalLevel> I<warnLevel> I<dieLevel>    level of verbosity;
8293    I<inhibit_exit>        Allows stepping off the end of the script.
8294    I<ImmediateStop>        Debugger should stop as early as possible.
8295    I<RemotePort>            Remote hostname:port for remote debugging
8296  The following options affect what happens with B<V>, B<X>, and B<x> commands:
8297    I<arrayDepth>, I<hashDepth>     print only first N elements ('' for all);
8298    I<compactDump>, I<veryCompact>     change style of array and hash dump;
8299    I<globPrint>             whether to print contents of globs;
8300    I<DumpDBFiles>         dump arrays holding debugged files;
8301    I<DumpPackages>         dump symbol tables of packages;
8302    I<DumpReused>             dump contents of \"reused\" addresses;
8303    I<quote>, I<HighBit>, I<undefPrint>     change style of string dump;
8304    I<bareStringify>         Do not print the overload-stringified value;
8305  Other options include:
8306    I<PrintRet>        affects printing of return value after B<r> command,
8307    I<frame>        affects printing messages on subroutine entry/exit.
8308    I<AutoTrace>    affects printing messages on possible breaking points.
8309    I<maxTraceLen>    gives max length of evals/args listed in stack trace.
8310    I<ornaments>     affects screen appearance of the command line.
8311    I<CreateTTY>     bits control attempts to create a new TTY on events:
8312            1: on fork()    2: debugger is started inside debugger
8313            4: on startup
8314    During startup options are initialized from \$ENV{PERLDB_OPTS}.
8315    You can put additional initialization options I<TTY>, I<noTTY>,
8316    I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
8317    B<R> after you set them).
8318
8319B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction.
8320B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
8321B<h h>        Summary of debugger commands.
8322B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the
8323        named Perl I<manpage>, or on B<$doccmd> itself if omitted.
8324        Set B<\$DB::doccmd> to change viewer.
8325
8326Type '|h' for a paged display if this was too hard to read.
8327
8328";    # Fix balance of vi % matching: }}}}
8329
8330    #  note: tabs in the following section are not-so-helpful
8331    $pre580_summary = <<"END_SUM";
8332I<List/search source lines:>               I<Control script execution:>
8333  B<l> [I<ln>|I<sub>]  List source code            B<T>           Stack trace
8334  B<-> or B<.>      List previous/current line  B<s> [I<expr>]    Single step [in expr]
8335  B<w> [I<line>]    List around line            B<n> [I<expr>]    Next, steps over subs
8336  B<f> I<filename>  View source in file         <B<CR>/B<Enter>>  Repeat last B<n> or B<s>
8337  B</>I<pattern>B</> B<?>I<patt>B<?>   Search forw/backw    B<r>           Return from subroutine
8338  B<v>           Show versions of modules    B<c> [I<ln>|I<sub>]  Continue until position
8339I<Debugger controls:>                        B<L>           List break/watch/actions
8340  B<O> [...]     Set debugger options        B<t> [I<expr>]    Toggle trace [trace expr]
8341  B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
8342  B<$prc> [I<N>|I<pat>]   Redo a previous command     B<d> [I<ln>] or B<D> Delete a/all breakpoints
8343  B<H> [I<-num>]    Display last num commands   B<a> [I<ln>] I<cmd>  Do cmd before line
8344  B<=> [I<a> I<val>]   Define/list an alias        B<W> I<expr>      Add a watch expression
8345  B<h> [I<db_cmd>]  Get help on command         B<A> or B<W>      Delete all actions/watch
8346  B<|>[B<|>]I<db_cmd>  Send output to pager        B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
8347  B<q> or B<^D>     Quit                        B<R>           Attempt a restart
8348I<Data Examination:>     B<expr>     Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
8349  B<x>|B<m> I<expr>       Evals expr in list context, dumps the result or lists methods.
8350  B<p> I<expr>         Print expression (uses script's current package).
8351  B<S> [[B<!>]I<pat>]     List subroutine names [not] matching pattern
8352  B<V> [I<Pk> [I<Vars>]]  List Variables in Package.  Vars can be ~pattern or !pattern.
8353  B<X> [I<Vars>]       Same as \"B<V> I<current_package> [I<Vars>]\".
8354  B<y> [I<n> [I<Vars>]]   List lexicals in higher scope <n>.  Vars same as B<V>.
8355For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
8356END_SUM
8357
8358    # ')}}; # Fix balance of vi % matching
8359
8360} ## end sub sethelp
8361
8362=head2 C<print_help()>
8363
8364Most of what C<print_help> does is just text formatting. It finds the
8365C<B> and C<I> ornaments, cleans them off, and substitutes the proper
8366terminal control characters to simulate them (courtesy of
8367C<Term::ReadLine::TermCap>).
8368
8369=cut
8370
8371sub print_help {
8372    my $help_str = shift;
8373
8374    # Restore proper alignment destroyed by eeevil I<> and B<>
8375    # ornaments: A pox on both their houses!
8376    #
8377    # A help command will have everything up to and including
8378    # the first tab sequence padded into a field 16 (or if indented 20)
8379    # wide.  If it's wider than that, an extra space will be added.
8380    $help_str =~ s{
8381        ^                       # only matters at start of line
8382          ( \040{4} | \t )*     # some subcommands are indented
8383          ( < ?                 # so <CR> works
8384            [BI] < [^\t\n] + )  # find an eeevil ornament
8385          ( \t+ )               # original separation, discarded
8386          ( .* )                # this will now start (no earlier) than
8387                                # column 16
8388    } {
8389        my($leadwhite, $command, $midwhite, $text) = ($1, $2, $3, $4);
8390        my $clean = $command;
8391        $clean =~ s/[BI]<([^>]*)>/$1/g;
8392
8393        # replace with this whole string:
8394        ($leadwhite ? " " x 4 : "")
8395      . $command
8396      . ((" " x (16 + ($leadwhite ? 4 : 0) - length($clean))) || " ")
8397      . $text;
8398
8399    }mgex;
8400
8401    $help_str =~ s{                          # handle bold ornaments
8402       B < ( [^>] + | > ) >
8403    } {
8404          $Term::ReadLine::TermCap::rl_term_set[2]
8405        . $1
8406        . $Term::ReadLine::TermCap::rl_term_set[3]
8407    }gex;
8408
8409    $help_str =~ s{                         # handle italic ornaments
8410       I < ( [^>] + | > ) >
8411    } {
8412          $Term::ReadLine::TermCap::rl_term_set[0]
8413        . $1
8414        . $Term::ReadLine::TermCap::rl_term_set[1]
8415    }gex;
8416
8417    local $\ = '';
8418    print {$OUT} $help_str;
8419
8420    return;
8421} ## end sub print_help
8422
8423=head2 C<fix_less>
8424
8425This routine does a lot of gyrations to be sure that the pager is C<less>.
8426It checks for C<less> masquerading as C<more> and records the result in
8427C<$fixed_less> so we don't have to go through doing the stats again.
8428
8429=cut
8430
8431use vars qw($fixed_less);
8432
8433sub _calc_is_less {
8434    if ($pager =~ /\bless\b/)
8435    {
8436        return 1;
8437    }
8438    elsif ($pager =~ /\bmore\b/)
8439    {
8440        # Nope, set to more. See what's out there.
8441        my @st_more = stat('/usr/bin/more');
8442        my @st_less = stat('/usr/bin/less');
8443
8444        # is it really less, pretending to be more?
8445        return (
8446            @st_more
8447            && @st_less
8448            && $st_more[0] == $st_less[0]
8449            && $st_more[1] == $st_less[1]
8450        );
8451    }
8452    else {
8453        return;
8454    }
8455}
8456
8457sub fix_less {
8458
8459    # We already know if this is set.
8460    return if $fixed_less;
8461
8462    # changes environment!
8463    # 'r' added so we don't do (slow) stats again.
8464    $fixed_less = 1 if _calc_is_less();
8465
8466    return;
8467} ## end sub fix_less
8468
8469=head1 DIE AND WARN MANAGEMENT
8470
8471=head2 C<diesignal>
8472
8473C<diesignal> is a just-drop-dead C<die> handler. It's most useful when trying
8474to debug a debugger problem.
8475
8476It does its best to report the error that occurred, and then forces the
8477program, debugger, and everything to die.
8478
8479=cut
8480
8481sub diesignal {
8482
8483    # No entry/exit messages.
8484    local $frame = 0;
8485
8486    # No return value prints.
8487    local $doret = -2;
8488
8489    # set the abort signal handling to the default (just terminate).
8490    $SIG{'ABRT'} = 'DEFAULT';
8491
8492    # If we enter the signal handler recursively, kill myself with an
8493    # abort signal (so we just terminate).
8494    kill 'ABRT', $$ if $panic++;
8495
8496    # If we can show detailed info, do so.
8497    if ( defined &Carp::longmess ) {
8498
8499        # Don't recursively enter the warn handler, since we're carping.
8500        local $SIG{__WARN__} = '';
8501
8502        # Skip two levels before reporting traceback: we're skipping
8503        # mydie and confess.
8504        local $Carp::CarpLevel = 2;    # mydie + confess
8505
8506        # Tell us all about it.
8507        _db_warn( Carp::longmess("Signal @_") );
8508    }
8509
8510    # No Carp. Tell us about the signal as best we can.
8511    else {
8512        local $\ = '';
8513        print $DB::OUT "Got signal @_\n";
8514    }
8515
8516    # Drop dead.
8517    kill 'ABRT', $$;
8518} ## end sub diesignal
8519
8520=head2 C<dbwarn>
8521
8522The debugger's own default C<$SIG{__WARN__}> handler. We load C<Carp> to
8523be able to get a stack trace, and output the warning message vi C<DB::dbwarn()>.
8524
8525=cut
8526
8527sub dbwarn {
8528
8529    # No entry/exit trace.
8530    local $frame = 0;
8531
8532    # No return value printing.
8533    local $doret = -2;
8534
8535    # Turn off warn and die handling to prevent recursive entries to this
8536    # routine.
8537    local $SIG{__WARN__} = '';
8538    local $SIG{__DIE__}  = '';
8539
8540    # Load Carp if we can. If $^S is false (current thing being compiled isn't
8541    # done yet), we may not be able to do a require.
8542    eval { require Carp }
8543      if defined $^S;    # If error/warning during compilation,
8544                         # require may be broken.
8545
8546    # Use the core warn() unless Carp loaded OK.
8547    CORE::warn( @_,
8548        "\nCannot print stack trace, load with -MCarp option to see stack" ),
8549      return
8550      unless defined &Carp::longmess;
8551
8552    # Save the current values of $single and $trace, and then turn them off.
8553    my ( $mysingle, $mytrace ) = ( $single, $trace );
8554    $single = 0;
8555    $trace  = 0;
8556
8557    # We can call Carp::longmess without its being "debugged" (which we
8558    # don't want - we just want to use it!). Capture this for later.
8559    my $mess = Carp::longmess(@_);
8560
8561    # Restore $single and $trace to their original values.
8562    ( $single, $trace ) = ( $mysingle, $mytrace );
8563
8564    # Use the debugger's own special way of printing warnings to print
8565    # the stack trace message.
8566    _db_warn($mess);
8567} ## end sub dbwarn
8568
8569=head2 C<dbdie>
8570
8571The debugger's own C<$SIG{__DIE__}> handler. Handles providing a stack trace
8572by loading C<Carp> and calling C<Carp::longmess()> to get it. We turn off
8573single stepping and tracing during the call to C<Carp::longmess> to avoid
8574debugging it - we just want to use it.
8575
8576If C<dieLevel> is zero, we let the program being debugged handle the
8577exceptions. If it's 1, you get backtraces for any exception. If it's 2,
8578the debugger takes over all exception handling, printing a backtrace and
8579displaying the exception via its C<dbwarn()> routine.
8580
8581=cut
8582
8583sub dbdie {
8584    local $frame         = 0;
8585    local $doret         = -2;
8586    local $SIG{__DIE__}  = '';
8587    local $SIG{__WARN__} = '';
8588    if ( $dieLevel > 2 ) {
8589        local $SIG{__WARN__} = \&dbwarn;
8590        _db_warn(@_);    # Yell no matter what
8591        return;
8592    }
8593    if ( $dieLevel < 2 ) {
8594        die @_ if $^S;    # in eval propagate
8595    }
8596
8597    # The code used to check $^S to see if compilation of the current thing
8598    # hadn't finished. We don't do it anymore, figuring eval is pretty stable.
8599    eval { require Carp };
8600
8601    die( @_,
8602        "\nCannot print stack trace, load with -MCarp option to see stack" )
8603      unless defined &Carp::longmess;
8604
8605    # We do not want to debug this chunk (automatic disabling works
8606    # inside DB::DB, but not in Carp). Save $single and $trace, turn them off,
8607    # get the stack trace from Carp::longmess (if possible), restore $signal
8608    # and $trace, and then die with the stack trace.
8609    my ( $mysingle, $mytrace ) = ( $single, $trace );
8610    $single = 0;
8611    $trace  = 0;
8612    my $mess = "@_";
8613    {
8614
8615        package Carp;    # Do not include us in the list
8616        eval { $mess = Carp::longmess(@_); };
8617    }
8618    ( $single, $trace ) = ( $mysingle, $mytrace );
8619    die $mess;
8620} ## end sub dbdie
8621
8622=head2 C<warnlevel()>
8623
8624Set the C<$DB::warnLevel> variable that stores the value of the
8625C<warnLevel> option. Calling C<warnLevel()> with a positive value
8626results in the debugger taking over all warning handlers. Setting
8627C<warnLevel> to zero leaves any warning handlers set up by the program
8628being debugged in place.
8629
8630=cut
8631
8632sub warnLevel {
8633    if (@_) {
8634        my $prevwarn = $SIG{__WARN__} unless $warnLevel;
8635        $warnLevel = shift;
8636        if ($warnLevel) {
8637            $SIG{__WARN__} = \&DB::dbwarn;
8638        }
8639        elsif ($prevwarn) {
8640            $SIG{__WARN__} = $prevwarn;
8641        } else {
8642            undef $SIG{__WARN__};
8643        }
8644    } ## end if (@_)
8645    $warnLevel;
8646} ## end sub warnLevel
8647
8648=head2 C<dielevel>
8649
8650Similar to C<warnLevel>. Non-zero values for C<dieLevel> result in the
8651C<DB::dbdie()> function overriding any other C<die()> handler. Setting it to
8652zero lets you use your own C<die()> handler.
8653
8654=cut
8655
8656sub dieLevel {
8657    local $\ = '';
8658    if (@_) {
8659        my $prevdie = $SIG{__DIE__} unless $dieLevel;
8660        $dieLevel = shift;
8661        if ($dieLevel) {
8662
8663            # Always set it to dbdie() for non-zero values.
8664            $SIG{__DIE__} = \&DB::dbdie;    # if $dieLevel < 2;
8665
8666            # No longer exists, so don't try  to use it.
8667            #$SIG{__DIE__} = \&DB::diehard if $dieLevel >= 2;
8668
8669            # If we've finished initialization, mention that stack dumps
8670            # are enabled, If dieLevel is 1, we won't stack dump if we die
8671            # in an eval().
8672            print $OUT "Stack dump during die enabled",
8673              ( $dieLevel == 1 ? " outside of evals" : "" ), ".\n"
8674              if $I_m_init;
8675
8676            # XXX This is probably obsolete, given that diehard() is gone.
8677            print $OUT "Dump printed too.\n" if $dieLevel > 2;
8678        } ## end if ($dieLevel)
8679
8680        # Put the old one back if there was one.
8681        elsif ($prevdie) {
8682            $SIG{__DIE__} = $prevdie;
8683            print $OUT "Default die handler restored.\n";
8684        } else {
8685            undef $SIG{__DIE__};
8686            print $OUT "Die handler removed.\n";
8687        }
8688    } ## end if (@_)
8689    $dieLevel;
8690} ## end sub dieLevel
8691
8692=head2 C<signalLevel>
8693
8694Number three in a series: set C<signalLevel> to zero to keep your own
8695signal handler for C<SIGSEGV> and/or C<SIGBUS>. Otherwise, the debugger
8696takes over and handles them with C<DB::diesignal()>.
8697
8698=cut
8699
8700sub signalLevel {
8701    if (@_) {
8702        my $prevsegv = $SIG{SEGV} unless $signalLevel;
8703        my $prevbus  = $SIG{BUS}  unless $signalLevel;
8704        $signalLevel = shift;
8705        if ($signalLevel) {
8706            $SIG{SEGV} = \&DB::diesignal;
8707            $SIG{BUS}  = \&DB::diesignal;
8708        }
8709        else {
8710            $SIG{SEGV} = $prevsegv;
8711            $SIG{BUS}  = $prevbus;
8712        }
8713    } ## end if (@_)
8714    $signalLevel;
8715} ## end sub signalLevel
8716
8717=head1 SUBROUTINE DECODING SUPPORT
8718
8719These subroutines are used during the C<x> and C<X> commands to try to
8720produce as much information as possible about a code reference. They use
8721L<Devel::Peek> to try to find the glob in which this code reference lives
8722(if it does) - this allows us to actually code references which correspond
8723to named subroutines (including those aliased via glob assignment).
8724
8725=head2 C<CvGV_name()>
8726
8727Wrapper for C<CvGV_name_or_bust>; tries to get the name of a reference
8728via that routine. If this fails, return the reference again (when the
8729reference is stringified, it'll come out as C<SOMETHING(0x...)>).
8730
8731=cut
8732
8733sub CvGV_name {
8734    my $in   = shift;
8735    my $name = CvGV_name_or_bust($in);
8736    defined $name ? $name : $in;
8737}
8738
8739=head2 C<CvGV_name_or_bust> I<coderef>
8740
8741Calls L<Devel::Peek> to try to find the glob the ref lives in; returns
8742C<undef> if L<Devel::Peek> can't be loaded, or if C<Devel::Peek::CvGV> can't
8743find a glob for this ref.
8744
8745Returns C<< I<package>::I<glob name> >> if the code ref is found in a glob.
8746
8747=cut
8748
8749use vars qw($skipCvGV);
8750
8751sub CvGV_name_or_bust {
8752    my $in = shift;
8753    return if $skipCvGV;    # Backdoor to avoid problems if XS broken...
8754    return unless ref $in;
8755    $in = \&$in;            # Hard reference...
8756    eval { require Devel::Peek; 1 } or return;
8757    my $gv = Devel::Peek::CvGV($in) or return;
8758    *$gv{PACKAGE} . '::' . *$gv{NAME};
8759} ## end sub CvGV_name_or_bust
8760
8761=head2 C<find_sub>
8762
8763A utility routine used in various places; finds the file where a subroutine
8764was defined, and returns that filename and a line-number range.
8765
8766Tries to use C<@sub> first; if it can't find it there, it tries building a
8767reference to the subroutine and uses C<CvGV_name_or_bust> to locate it,
8768loading it into C<@sub> as a side effect (XXX I think). If it can't find it
8769this way, it brute-force searches C<%sub>, checking for identical references.
8770
8771=cut
8772
8773sub _find_sub_helper {
8774    my $subr = shift;
8775
8776    return unless defined &$subr;
8777    my $name = CvGV_name_or_bust($subr);
8778    my $data;
8779    $data = $sub{$name} if defined $name;
8780    return $data if defined $data;
8781
8782    # Old stupid way...
8783    $subr = \&$subr;    # Hard reference
8784    my $s;
8785    for ( keys %sub ) {
8786        $s = $_, last if $subr eq \&$_;
8787    }
8788    if ($s)
8789    {
8790        return $sub{$s};
8791    }
8792    else
8793    {
8794        return;
8795    }
8796
8797}
8798
8799sub find_sub {
8800    my $subr = shift;
8801    return ( $sub{$subr} || _find_sub_helper($subr) );
8802} ## end sub find_sub
8803
8804=head2 C<methods>
8805
8806A subroutine that uses the utility function C<methods_via> to find all the
8807methods in the class corresponding to the current reference and in
8808C<UNIVERSAL>.
8809
8810=cut
8811
8812use vars qw(%seen);
8813
8814sub methods {
8815
8816    # Figure out the class - either this is the class or it's a reference
8817    # to something blessed into that class.
8818    my $class = shift;
8819    $class = ref $class if ref $class;
8820
8821    local %seen;
8822
8823    # Show the methods that this class has.
8824    methods_via( $class, '', 1 );
8825
8826    # Show the methods that UNIVERSAL has.
8827    methods_via( 'UNIVERSAL', 'UNIVERSAL', 0 );
8828} ## end sub methods
8829
8830=head2 C<methods_via($class, $prefix, $crawl_upward)>
8831
8832C<methods_via> does the work of crawling up the C<@ISA> tree and reporting
8833all the parent class methods. C<$class> is the name of the next class to
8834try; C<$prefix> is the message prefix, which gets built up as we go up the
8835C<@ISA> tree to show parentage; C<$crawl_upward> is 1 if we should try to go
8836higher in the C<@ISA> tree, 0 if we should stop.
8837
8838=cut
8839
8840sub methods_via {
8841
8842    # If we've processed this class already, just quit.
8843    my $class = shift;
8844    return if $seen{$class}++;
8845
8846    # This is a package that is contributing the methods we're about to print.
8847    my $prefix  = shift;
8848    my $prepend = $prefix ? "via $prefix: " : '';
8849    my @to_print;
8850
8851    # Extract from all the symbols in this class.
8852    my $class_ref = do { no strict "refs"; \%{$class . '::'} };
8853    while (my ($name, $glob) = each %$class_ref) {
8854        # references directly in the symbol table are Proxy Constant
8855        # Subroutines, and are by their very nature defined
8856        # Otherwise, check if the thing is a typeglob, and if it is, it decays
8857        # to a subroutine reference, which can be tested by defined.
8858        # $glob might also be the value -1  (from sub foo;)
8859        # or (say) '$$' (from sub foo ($$);)
8860        # \$glob will be SCALAR in both cases.
8861        if ((ref $glob || ($glob && ref \$glob eq 'GLOB' && defined &$glob))
8862            && !$seen{$name}++) {
8863            push @to_print, "$prepend$name\n";
8864        }
8865    }
8866
8867    {
8868        local $\ = '';
8869        local $, = '';
8870        print $DB::OUT $_ foreach sort @to_print;
8871    }
8872
8873    # If the $crawl_upward argument is false, just quit here.
8874    return unless shift;
8875
8876    # $crawl_upward true: keep going up the tree.
8877    # Find all the classes this one is a subclass of.
8878    my $class_ISA_ref = do { no strict "refs"; \@{"${class}::ISA"} };
8879    for my $name ( @$class_ISA_ref ) {
8880
8881        # Set up the new prefix.
8882        $prepend = $prefix ? $prefix . " -> $name" : $name;
8883
8884        # Crawl up the tree and keep trying to crawl up.
8885        methods_via( $name, $prepend, 1 );
8886    }
8887} ## end sub methods_via
8888
8889=head2 C<setman> - figure out which command to use to show documentation
8890
8891Just checks the contents of C<$^O> and sets the C<$doccmd> global accordingly.
8892
8893=cut
8894
8895sub setman {
8896    $doccmd = $^O !~ /^(?:MSWin32|VMS|os2|dos|amigaos|riscos|NetWare)\z/s
8897      ? "man"         # O Happy Day!
8898      : "perldoc";    # Alas, poor unfortunates
8899} ## end sub setman
8900
8901=head2 C<runman> - run the appropriate command to show documentation
8902
8903Accepts a man page name; runs the appropriate command to display it (set up
8904during debugger initialization). Uses C<_db_system()> to avoid mucking up the
8905program's STDIN and STDOUT.
8906
8907=cut
8908
8909sub runman {
8910    my $page = shift;
8911    unless ($page) {
8912        _db_system("$doccmd $doccmd");
8913        return;
8914    }
8915
8916    # this way user can override, like with $doccmd="man -Mwhatever"
8917    # or even just "man " to disable the path check.
8918    if ( $doccmd ne 'man' ) {
8919        _db_system("$doccmd $page");
8920        return;
8921    }
8922
8923    $page = 'perl' if lc($page) eq 'help';
8924
8925    require Config;
8926    my $man1dir = $Config::Config{man1direxp};
8927    my $man3dir = $Config::Config{man3direxp};
8928    for ( $man1dir, $man3dir ) { s#/[^/]*\z## if /\S/ }
8929    my $manpath = '';
8930    $manpath .= "$man1dir:" if $man1dir =~ /\S/;
8931    $manpath .= "$man3dir:" if $man3dir =~ /\S/ && $man1dir ne $man3dir;
8932    chop $manpath if $manpath;
8933
8934    # harmless if missing, I figure
8935    local $ENV{MANPATH} = $manpath if $manpath;
8936    my $nopathopt = $^O =~ /dunno what goes here/;
8937    if (
8938        CORE::system(
8939            $doccmd,
8940
8941            # I just *know* there are men without -M
8942            ( ( $manpath && !$nopathopt ) ? ( "-M", $manpath ) : () ),
8943            split ' ', $page
8944        )
8945      )
8946    {
8947        unless ( $page =~ /^perl\w/ ) {
8948            # Previously the debugger contained a list which it slurped in,
8949            # listing the known "perl" manpages. However, it was out of date,
8950            # with errors both of omission and inclusion. This approach is
8951            # considerably less complex. The failure mode on a butchered
8952            # install is simply that the user has to run man or perldoc
8953            # "manually" with the full manpage name.
8954
8955            # There is a list of $^O values in installperl to determine whether
8956            # the directory is 'pods' or 'pod'. However, we can avoid tight
8957            # coupling to that by simply checking the "non-standard" 'pods'
8958            # first.
8959            my $pods = "$Config::Config{privlibexp}/pods";
8960            $pods = "$Config::Config{privlibexp}/pod"
8961                unless -d $pods;
8962            if (-f "$pods/perl$page.pod") {
8963                CORE::system( $doccmd,
8964                    ( ( $manpath && !$nopathopt ) ? ( "-M", $manpath ) : () ),
8965                    "perl$page" );
8966            }
8967        }
8968    } ## end if (CORE::system($doccmd...
8969} ## end sub runman
8970
8971#use Carp;                          # This did break, left for debugging
8972
8973=head1 DEBUGGER INITIALIZATION - THE SECOND BEGIN BLOCK
8974
8975Because of the way the debugger interface to the Perl core is designed, any
8976debugger package globals that C<DB::sub()> requires have to be defined before
8977any subroutines can be called. These are defined in the second C<BEGIN> block.
8978
8979This block sets things up so that (basically) the world is sane
8980before the debugger starts executing. We set up various variables that the
8981debugger has to have set up before the Perl core starts running:
8982
8983=over 4
8984
8985=item *
8986
8987The debugger's own filehandles (copies of STD and STDOUT for now).
8988
8989=item *
8990
8991Characters for shell escapes, the recall command, and the history command.
8992
8993=item *
8994
8995The maximum recursion depth.
8996
8997=item *
8998
8999The size of a C<w> command's window.
9000
9001=item *
9002
9003The before-this-line context to be printed in a C<v> (view a window around this line) command.
9004
9005=item *
9006
9007The fact that we're not in a sub at all right now.
9008
9009=item *
9010
9011The default SIGINT handler for the debugger.
9012
9013=item *
9014
9015The appropriate value of the flag in C<$^D> that says the debugger is running
9016
9017=item *
9018
9019The current debugger recursion level
9020
9021=item *
9022
9023The list of postponed items and the C<$single> stack (XXX define this)
9024
9025=item *
9026
9027That we want no return values and no subroutine entry/exit trace.
9028
9029=back
9030
9031=cut
9032
9033# The following BEGIN is very handy if debugger goes havoc, debugging debugger?
9034
9035use vars qw($db_stop);
9036
9037BEGIN {    # This does not compile, alas. (XXX eh?)
9038    $IN  = \*STDIN;     # For bugs before DB::OUT has been opened
9039    $OUT = \*STDERR;    # For errors before DB::OUT has been opened
9040
9041    # Define characters used by command parsing.
9042    $sh       = '!';      # Shell escape (does not work)
9043    $rc       = ',';      # Recall command (does not work)
9044    @hist     = ('?');    # Show history (does not work)
9045    @truehist = ();       # Can be saved for replay (per session)
9046
9047    # This defines the point at which you get the 'deep recursion'
9048    # warning. It MUST be defined or the debugger will not load.
9049    $deep = 1000;
9050
9051    # Number of lines around the current one that are shown in the
9052    # 'w' command.
9053    $window = 10;
9054
9055    # How much before-the-current-line context the 'v' command should
9056    # use in calculating the start of the window it will display.
9057    $preview = 3;
9058
9059    # We're not in any sub yet, but we need this to be a defined value.
9060    $sub = '';
9061
9062    # Set up the debugger's interrupt handler. It simply sets a flag
9063    # ($signal) that DB::DB() will check before each command is executed.
9064    $SIG{INT} = \&DB::catch;
9065
9066    # The following lines supposedly, if uncommented, allow the debugger to
9067    # debug itself. Perhaps we can try that someday.
9068    # This may be enabled to debug debugger:
9069    #$warnLevel = 1 unless defined $warnLevel;
9070    #$dieLevel = 1 unless defined $dieLevel;
9071    #$signalLevel = 1 unless defined $signalLevel;
9072
9073    # This is the flag that says "a debugger is running, please call
9074    # DB::DB and DB::sub". We will turn it on forcibly before we try to
9075    # execute anything in the user's context, because we always want to
9076    # get control back.
9077    $db_stop = 0;          # Compiler warning ...
9078    $db_stop = 1 << 30;    # ... because this is only used in an eval() later.
9079
9080    # This variable records how many levels we're nested in debugging. Used
9081    # Used in the debugger prompt, and in determining whether it's all over or
9082    # not.
9083    $level = 0;            # Level of recursive debugging
9084
9085    # "Triggers bug (?) in perl if we postpone this until runtime."
9086    # XXX No details on this yet, or whether we should fix the bug instead
9087    # of work around it. Stay tuned.
9088    @stack = (0);
9089
9090    # Used to track the current stack depth using the auto-stacked-variable
9091    # trick.
9092    $stack_depth = 0;      # Localized repeatedly; simple way to track $#stack
9093
9094    # Don't print return values on exiting a subroutine.
9095    $doret = -2;
9096
9097    # No extry/exit tracing.
9098    $frame = 0;
9099
9100} ## end BEGIN
9101
9102BEGIN { $^W = $ini_warn; }    # Switch warnings back
9103
9104=head1 READLINE SUPPORT - COMPLETION FUNCTION
9105
9106=head2 db_complete
9107
9108C<readline> support - adds command completion to basic C<readline>.
9109
9110Returns a list of possible completions to C<readline> when invoked. C<readline>
9111will print the longest common substring following the text already entered.
9112
9113If there is only a single possible completion, C<readline> will use it in full.
9114
9115This code uses C<map> and C<grep> heavily to create lists of possible
9116completion. Think LISP in this section.
9117
9118=cut
9119
9120sub db_complete {
9121
9122    # Specific code for b c l V m f O, &blah, $blah, @blah, %blah
9123    # $text is the text to be completed.
9124    # $line is the incoming line typed by the user.
9125    # $start is the start of the text to be completed in the incoming line.
9126    my ( $text, $line, $start ) = @_;
9127
9128    # Save the initial text.
9129    # The search pattern is current package, ::, extract the next qualifier
9130    # Prefix and pack are set to undef.
9131    my ( $itext, $search, $prefix, $pack ) =
9132      ( $text, "^\Q${package}::\E([^:]+)\$" );
9133
9134=head3 C<b postpone|compile>
9135
9136=over 4
9137
9138=item *
9139
9140Find all the subroutines that might match in this package
9141
9142=item *
9143
9144Add C<postpone>, C<load>, and C<compile> as possibles (we may be completing the keyword itself)
9145
9146=item *
9147
9148Include all the rest of the subs that are known
9149
9150=item *
9151
9152C<grep> out the ones that match the text we have so far
9153
9154=item *
9155
9156Return this as the list of possible completions
9157
9158=back
9159
9160=cut
9161
9162    return sort grep /^\Q$text/, ( keys %sub ),
9163      qw(postpone load compile),    # subroutines
9164      ( map { /$search/ ? ($1) : () } keys %sub )
9165      if ( substr $line, 0, $start ) =~ /^\|*[blc]\s+((postpone|compile)\s+)?$/;
9166
9167=head3 C<b load>
9168
9169Get all the possible files from C<@INC> as it currently stands and
9170select the ones that match the text so far.
9171
9172=cut
9173
9174    return sort grep /^\Q$text/, values %INC    # files
9175      if ( substr $line, 0, $start ) =~ /^\|*b\s+load\s+$/;
9176
9177=head3  C<V> (list variable) and C<m> (list modules)
9178
9179There are two entry points for these commands:
9180
9181=head4 Unqualified package names
9182
9183Get the top-level packages and grab everything that matches the text
9184so far. For each match, recursively complete the partial packages to
9185get all possible matching packages. Return this sorted list.
9186
9187=cut
9188
9189    return sort map { ( $_, db_complete( $_ . "::", "V ", 2 ) ) }
9190      grep /^\Q$text/, map { /^(.*)::$/ ? ($1) : () } keys %::    # top-packages
9191      if ( substr $line, 0, $start ) =~ /^\|*[Vm]\s+$/ and $text =~ /^\w*$/;
9192
9193=head4 Qualified package names
9194
9195Take a partially-qualified package and find all subpackages for it
9196by getting all the subpackages for the package so far, matching all
9197the subpackages against the text, and discarding all of them which
9198start with 'main::'. Return this list.
9199
9200=cut
9201
9202    return sort map { ( $_, db_complete( $_ . "::", "V ", 2 ) ) }
9203      grep !/^main::/, grep /^\Q$text/,
9204      map { /^(.*)::$/ ? ( $prefix . "::$1" ) : () }
9205      do { no strict 'refs'; keys %{ $prefix . '::' } }
9206      if ( substr $line, 0, $start ) =~ /^\|*[Vm]\s+$/
9207      and $text =~ /^(.*[^:])::?(\w*)$/
9208      and $prefix = $1;
9209
9210=head3 C<f> - switch files
9211
9212Here, we want to get a fully-qualified filename for the C<f> command.
9213Possibilities are:
9214
9215=over 4
9216
9217=item 1. The original source file itself
9218
9219=item 2. A file from C<@INC>
9220
9221=item 3. An C<eval> (the debugger gets a C<(eval N)> fake file for each C<eval>).
9222
9223=back
9224
9225=cut
9226
9227    if ( $line =~ /^\|*f\s+(.*)/ ) {    # Loaded files
9228           # We might possibly want to switch to an eval (which has a "filename"
9229           # like '(eval 9)'), so we may need to clean up the completion text
9230           # before proceeding.
9231        $prefix = length($1) - length($text);
9232        $text   = $1;
9233
9234=pod
9235
9236Under the debugger, source files are represented as C<_E<lt>/fullpath/to/file>
9237(C<eval>s are C<_E<lt>(eval NNN)>) keys in C<%main::>. We pull all of these
9238out of C<%main::>, add the initial source file, and extract the ones that
9239match the completion text so far.
9240
9241=cut
9242
9243        return sort
9244          map { substr $_, 2 + $prefix } grep /^_<\Q$text/, ( keys %main:: ),
9245          $0;
9246    } ## end if ($line =~ /^\|*f\s+(.*)/)
9247
9248=head3 Subroutine name completion
9249
9250We look through all of the defined subs (the keys of C<%sub>) and
9251return both all the possible matches to the subroutine name plus
9252all the matches qualified to the current package.
9253
9254=cut
9255
9256    if ( ( substr $text, 0, 1 ) eq '&' ) {    # subroutines
9257        $text = substr $text, 1;
9258        $prefix = "&";
9259        return sort map "$prefix$_", grep /^\Q$text/, ( keys %sub ),
9260          (
9261            map { /$search/ ? ($1) : () }
9262              keys %sub
9263          );
9264    } ## end if ((substr $text, 0, ...
9265
9266=head3  Scalar, array, and hash completion: partially qualified package
9267
9268Much like the above, except we have to do a little more cleanup:
9269
9270=cut
9271
9272    if ( $text =~ /^[\$@%](.*)::(.*)/ ) {    # symbols in a package
9273
9274=pod
9275
9276=over 4
9277
9278=item *
9279
9280Determine the package that the symbol is in. Put it in C<::> (effectively C<main::>) if no package is specified.
9281
9282=cut
9283
9284        $pack = ( $1 eq 'main' ? '' : $1 ) . '::';
9285
9286=pod
9287
9288=item *
9289
9290Figure out the prefix vs. what needs completing.
9291
9292=cut
9293
9294        $prefix = ( substr $text, 0, 1 ) . $1 . '::';
9295        $text   = $2;
9296
9297=pod
9298
9299=item *
9300
9301Look through all the symbols in the package. C<grep> out all the possible hashes/arrays/scalars, and then C<grep> the possible matches out of those. C<map> the prefix onto all the possibilities.
9302
9303=cut
9304
9305        my @out = do {
9306            no strict 'refs';
9307            map "$prefix$_", grep /^\Q$text/, grep /^_?[a-zA-Z]/,
9308            keys %$pack;
9309        };
9310
9311=pod
9312
9313=item *
9314
9315If there's only one hit, and it's a package qualifier, and it's not equal to the initial text, re-complete it using the symbol we actually found.
9316
9317=cut
9318
9319        if ( @out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext ) {
9320            return db_complete( $out[0], $line, $start );
9321        }
9322
9323        # Return the list of possibles.
9324        return sort @out;
9325
9326    } ## end if ($text =~ /^[\$@%](.*)::(.*)/)
9327
9328=pod
9329
9330=back
9331
9332=head3 Symbol completion: current package or package C<main>.
9333
9334=cut
9335
9336    if ( $text =~ /^[\$@%]/ ) {    # symbols (in $package + packages in main)
9337=pod
9338
9339=over 4
9340
9341=item *
9342
9343If it's C<main>, delete main to just get C<::> leading.
9344
9345=cut
9346
9347        $pack = ( $package eq 'main' ? '' : $package ) . '::';
9348
9349=pod
9350
9351=item *
9352
9353We set the prefix to the item's sigil, and trim off the sigil to get the text to be completed.
9354
9355=cut
9356
9357        $prefix = substr $text, 0, 1;
9358        $text   = substr $text, 1;
9359
9360        my @out;
9361
9362=pod
9363
9364=item *
9365
9366We look for the lexical scope above DB::DB and auto-complete lexical variables
9367if PadWalker could be loaded.
9368
9369=cut
9370
9371        if (not $text =~ /::/ and eval {
9372            local @INC = @INC;
9373            pop @INC if $INC[-1] eq '.';
9374            require PadWalker } ) {
9375            my $level = 1;
9376            while (1) {
9377                my @info = caller($level);
9378                $level++;
9379                $level = -1, last
9380                  if not @info;
9381                last if $info[3] eq 'DB::DB';
9382            }
9383            if ($level > 0) {
9384                my $lexicals = PadWalker::peek_my($level);
9385                push @out, grep /^\Q$prefix$text/, keys %$lexicals;
9386            }
9387        }
9388
9389=pod
9390
9391=item *
9392
9393If the package is C<::> (C<main>), create an empty list; if it's something else, create a list of all the packages known.  Append whichever list to a list of all the possible symbols in the current package. C<grep> out the matches to the text entered so far, then C<map> the prefix back onto the symbols.
9394
9395=cut
9396
9397        push @out, map "$prefix$_", grep /^\Q$text/,
9398          ( grep /^_?[a-zA-Z]/, do { no strict 'refs'; keys %$pack } ),
9399          ( $pack eq '::' ? () : ( grep /::$/, keys %:: ) );
9400
9401=item *
9402
9403If there's only one hit, it's a package qualifier, and it's not equal to the initial text, recomplete using this symbol.
9404
9405=back
9406
9407=cut
9408
9409        if ( @out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext ) {
9410            return db_complete( $out[0], $line, $start );
9411        }
9412
9413        # Return the list of possibles.
9414        return sort @out;
9415    } ## end if ($text =~ /^[\$@%]/)
9416
9417=head3 Options
9418
9419We use C<option_val()> to look up the current value of the option. If there's
9420only a single value, we complete the command in such a way that it is a
9421complete command for setting the option in question. If there are multiple
9422possible values, we generate a command consisting of the option plus a trailing
9423question mark, which, if executed, will list the current value of the option.
9424
9425=cut
9426
9427    if ( ( substr $line, 0, $start ) =~ /^\|*[oO]\b.*\s$/ )
9428    {    # Options after space
9429           # We look for the text to be matched in the list of possible options,
9430           # and fetch the current value.
9431        my @out = grep /^\Q$text/, @options;
9432        my $val = option_val( $out[0], undef );
9433
9434        # Set up a 'query option's value' command.
9435        my $out = '? ';
9436        if ( not defined $val or $val =~ /[\n\r]/ ) {
9437
9438            # There's really nothing else we can do.
9439        }
9440
9441        # We have a value. Create a proper option-setting command.
9442        elsif ( $val =~ /\s/ ) {
9443
9444            # XXX This may be an extraneous variable.
9445            my $found;
9446
9447            # We'll want to quote the string (because of the embedded
9448            # whtespace), but we want to make sure we don't end up with
9449            # mismatched quote characters. We try several possibilities.
9450            foreach my $l ( split //, qq/\"\'\#\|/ ) {
9451
9452                # If we didn't find this quote character in the value,
9453                # quote it using this quote character.
9454                $out = "$l$val$l ", last if ( index $val, $l ) == -1;
9455            }
9456        } ## end elsif ($val =~ /\s/)
9457
9458        # Don't need any quotes.
9459        else {
9460            $out = "=$val ";
9461        }
9462
9463        # If there were multiple possible values, return '? ', which
9464        # makes the command into a query command. If there was just one,
9465        # have readline append that.
9466        $rl_attribs->{completer_terminator_character} =
9467          ( @out == 1 ? $out : '? ' );
9468
9469        # Return list of possibilities.
9470        return sort @out;
9471    } ## end if ((substr $line, 0, ...
9472
9473=head3 Filename completion
9474
9475For entering filenames. We simply call C<readline>'s C<filename_list()>
9476method with the completion text to get the possible completions.
9477
9478=cut
9479
9480    return $term->filename_list($text);    # filenames
9481
9482} ## end sub db_complete
9483
9484=head1 MISCELLANEOUS SUPPORT FUNCTIONS
9485
9486Functions that possibly ought to be somewhere else.
9487
9488=head2 end_report
9489
9490Say we're done.
9491
9492=cut
9493
9494sub end_report {
9495    local $\ = '';
9496    print $OUT "Use 'q' to quit or 'R' to restart.  'h q' for details.\n";
9497}
9498
9499=head2 clean_ENV
9500
9501If we have $ini_pids, save it in the environment; else remove it from the
9502environment. Used by the C<R> (restart) command.
9503
9504=cut
9505
9506sub clean_ENV {
9507    if ( defined($ini_pids) ) {
9508        $ENV{PERLDB_PIDS} = $ini_pids;
9509    }
9510    else {
9511        delete( $ENV{PERLDB_PIDS} );
9512    }
9513} ## end sub clean_ENV
9514
9515# PERLDBf_... flag names from perl.h
9516our ( %DollarCaretP_flags, %DollarCaretP_flags_r );
9517
9518BEGIN {
9519    %DollarCaretP_flags = (
9520        PERLDBf_SUB       => 0x01,     # Debug sub enter/exit
9521        PERLDBf_LINE      => 0x02,     # Keep line #
9522        PERLDBf_NOOPT     => 0x04,     # Switch off optimizations
9523        PERLDBf_INTER     => 0x08,     # Preserve more data
9524        PERLDBf_SUBLINE   => 0x10,     # Keep subr source lines
9525        PERLDBf_SINGLE    => 0x20,     # Start with single-step on
9526        PERLDBf_NONAME    => 0x40,     # For _SUB: no name of the subr
9527        PERLDBf_GOTO      => 0x80,     # Report goto: call DB::goto
9528        PERLDBf_NAMEEVAL  => 0x100,    # Informative names for evals
9529        PERLDBf_NAMEANON  => 0x200,    # Informative names for anon subs
9530        PERLDBf_SAVESRC   => 0x400,    # Save source lines into @{"_<$filename"}
9531        PERLDB_ALL        => 0x33f,    # No _NONAME, _GOTO
9532    );
9533    # PERLDBf_LINE also enables the actions of PERLDBf_SAVESRC, so the debugger
9534    # doesn't need to set it. It's provided for the benefit of profilers and
9535    # other code analysers.
9536
9537    %DollarCaretP_flags_r = reverse %DollarCaretP_flags;
9538}
9539
9540sub parse_DollarCaretP_flags {
9541    my $flags = shift;
9542    $flags =~ s/^\s+//;
9543    $flags =~ s/\s+$//;
9544    my $acu = 0;
9545    foreach my $f ( split /\s*\|\s*/, $flags ) {
9546        my $value;
9547        if ( $f =~ /^0x([[:xdigit:]]+)$/ ) {
9548            $value = hex $1;
9549        }
9550        elsif ( $f =~ /^(\d+)$/ ) {
9551            $value = int $1;
9552        }
9553        elsif ( $f =~ /^DEFAULT$/i ) {
9554            $value = $DollarCaretP_flags{PERLDB_ALL};
9555        }
9556        else {
9557            $f =~ /^(?:PERLDBf_)?(.*)$/i;
9558            $value = $DollarCaretP_flags{ 'PERLDBf_' . uc($1) };
9559            unless ( defined $value ) {
9560                print $OUT (
9561                    "Unrecognized \$^P flag '$f'!\n",
9562                    "Acceptable flags are: "
9563                      . join( ', ', sort keys %DollarCaretP_flags ),
9564                    ", and hexadecimal and decimal numbers.\n"
9565                );
9566                return undef;
9567            }
9568        }
9569        $acu |= $value;
9570    }
9571    $acu;
9572}
9573
9574sub expand_DollarCaretP_flags {
9575    my $DollarCaretP = shift;
9576    my @bits         = (
9577        map {
9578            my $n = ( 1 << $_ );
9579            ( $DollarCaretP & $n )
9580              ? ( $DollarCaretP_flags_r{$n}
9581                  || sprintf( '0x%x', $n ) )
9582              : ()
9583          } 0 .. 31
9584    );
9585    return @bits ? join( '|', @bits ) : 0;
9586}
9587
9588=over 4
9589
9590=item rerun
9591
9592Rerun the current session to:
9593
9594    rerun        current position
9595
9596    rerun 4      command number 4
9597
9598    rerun -4     current command minus 4 (go back 4 steps)
9599
9600Whether this always makes sense, in the current context is unknowable, and is
9601in part left as a useful exercise for the reader.  This sub returns the
9602appropriate arguments to rerun the current session.
9603
9604=cut
9605
9606sub rerun {
9607    my $i = shift;
9608    my @args;
9609    pop(@truehist);                      # strim
9610    unless (defined $truehist[$i]) {
9611        print "Unable to return to non-existent command: $i\n";
9612    } else {
9613        $#truehist = ($i < 0 ? $#truehist + $i : $i > 0 ? $i : $#truehist);
9614        my @temp = @truehist;            # store
9615        push(@DB::typeahead, @truehist); # saved
9616        @truehist = @hist = ();          # flush
9617        @args = restart();              # setup
9618        get_list("PERLDB_HIST");        # clean
9619        set_list("PERLDB_HIST", @temp); # reset
9620    }
9621    return @args;
9622}
9623
9624=item restart
9625
9626Restarting the debugger is a complex operation that occurs in several phases.
9627First, we try to reconstruct the command line that was used to invoke Perl
9628and the debugger.
9629
9630=cut
9631
9632sub restart {
9633    # I may not be able to resurrect you, but here goes ...
9634    print $OUT
9635"Warning: some settings and command-line options may be lost!\n";
9636    my ( @script, @flags, $cl );
9637
9638    # If warn was on before, turn it on again.
9639    push @flags, '-w' if $ini_warn;
9640
9641    # Rebuild the -I flags that were on the initial
9642    # command line.
9643    for (@ini_INC) {
9644        push @flags, '-I', $_;
9645    }
9646
9647    # Turn on taint if it was on before.
9648    push @flags, '-T' if ${^TAINT};
9649
9650    # Arrange for setting the old INC:
9651    # Save the current @init_INC in the environment.
9652    set_list( "PERLDB_INC", @ini_INC );
9653
9654    # If this was a perl one-liner, go to the "file"
9655    # corresponding to the one-liner read all the lines
9656    # out of it (except for the first one, which is going
9657    # to be added back on again when 'perl -d' runs: that's
9658    # the 'require perl5db.pl;' line), and add them back on
9659    # to the command line to be executed.
9660    if ( $0 eq '-e' ) {
9661        my $lines = *{$main::{'_<-e'}}{ARRAY};
9662        for ( 1 .. $#$lines ) {  # The first line is PERL5DB
9663            chomp( $cl = $lines->[$_] );
9664            push @script, '-e', $cl;
9665        }
9666    } ## end if ($0 eq '-e')
9667
9668    # Otherwise we just reuse the original name we had
9669    # before.
9670    else {
9671        @script = $0;
9672    }
9673
9674=pod
9675
9676After the command line  has been reconstructed, the next step is to save
9677the debugger's status in environment variables. The C<DB::set_list> routine
9678is used to save aggregate variables (both hashes and arrays); scalars are
9679just popped into environment variables directly.
9680
9681=cut
9682
9683    # If the terminal supported history, grab it and
9684    # save that in the environment.
9685    set_list( "PERLDB_HIST",
9686          $term->Features->{getHistory}
9687        ? $term->GetHistory
9688        : @hist );
9689
9690    # Find all the files that were visited during this
9691    # session (i.e., the debugger had magic hashes
9692    # corresponding to them) and stick them in the environment.
9693    my @had_breakpoints = keys %had_breakpoints;
9694    set_list( "PERLDB_VISITED", @had_breakpoints );
9695
9696    # Save the debugger options we chose.
9697    set_list( "PERLDB_OPT", %option );
9698    # set_list( "PERLDB_OPT", options2remember() );
9699
9700    # Save the break-on-loads.
9701    set_list( "PERLDB_ON_LOAD", %break_on_load );
9702
9703=pod
9704
9705The most complex part of this is the saving of all of the breakpoints. They
9706can live in an awful lot of places, and we have to go through all of them,
9707find the breakpoints, and then save them in the appropriate environment
9708variable via C<DB::set_list>.
9709
9710=cut
9711
9712    # Go through all the breakpoints and make sure they're
9713    # still valid.
9714    my @hard;
9715    for ( 0 .. $#had_breakpoints ) {
9716
9717        # We were in this file.
9718        my $file = $had_breakpoints[$_];
9719
9720        # Grab that file's magic line hash.
9721        *dbline = $main::{ '_<' . $file };
9722
9723        # Skip out if it doesn't exist, or if the breakpoint
9724        # is in a postponed file (we'll do postponed ones
9725        # later).
9726        next unless %dbline or $postponed_file{$file};
9727
9728        # In an eval. This is a little harder, so we'll
9729        # do more processing on that below.
9730        ( push @hard, $file ), next
9731          if $file =~ /^\(\w*eval/;
9732
9733        # XXX I have no idea what this is doing. Yet.
9734        my @add;
9735        @add = %{ $postponed_file{$file} }
9736          if $postponed_file{$file};
9737
9738        # Save the list of all the breakpoints for this file.
9739        set_list( "PERLDB_FILE_$_", %dbline, @add );
9740
9741        # Serialize the extra data %breakpoints_data hash.
9742        # That's a bug fix.
9743        set_list( "PERLDB_FILE_ENABLED_$_",
9744            map { _is_breakpoint_enabled($file, $_) ? 1 : 0 }
9745            sort { $a <=> $b } keys(%dbline)
9746        )
9747    } ## end for (0 .. $#had_breakpoints)
9748
9749    # The breakpoint was inside an eval. This is a little
9750    # more difficult. XXX and I don't understand it.
9751    foreach my $hard_file (@hard) {
9752        # Get over to the eval in question.
9753        *dbline = $main::{ '_<' . $hard_file };
9754        my $quoted = quotemeta $hard_file;
9755        my %subs;
9756        for my $sub ( keys %sub ) {
9757            if (my ($n1, $n2) = $sub{$sub} =~ /\A$quoted:(\d+)-(\d+)\z/) {
9758                $subs{$sub} = [ $n1, $n2 ];
9759            }
9760        }
9761        unless (%subs) {
9762            print {$OUT}
9763            "No subroutines in $hard_file, ignoring breakpoints.\n";
9764            next;
9765        }
9766        LINES: foreach my $line ( keys %dbline ) {
9767
9768            # One breakpoint per sub only:
9769            my ( $offset, $found );
9770            SUBS: foreach my $sub ( keys %subs ) {
9771                if (
9772                    $subs{$sub}->[1] >= $line    # Not after the subroutine
9773                    and (
9774                        not defined $offset    # Not caught
9775                            or $offset < 0
9776                    )
9777                )
9778                {                              # or badly caught
9779                    $found  = $sub;
9780                    $offset = $line - $subs{$sub}->[0];
9781                    if ($offset >= 0) {
9782                        $offset = "+$offset";
9783                        last SUBS;
9784                    }
9785                } ## end if ($subs{$sub}->[1] >=...
9786            } ## end for $sub (keys %subs)
9787            if ( defined $offset ) {
9788                $postponed{$found} =
9789                "break $offset if $dbline{$line}";
9790            }
9791            else {
9792                print {$OUT}
9793                ("Breakpoint in ${hard_file}:$line ignored:"
9794                . " after all the subroutines.\n");
9795            }
9796        } ## end for $line (keys %dbline)
9797    } ## end for (@hard)
9798
9799    # Save the other things that don't need to be
9800    # processed.
9801    set_list( "PERLDB_POSTPONE",  %postponed );
9802    set_list( "PERLDB_PRETYPE",   @$pretype );
9803    set_list( "PERLDB_PRE",       @$pre );
9804    set_list( "PERLDB_POST",      @$post );
9805    set_list( "PERLDB_TYPEAHEAD", @typeahead );
9806
9807    # We are officially restarting.
9808    $ENV{PERLDB_RESTART} = 1;
9809
9810    # We are junking all child debuggers.
9811    delete $ENV{PERLDB_PIDS};    # Restore ini state
9812
9813    # Set this back to the initial pid.
9814    $ENV{PERLDB_PIDS} = $ini_pids if defined $ini_pids;
9815
9816=pod
9817
9818After all the debugger status has been saved, we take the command we built up
9819and then return it, so we can C<exec()> it. The debugger will spot the
9820C<PERLDB_RESTART> environment variable and realize it needs to reload its state
9821from the environment.
9822
9823=cut
9824
9825    # And run Perl again. Add the "-d" flag, all the
9826    # flags we built up, the script (whether a one-liner
9827    # or a file), add on the -emacs flag for a slave editor,
9828    # and then the old arguments.
9829
9830    return ($^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS);
9831
9832};  # end restart
9833
9834=back
9835
9836=head1 END PROCESSING - THE C<END> BLOCK
9837
9838Come here at the very end of processing. We want to go into a
9839loop where we allow the user to enter commands and interact with the
9840debugger, but we don't want anything else to execute.
9841
9842First we set the C<$finished> variable, so that some commands that
9843shouldn't be run after the end of program quit working.
9844
9845We then figure out whether we're truly done (as in the user entered a C<q>
9846command, or we finished execution while running nonstop). If we aren't,
9847we set C<$single> to 1 (causing the debugger to get control again).
9848
9849We then call C<DB::fake::at_exit()>, which returns the C<Use 'q' to quit ...>
9850message and returns control to the debugger. Repeat.
9851
9852When the user finally enters a C<q> command, C<$fall_off_end> is set to
98531 and the C<END> block simply exits with C<$single> set to 0 (don't
9854break, run to completion.).
9855
9856=cut
9857
9858END {
9859    $finished = 1 if $inhibit_exit;    # So that some commands may be disabled.
9860    $fall_off_end = 1 unless $inhibit_exit;
9861
9862    # Do not stop in at_exit() and destructors on exit:
9863    if ($fall_off_end or $runnonstop) {
9864        save_hist();
9865    } else {
9866        $DB::single = 1;
9867        DB::fake::at_exit();
9868    }
9869} ## end END
9870
9871=head1 PRE-5.8 COMMANDS
9872
9873Some of the commands changed function quite a bit in the 5.8 command
9874realignment, so much so that the old code had to be replaced completely.
9875Because we wanted to retain the option of being able to go back to the
9876former command set, we moved the old code off to this section.
9877
9878There's an awful lot of duplicated code here. We've duplicated the
9879comments to keep things clear.
9880
9881=head2 Null command
9882
9883Does nothing. Used to I<turn off> commands.
9884
9885=cut
9886
9887sub cmd_pre580_null {
9888
9889    # do nothing...
9890}
9891
9892=head2 Old C<a> command.
9893
9894This version added actions if you supplied them, and deleted them
9895if you didn't.
9896
9897=cut
9898
9899sub cmd_pre580_a {
9900    my $xcmd = shift;
9901    my $cmd  = shift;
9902
9903    # Argument supplied. Add the action.
9904    if ( $cmd =~ /^(\d*)\s*(.*)/ ) {
9905
9906        # If the line isn't there, use the current line.
9907        my $i = $1 || $line;
9908        my $j = $2;
9909
9910        # If there is an action ...
9911        if ( length $j ) {
9912
9913            # ... but the line isn't breakable, skip it.
9914            if ( $dbline[$i] == 0 ) {
9915                print $OUT "Line $i may not have an action.\n";
9916            }
9917            else {
9918
9919                # ... and the line is breakable:
9920                # Mark that there's an action in this file.
9921                $had_breakpoints{$filename} |= 2;
9922
9923                # Delete any current action.
9924                $dbline{$i} =~ s/\0[^\0]*//;
9925
9926                # Add the new action, continuing the line as needed.
9927                $dbline{$i} .= "\0" . action($j);
9928            }
9929        } ## end if (length $j)
9930
9931        # No action supplied.
9932        else {
9933
9934            # Delete the action.
9935            $dbline{$i} =~ s/\0[^\0]*//;
9936
9937            # Mark as having no break or action if nothing's left.
9938            delete $dbline{$i} if $dbline{$i} eq '';
9939        }
9940    } ## end if ($cmd =~ /^(\d*)\s*(.*)/)
9941} ## end sub cmd_pre580_a
9942
9943=head2 Old C<b> command
9944
9945Add breakpoints.
9946
9947=cut
9948
9949sub cmd_pre580_b {
9950    my $xcmd   = shift;
9951    my $cmd    = shift;
9952    my $dbline = shift;
9953
9954    # Break on load.
9955    if ( $cmd =~ /^load\b\s*(.*)/ ) {
9956        my $file = $1;
9957        $file =~ s/\s+$//;
9958        cmd_b_load($file);
9959    }
9960
9961    # b compile|postpone <some sub> [<condition>]
9962    # The interpreter actually traps this one for us; we just put the
9963    # necessary condition in the %postponed hash.
9964    elsif ( $cmd =~ /^(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/ ) {
9965
9966        # Capture the condition if there is one. Make it true if none.
9967        my $cond = length $3 ? $3 : '1';
9968
9969        # Save the sub name and set $break to 1 if $1 was 'postpone', 0
9970        # if it was 'compile'.
9971        my ( $subname, $break ) = ( $2, $1 eq 'postpone' );
9972
9973        # De-Perl4-ify the name - ' separators to ::.
9974        $subname =~ s/\'/::/g;
9975
9976        # Qualify it into the current package unless it's already qualified.
9977        $subname = "${package}::" . $subname
9978          unless $subname =~ /::/;
9979
9980        # Add main if it starts with ::.
9981        $subname = "main" . $subname if substr( $subname, 0, 2 ) eq "::";
9982
9983        # Save the break type for this sub.
9984        $postponed{$subname} = $break ? "break +0 if $cond" : "compile";
9985    } ## end elsif ($cmd =~ ...
9986
9987    # b <sub name> [<condition>]
9988    elsif ( $cmd =~ /^([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/ ) {
9989        my $subname = $1;
9990        my $cond = length $2 ? $2 : '1';
9991        cmd_b_sub( $subname, $cond );
9992    }
9993    # b <line> [<condition>].
9994    elsif ( $cmd =~ /^(\d*)\s*(.*)/ ) {
9995        my $i = $1 || $dbline;
9996        my $cond = length $2 ? $2 : '1';
9997        cmd_b_line( $i, $cond );
9998    }
9999} ## end sub cmd_pre580_b
10000
10001=head2 Old C<D> command.
10002
10003Delete all breakpoints unconditionally.
10004
10005=cut
10006
10007sub cmd_pre580_D {
10008    my $xcmd = shift;
10009    my $cmd  = shift;
10010    if ( $cmd =~ /^\s*$/ ) {
10011        print $OUT "Deleting all breakpoints...\n";
10012
10013        # %had_breakpoints lists every file that had at least one
10014        # breakpoint in it.
10015        my $file;
10016        for $file ( keys %had_breakpoints ) {
10017
10018            # Switch to the desired file temporarily.
10019            local *dbline = $main::{ '_<' . $file };
10020
10021            $max = $#dbline;
10022            my $was;
10023
10024            # For all lines in this file ...
10025            for my $i (1 .. $max) {
10026
10027                # If there's a breakpoint or action on this line ...
10028                if ( defined $dbline{$i} ) {
10029
10030                    # ... remove the breakpoint.
10031                    $dbline{$i} =~ s/^[^\0]+//;
10032                    if ( $dbline{$i} =~ s/^\0?$// ) {
10033
10034                        # Remove the entry altogether if no action is there.
10035                        delete $dbline{$i};
10036                    }
10037                } ## end if (defined $dbline{$i...
10038            } ## end for my $i (1 .. $max)
10039
10040            # If, after we turn off the "there were breakpoints in this file"
10041            # bit, the entry in %had_breakpoints for this file is zero,
10042            # we should remove this file from the hash.
10043            if ( not $had_breakpoints{$file} &= ~1 ) {
10044                delete $had_breakpoints{$file};
10045            }
10046        } ## end for $file (keys %had_breakpoints)
10047
10048        # Kill off all the other breakpoints that are waiting for files that
10049        # haven't been loaded yet.
10050        undef %postponed;
10051        undef %postponed_file;
10052        undef %break_on_load;
10053    } ## end if ($cmd =~ /^\s*$/)
10054} ## end sub cmd_pre580_D
10055
10056=head2 Old C<h> command
10057
10058Print help. Defaults to printing the long-form help; the 5.8 version
10059prints the summary by default.
10060
10061=cut
10062
10063sub cmd_pre580_h {
10064    my $xcmd = shift;
10065    my $cmd  = shift;
10066
10067    # Print the *right* help, long format.
10068    if ( $cmd =~ /^\s*$/ ) {
10069        print_help($pre580_help);
10070    }
10071
10072    # 'h h' - explicitly-requested summary.
10073    elsif ( $cmd =~ /^h\s*/ ) {
10074        print_help($pre580_summary);
10075    }
10076
10077    # Find and print a command's help.
10078    elsif ( $cmd =~ /^h\s+(\S.*)$/ ) {
10079        my $asked  = $1;                   # for proper errmsg
10080        my $qasked = quotemeta($asked);    # for searching
10081                                           # XXX: finds CR but not <CR>
10082        if (
10083            $pre580_help =~ /^
10084                              <?           # Optional '<'
10085                              (?:[IB]<)    # Optional markup
10086                              $qasked      # The command name
10087                            /mx
10088          )
10089        {
10090
10091            while (
10092                $pre580_help =~ /^
10093                                  (             # The command help:
10094                                   <?           # Optional '<'
10095                                   (?:[IB]<)    # Optional markup
10096                                   $qasked      # The command name
10097                                   ([\s\S]*?)   # Lines starting with tabs
10098                                   \n           # Final newline
10099                                  )
10100                                  (?!\s)/mgx
10101              )    # Line not starting with space
10102                   # (Next command's help)
10103            {
10104                print_help($1);
10105            }
10106        } ## end if ($pre580_help =~ /^<?(?:[IB]<)$qasked/m)
10107
10108        # Help not found.
10109        else {
10110            print_help("B<$asked> is not a debugger command.\n");
10111        }
10112    } ## end elsif ($cmd =~ /^h\s+(\S.*)$/)
10113} ## end sub cmd_pre580_h
10114
10115=head2 Old C<W> command
10116
10117C<W E<lt>exprE<gt>> adds a watch expression, C<W> deletes them all.
10118
10119=cut
10120
10121sub cmd_pre580_W {
10122    my $xcmd = shift;
10123    my $cmd  = shift;
10124
10125    # Delete all watch expressions.
10126    if ( $cmd =~ /^$/ ) {
10127
10128        # No watching is going on.
10129        $trace &= ~2;
10130
10131        # Kill all the watch expressions and values.
10132        @to_watch = @old_watch = ();
10133    }
10134
10135    # Add a watch expression.
10136    elsif ( $cmd =~ /^(.*)/s ) {
10137
10138        # add it to the list to be watched.
10139        push @to_watch, $1;
10140
10141        # Get the current value of the expression.
10142        # Doesn't handle expressions returning list values!
10143        $evalarg = $1;
10144        # The &-call is here to ascertain the mutability of @_.
10145        my ($val) = &DB::eval;
10146        $val = ( defined $val ) ? "'$val'" : 'undef';
10147
10148        # Save it.
10149        push @old_watch, $val;
10150
10151        # We're watching stuff.
10152        $trace |= 2;
10153
10154    } ## end elsif ($cmd =~ /^(.*)/s)
10155} ## end sub cmd_pre580_W
10156
10157=head1 PRE-AND-POST-PROMPT COMMANDS AND ACTIONS
10158
10159The debugger used to have a bunch of nearly-identical code to handle
10160the pre-and-post-prompt action commands. C<cmd_pre590_prepost> and
10161C<cmd_prepost> unify all this into one set of code to handle the
10162appropriate actions.
10163
10164=head2 C<cmd_pre590_prepost>
10165
10166A small wrapper around C<cmd_prepost>; it makes sure that the default doesn't
10167do something destructive. In pre 5.8 debuggers, the default action was to
10168delete all the actions.
10169
10170=cut
10171
10172sub cmd_pre590_prepost {
10173    my $cmd    = shift;
10174    my $line   = shift || '*';
10175    my $dbline = shift;
10176
10177    return cmd_prepost( $cmd, $line, $dbline );
10178} ## end sub cmd_pre590_prepost
10179
10180=head2 C<cmd_prepost>
10181
10182Actually does all the handling for C<E<lt>>, C<E<gt>>, C<{{>, C<{>, etc.
10183Since the lists of actions are all held in arrays that are pointed to by
10184references anyway, all we have to do is pick the right array reference and
10185then use generic code to all, delete, or list actions.
10186
10187=cut
10188
10189sub cmd_prepost {
10190    my $cmd = shift;
10191
10192    # No action supplied defaults to 'list'.
10193    my $line = shift || '?';
10194
10195    # Figure out what to put in the prompt.
10196    my $which = '';
10197
10198    # Make sure we have some array or another to address later.
10199    # This means that if for some reason the tests fail, we won't be
10200    # trying to stash actions or delete them from the wrong place.
10201    my $aref = [];
10202
10203    # < - Perl code to run before prompt.
10204    if ( $cmd =~ /^\</o ) {
10205        $which = 'pre-perl';
10206        $aref  = $pre;
10207    }
10208
10209    # > - Perl code to run after prompt.
10210    elsif ( $cmd =~ /^\>/o ) {
10211        $which = 'post-perl';
10212        $aref  = $post;
10213    }
10214
10215    # { - first check for properly-balanced braces.
10216    elsif ( $cmd =~ /^\{/o ) {
10217        if ( $cmd =~ /^\{.*\}$/o && unbalanced( substr( $cmd, 1 ) ) ) {
10218            print $OUT
10219"$cmd is now a debugger command\nuse ';$cmd' if you mean Perl code\n";
10220        }
10221
10222        # Properly balanced. Pre-prompt debugger actions.
10223        else {
10224            $which = 'pre-debugger';
10225            $aref  = $pretype;
10226        }
10227    } ## end elsif ( $cmd =~ /^\{/o )
10228
10229    # Did we find something that makes sense?
10230    unless ($which) {
10231        print $OUT "Confused by command: $cmd\n";
10232    }
10233
10234    # Yes.
10235    else {
10236
10237        # List actions.
10238        if ( $line =~ /^\s*\?\s*$/o ) {
10239            unless (@$aref) {
10240
10241                # Nothing there. Complain.
10242                print $OUT "No $which actions.\n";
10243            }
10244            else {
10245
10246                # List the actions in the selected list.
10247                print $OUT "$which commands:\n";
10248                foreach my $action (@$aref) {
10249                    print $OUT "\t$cmd -- $action\n";
10250                }
10251            } ## end else
10252        } ## end if ( $line =~ /^\s*\?\s*$/o)
10253
10254        # Might be a delete.
10255        else {
10256            if ( length($cmd) == 1 ) {
10257                if ( $line =~ /^\s*\*\s*$/o ) {
10258
10259                    # It's a delete. Get rid of the old actions in the
10260                    # selected list..
10261                    @$aref = ();
10262                    print $OUT "All $cmd actions cleared.\n";
10263                }
10264                else {
10265
10266                    # Replace all the actions. (This is a <, >, or {).
10267                    @$aref = action($line);
10268                }
10269            } ## end if ( length($cmd) == 1)
10270            elsif ( length($cmd) == 2 ) {
10271
10272                # Add the action to the line. (This is a <<, >>, or {{).
10273                push @$aref, action($line);
10274            }
10275            else {
10276
10277                # <<<, >>>>, {{{{{{ ... something not a command.
10278                print $OUT
10279                  "Confused by strange length of $which command($cmd)...\n";
10280            }
10281        } ## end else [ if ( $line =~ /^\s*\?\s*$/o)
10282    } ## end else
10283} ## end sub cmd_prepost
10284
10285=head1 C<DB::fake>
10286
10287Contains the C<at_exit> routine that the debugger uses to issue the
10288C<Debugged program terminated ...> message after the program completes. See
10289the C<END> block documentation for more details.
10290
10291=cut
10292
10293package DB::fake;
10294
10295sub at_exit {
10296    "Debugged program terminated.  Use 'q' to quit or 'R' to restart.";
10297}
10298
10299package DB;    # Do not trace this 1; below!
10300
103011;
10302
10303
10304