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