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.77';
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        import threads::shared qw(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 = $subname;
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 ($spec, $start_match, $end_match) = @_;
2709
2710    # Determine end point; use end of file if not specified.
2711    my $end = ( !defined $start_match ) ? $max :
2712    ( $end_match ? $end_match : $start_match );
2713
2714    # Go on to the end, and then stop.
2715    _minify_to_max(\$end);
2716
2717    # Determine start line.
2718    my $i = $start_match;
2719
2720    if ($i eq '.') {
2721        $i = $spec;
2722    }
2723
2724    $i = _max($i, 1);
2725
2726    $incr = $end - $i;
2727
2728    return ($end, $i);
2729}
2730
2731sub _cmd_l_range {
2732    my ($spec, $current_line, $start_match, $end_match) = @_;
2733
2734    my ($end, $i) =
2735        _cmd_l_calc_initial_end_and_i($spec, $start_match, $end_match);
2736
2737    # If we're running under a client editor, force it to show the lines.
2738    if ($client_editor) {
2739        print {$OUT} "$sub_twice$filename:$i:0\n";
2740        $i = $end;
2741    }
2742    # We're doing it ourselves. We want to show the line and special
2743    # markers for:
2744    # - the current line in execution
2745    # - whether a line is breakable or not
2746    # - whether a line has a break or not
2747    # - whether a line has an action or not
2748    else {
2749        I_TO_END:
2750        for ( ; $i <= $end ; $i++ ) {
2751
2752            # Check for breakpoints and actions.
2753            my ( $stop, $action );
2754            if ($dbline{$i}) {
2755                ( $stop, $action ) = split( /\0/, $dbline{$i} );
2756            }
2757
2758            # ==> if this is the current line in execution,
2759            # : if it's breakable.
2760            my $arrow =
2761            ( $i == $current_line and $filename eq $filename_ini )
2762            ? '==>'
2763            : ( $dbline[$i] + 0 ? ':' : ' ' );
2764
2765            # Add break and action indicators.
2766            $arrow .= 'b' if $stop;
2767            $arrow .= 'a' if $action;
2768
2769            # Print the line.
2770            print {$OUT} "$i$arrow\t", $dbline[$i];
2771
2772            # Move on to the next line. Drop out on an interrupt.
2773            if ($signal) {
2774                $i++;
2775                last I_TO_END;
2776            }
2777        } ## end for (; $i <= $end ; $i++)
2778
2779        # Line the prompt up; print a newline if the last line listed
2780        # didn't have a newline.
2781        if ($dbline[ $i - 1 ] !~ /\n\z/) {
2782            print {$OUT} "\n";
2783        }
2784    } ## end else [ if ($client_editor)
2785
2786    # Save the point we last listed to in case another relative 'l'
2787    # command is desired. Don't let it run off the end.
2788    $start = $i;
2789    _minify_to_max(\$start);
2790
2791    return;
2792}
2793
2794sub _cmd_l_main {
2795    my $spec = shift;
2796
2797    # If this is '-something', delete any spaces after the dash.
2798    $spec =~ s/\A-\s*\z/-/;
2799
2800    # If the line is '$something', assume this is a scalar containing a
2801    # line number.
2802    # Set up for DB::eval() - evaluate in *user* context.
2803    if ( my ($var_name) = $spec =~ /\A(\$.*)/s ) {
2804        return _cmd_l_handle_var_name($var_name);
2805    }
2806    # l name. Try to find a sub by that name.
2807    elsif ( ($subname) = $spec =~ /\A([\':A-Za-z_][\':\w]*(?:\[.*\])?)/s ) {
2808        return _cmd_l_handle_subname();
2809    }
2810    # Bare 'l' command.
2811    elsif ( $spec !~ /\S/ ) {
2812        return _cmd_l_empty();
2813    }
2814    # l [start]+number_of_lines
2815    elsif ( my ($new_start, $new_incr) = $spec =~ /\A(\d*)\+(\d*)\z/ ) {
2816        return _cmd_l_plus($new_start, $new_incr);
2817    }
2818    # l start-stop or l start,stop
2819    elsif (my ($s, $e) = $spec =~ /^(?:(-?[\d\$\.]+)(?:[-,]([\d\$\.]+))?)?/ ) {
2820        return _cmd_l_range($spec, $line, $s, $e);
2821    }
2822
2823    return;
2824} ## end sub _cmd_l_main
2825
2826sub _DB__handle_l_command {
2827    my $self = shift;
2828
2829    _cmd_l_main($self->cmd_args);
2830    next CMD;
2831}
2832
2833
2834# 't' is type.
2835# 'm' is method.
2836# 'v' is the value (i.e: method name or subroutine ref).
2837# 's' is subroutine.
2838my %cmd_lookup;
2839
2840BEGIN
2841{
2842    %cmd_lookup =
2843(
2844    '-' => { t => 'm', v => '_handle_dash_command', },
2845    '.' => { t => 's', v => \&_DB__handle_dot_command, },
2846    '=' => { t => 'm', v => '_handle_equal_sign_command', },
2847    'H' => { t => 'm', v => '_handle_H_command', },
2848    'S' => { t => 'm', v => '_handle_S_command', },
2849    'T' => { t => 'm', v => '_handle_T_command', },
2850    'W' => { t => 'm', v => '_handle_W_command', },
2851    'c' => { t => 's', v => \&_DB__handle_c_command, },
2852    'f' => { t => 's', v => \&_DB__handle_f_command, },
2853    'i' => { t => 's', v => \&_DB__handle_i_command, },
2854    'l' => { t => 's', v => \&_DB__handle_l_command, },
2855    'm' => { t => 's', v => \&_DB__handle_m_command, },
2856    'n' => { t => 'm', v => '_handle_n_command', },
2857    'p' => { t => 'm', v => '_handle_p_command', },
2858    'q' => { t => 'm', v => '_handle_q_command', },
2859    'r' => { t => 'm', v => '_handle_r_command', },
2860    's' => { t => 'm', v => '_handle_s_command', },
2861    'save' => { t => 'm', v => '_handle_save_command', },
2862    'source' => { t => 'm', v => '_handle_source_command', },
2863    't' => { t => 'm', v => '_handle_t_command', },
2864    'w' => { t => 'm', v => '_handle_w_command', },
2865    'x' => { t => 'm', v => '_handle_x_command', },
2866    'y' => { t => 's', v => \&_DB__handle_y_command, },
2867    (map { $_ => { t => 'm', v => '_handle_V_command_and_X_command', }, }
2868        ('X', 'V')),
2869    (map { $_ => { t => 'm', v => '_handle_enable_disable_commands', }, }
2870        qw(enable disable)),
2871    (map { $_ =>
2872        { t => 's', v => \&_DB__handle_restart_and_rerun_commands, },
2873        } qw(R rerun)),
2874    (map { $_ => {t => 'm', v => '_handle_cmd_wrapper_commands' }, }
2875        qw(a A b B e E h L M o O v w W)),
2876);
2877};
2878
2879sub DB {
2880
2881    # lock the debugger and get the thread id for the prompt
2882    lock($DBGR);
2883    my $tid;
2884    my $position;
2885    my ($prefix, $after, $infix);
2886    my $pat;
2887    my $explicit_stop;
2888    my $piped;
2889    my $selected;
2890
2891    if ($ENV{PERL5DB_THREADED}) {
2892        $tid = eval { "[".threads->tid."]" };
2893    }
2894
2895    my $cmd_verb;
2896    my $cmd_args;
2897
2898    my $obj = DB::Obj->new(
2899        {
2900            position => \$position,
2901            prefix => \$prefix,
2902            after => \$after,
2903            explicit_stop => \$explicit_stop,
2904            infix => \$infix,
2905            cmd_args => \$cmd_args,
2906            cmd_verb => \$cmd_verb,
2907            pat => \$pat,
2908            piped => \$piped,
2909            selected => \$selected,
2910        },
2911    );
2912
2913    $obj->_DB_on_init__initialize_globals(@_);
2914
2915    # Preserve current values of $@, $!, $^E, $,, $/, $\, $^W.
2916    # The code being debugged may have altered them.
2917    DB::save();
2918
2919    # Since DB::DB gets called after every line, we can use caller() to
2920    # figure out where we last were executing. Sneaky, eh? This works because
2921    # caller is returning all the extra information when called from the
2922    # debugger.
2923    local ( $package, $filename, $line ) = caller;
2924    $filename_ini = $filename;
2925
2926    # set up the context for DB::eval, so it can properly execute
2927    # code on behalf of the user. We add the package in so that the
2928    # code is eval'ed in the proper package (not in the debugger!).
2929    local $usercontext = _calc_usercontext($package);
2930
2931    # Create an alias to the active file magical array to simplify
2932    # the code here.
2933    local (*dbline) = $main::{ '_<' . $filename };
2934
2935    # Last line in the program.
2936    $max = $#dbline;
2937
2938    # The &-call is here to ascertain the mutability of @_.
2939    &_DB__determine_if_we_should_break;
2940
2941    # Preserve the current stop-or-not, and see if any of the W
2942    # (watch expressions) has changed.
2943    my $was_signal = $signal;
2944
2945    # If we have any watch expressions ...
2946    _DB__handle_watch_expressions($obj);
2947
2948=head2 C<watchfunction()>
2949
2950C<watchfunction()> is a function that can be defined by the user; it is a
2951function which will be run on each entry to C<DB::DB>; it gets the
2952current package, filename, and line as its parameters.
2953
2954The watchfunction can do anything it likes; it is executing in the
2955debugger's context, so it has access to all of the debugger's internal
2956data structures and functions.
2957
2958C<watchfunction()> can control the debugger's actions. Any of the following
2959will cause the debugger to return control to the user's program after
2960C<watchfunction()> executes:
2961
2962=over 4
2963
2964=item *
2965
2966Returning a false value from the C<watchfunction()> itself.
2967
2968=item *
2969
2970Altering C<$single> to a false value.
2971
2972=item *
2973
2974Altering C<$signal> to a false value.
2975
2976=item *
2977
2978Turning off the C<4> bit in C<$trace> (this also disables the
2979check for C<watchfunction()>. This can be done with
2980
2981    $trace &= ~4;
2982
2983=back
2984
2985=cut
2986
2987    # If there's a user-defined DB::watchfunction, call it with the
2988    # current package, filename, and line. The function executes in
2989    # the DB:: package.
2990    if ( $trace & 4 ) {    # User-installed watch
2991        return
2992          if watchfunction( $package, $filename, $line )
2993          and not $single
2994          and not $was_signal
2995          and not( $trace & ~4 );
2996    } ## end if ($trace & 4)
2997
2998    # Pick up any alteration to $signal in the watchfunction, and
2999    # turn off the signal now.
3000    $was_signal = $signal;
3001    $signal     = 0;
3002
3003=head2 GETTING READY TO EXECUTE COMMANDS
3004
3005The debugger decides to take control if single-step mode is on, the
3006C<t> command was entered, or the user generated a signal. If the program
3007has fallen off the end, we set things up so that entering further commands
3008won't cause trouble, and we say that the program is over.
3009
3010=cut
3011
3012    # Make sure that we always print if asked for explicitly regardless
3013    # of $trace_to_depth .
3014    $explicit_stop = ($single || $was_signal);
3015
3016    # Check to see if we should grab control ($single true,
3017    # trace set appropriately, or we got a signal).
3018    if ( $explicit_stop || ( $trace & 1 ) ) {
3019        $obj->_DB__grab_control(@_);
3020    } ## end if ($single || ($trace...
3021
3022=pod
3023
3024If there's an action to be executed for the line we stopped at, execute it.
3025If there are any preprompt actions, execute those as well.
3026
3027=cut
3028
3029    # If there's an action, do it now.
3030    if ($action) {
3031        $evalarg = $action;
3032        # The &-call is here to ascertain the mutability of @_.
3033        &DB::eval;
3034    }
3035    undef $action;
3036
3037    # Are we nested another level (e.g., did we evaluate a function
3038    # that had a breakpoint in it at the debugger prompt)?
3039    if ( $single || $was_signal ) {
3040
3041        # Yes, go down a level.
3042        local $level = $level + 1;
3043
3044        # Do any pre-prompt actions.
3045        foreach $evalarg (@$pre) {
3046            # The &-call is here to ascertain the mutability of @_.
3047            &DB::eval;
3048        }
3049
3050        # Complain about too much recursion if we passed the limit.
3051        if ($single & 4) {
3052            print $OUT $stack_depth . " levels deep in subroutine calls!\n";
3053        }
3054
3055        # The line we're currently on. Set $incr to -1 to stay here
3056        # until we get a command that tells us to advance.
3057        $start = $line;
3058        $incr  = -1;      # for backward motion.
3059
3060        # Tack preprompt debugger actions ahead of any actual input.
3061        @typeahead = ( @$pretype, @typeahead );
3062
3063=head2 WHERE ARE WE?
3064
3065XXX Relocate this section?
3066
3067The debugger normally shows the line corresponding to the current line of
3068execution. Sometimes, though, we want to see the next line, or to move elsewhere
3069in the file. This is done via the C<$incr>, C<$start>, and C<$max> variables.
3070
3071C<$incr> controls by how many lines the I<current> line should move forward
3072after a command is executed. If set to -1, this indicates that the I<current>
3073line shouldn't change.
3074
3075C<$start> is the I<current> line. It is used for things like knowing where to
3076move forwards or backwards from when doing an C<L> or C<-> command.
3077
3078C<$max> tells the debugger where the last line of the current file is. It's
3079used to terminate loops most often.
3080
3081=head2 THE COMMAND LOOP
3082
3083Most of C<DB::DB> is actually a command parsing and dispatch loop. It comes
3084in two parts:
3085
3086=over 4
3087
3088=item *
3089
3090The outer part of the loop, starting at the C<CMD> label. This loop
3091reads a command and then executes it.
3092
3093=item *
3094
3095The inner part of the loop, starting at the C<PIPE> label. This part
3096is wholly contained inside the C<CMD> block and only executes a command.
3097Used to handle commands running inside a pager.
3098
3099=back
3100
3101So why have two labels to restart the loop? Because sometimes, it's easier to
3102have a command I<generate> another command and then re-execute the loop to do
3103the new command. This is faster, but perhaps a bit more convoluted.
3104
3105=cut
3106
3107        # The big command dispatch loop. It keeps running until the
3108        # user yields up control again.
3109        #
3110        # If we have a terminal for input, and we get something back
3111        # from readline(), keep on processing.
3112
3113      CMD:
3114        while (_DB__read_next_cmd($tid))
3115        {
3116
3117            share($cmd);
3118            # ... try to execute the input as debugger commands.
3119
3120            # Don't stop running.
3121            $single = 0;
3122
3123            # No signal is active.
3124            $signal = 0;
3125
3126            # Handle continued commands (ending with \):
3127            if ($cmd =~ s/\\\z/\n/) {
3128                $cmd .= DB::readline("  cont: ");
3129                redo CMD;
3130            }
3131
3132=head4 The null command
3133
3134A newline entered by itself means I<re-execute the last command>. We grab the
3135command out of C<$laststep> (where it was recorded previously), and copy it
3136back into C<$cmd> to be executed below. If there wasn't any previous command,
3137we'll do nothing below (no command will match). If there was, we also save it
3138in the command history and fall through to allow the command parsing to pick
3139it up.
3140
3141=cut
3142
3143            # Empty input means repeat the last command.
3144            if ($cmd eq '') {
3145                $cmd = $laststep;
3146            }
3147            chomp($cmd);    # get rid of the annoying extra newline
3148            if (length($cmd) >= option_val('HistItemMinLength', 2)) {
3149                push( @hist, $cmd );
3150            }
3151            push( @truehist, $cmd );
3152            share(@hist);
3153            share(@truehist);
3154
3155            # This is a restart point for commands that didn't arrive
3156            # via direct user input. It allows us to 'redo PIPE' to
3157            # re-execute command processing without reading a new command.
3158          PIPE: {
3159                _DB__trim_command_and_return_first_component($obj);
3160
3161=head3 COMMAND ALIASES
3162
3163The debugger can create aliases for commands (these are stored in the
3164C<%alias> hash). Before a command is executed, the command loop looks it up
3165in the alias hash and substitutes the contents of the alias for the command,
3166completely replacing it.
3167
3168=cut
3169
3170                # See if there's an alias for the command, and set it up if so.
3171                if ( $alias{$cmd_verb} ) {
3172
3173                    # Squelch signal handling; we want to keep control here
3174                    # if something goes loco during the alias eval.
3175                    local $SIG{__DIE__};
3176                    local $SIG{__WARN__};
3177
3178                    # This is a command, so we eval it in the DEBUGGER's
3179                    # scope! Otherwise, we can't see the special debugger
3180                    # variables, or get to the debugger's subs. (Well, we
3181                    # _could_, but why make it even more complicated?)
3182                    eval "\$cmd =~ $alias{$cmd_verb}";
3183                    if ($@) {
3184                        local $\ = '';
3185                        print $OUT "Couldn't evaluate '$cmd_verb' alias: $@";
3186                        next CMD;
3187                    }
3188                    _DB__trim_command_and_return_first_component($obj);
3189                } ## end if ($alias{$cmd_verb})
3190
3191=head3 MAIN-LINE COMMANDS
3192
3193All of these commands work up to and after the program being debugged has
3194terminated.
3195
3196=head4 C<q> - quit
3197
3198Quit the debugger. This entails setting the C<$fall_off_end> flag, so we don't
3199try to execute further, cleaning any restart-related stuff out of the
3200environment, and executing with the last value of C<$?>.
3201
3202=cut
3203
3204                # All of these commands were remapped in perl 5.8.0;
3205                # we send them off to the secondary dispatcher (see below).
3206                $obj->_handle_special_char_cmd_wrapper_commands;
3207                _DB__trim_command_and_return_first_component($obj);
3208
3209                if (my $cmd_rec = $cmd_lookup{$cmd_verb}) {
3210                    my $type = $cmd_rec->{t};
3211                    my $val = $cmd_rec->{v};
3212                    if ($type eq 'm') {
3213                        $obj->$val();
3214                    }
3215                    elsif ($type eq 's') {
3216                        $val->($obj);
3217                    }
3218                }
3219
3220=head4 C<t> - trace [n]
3221
3222Turn tracing on or off. Inverts the appropriate bit in C<$trace> (q.v.).
3223If level is specified, set C<$trace_to_depth>.
3224
3225=head4 C<S> - list subroutines matching/not matching a pattern
3226
3227Walks through C<%sub>, checking to see whether or not to print the name.
3228
3229=head4 C<X> - list variables in current package
3230
3231Since the C<V> command actually processes this, just change this to the
3232appropriate C<V> command and fall through.
3233
3234=head4 C<V> - list variables
3235
3236Uses C<dumpvar.pl> to dump out the current values for selected variables.
3237
3238=head4 C<x> - evaluate and print an expression
3239
3240Hands the expression off to C<DB::eval>, setting it up to print the value
3241via C<dumpvar.pl> instead of just printing it directly.
3242
3243=head4 C<m> - print methods
3244
3245Just uses C<DB::methods> to determine what methods are available.
3246
3247=head4 C<f> - switch files
3248
3249Switch to a different filename.
3250
3251=head4 C<.> - return to last-executed line.
3252
3253We set C<$incr> to -1 to indicate that the debugger shouldn't move ahead,
3254and then we look up the line in the magical C<%dbline> hash.
3255
3256=head4 C<-> - back one window
3257
3258We change C<$start> to be one window back; if we go back past the first line,
3259we set it to be the first line. We set C<$incr> to put us back at the
3260currently-executing line, and then put a S<C<l $start +>> (list one window from
3261C<$start>) in C<$cmd> to be executed later.
3262
3263=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>>
3264
3265In Perl 5.8.0, a realignment of the commands was done to fix up a number of
3266problems, most notably that the default case of several commands destroying
3267the user's work in setting watchpoints, actions, etc. We wanted, however, to
3268retain the old commands for those who were used to using them or who preferred
3269them. At this point, we check for the new commands and call C<cmd_wrapper> to
3270deal with them instead of processing them in-line.
3271
3272=head4 C<y> - List lexicals in higher scope
3273
3274Uses C<PadWalker> to find the lexicals supplied as arguments in a scope
3275above the current one and then displays them using F<dumpvar.pl>.
3276
3277=head3 COMMANDS NOT WORKING AFTER PROGRAM ENDS
3278
3279All of the commands below this point don't work after the program being
3280debugged has ended. All of them check to see if the program has ended; this
3281allows the commands to be relocated without worrying about a 'line of
3282demarcation' above which commands can be entered anytime, and below which
3283they can't.
3284
3285=head4 C<n> - single step, but don't trace down into subs
3286
3287Done by setting C<$single> to 2, which forces subs to execute straight through
3288when entered (see C<DB::sub> in L</DEBUGGER INTERFACE VARIABLES>). We also
3289save the C<n> command in C<$laststep>,
3290
3291so a null command knows what to re-execute.
3292
3293=head4 C<s> - single-step, entering subs
3294
3295Sets C<$single> to 1, which causes C<DB::sub> to continue tracing inside
3296subs. Also saves C<s> as C<$lastcmd>.
3297
3298=head4 C<c> - run continuously, setting an optional breakpoint
3299
3300Most of the code for this command is taken up with locating the optional
3301breakpoint, which is either a subroutine name or a line number. We set
3302the appropriate one-time-break in C<@dbline> and then turn off single-stepping
3303in this and all call levels above this one.
3304
3305=head4 C<r> - return from a subroutine
3306
3307For C<r> to work properly, the debugger has to stop execution again
3308immediately after the return is executed. This is done by forcing
3309single-stepping to be on in the call level above the current one. If
3310we are printing return values when a C<r> is executed, set C<$doret>
3311appropriately, and force us out of the command loop.
3312
3313=head4 C<T> - stack trace
3314
3315Just calls C<DB::print_trace>.
3316
3317=head4 C<w> - List window around current line.
3318
3319Just calls C<DB::cmd_w>.
3320
3321=head4 C<W> - watch-expression processing.
3322
3323Just calls C<DB::cmd_W>.
3324
3325=head4 C</> - search forward for a string in the source
3326
3327We take the argument and treat it as a pattern. If it turns out to be a
3328bad one, we return the error we got from trying to C<eval> it and exit.
3329If not, we create some code to do the search and C<eval> it so it can't
3330mess us up.
3331
3332=cut
3333
3334                _DB__handle_forward_slash_command($obj);
3335
3336=head4 C<?> - search backward for a string in the source
3337
3338Same as for C</>, except the loop runs backwards.
3339
3340=cut
3341
3342                _DB__handle_question_mark_command($obj);
3343
3344=head4 C<$rc> - Recall command
3345
3346Manages the commands in C<@hist> (which is created if C<Term::ReadLine> reports
3347that the terminal supports history). It finds the command required, puts it
3348into C<$cmd>, and redoes the loop to execute it.
3349
3350=cut
3351
3352                # $rc - recall command.
3353                $obj->_handle_rc_recall_command;
3354
3355=head4 C<$sh$sh> - C<system()> command
3356
3357Calls the C<_db_system()> to handle the command. This keeps the C<STDIN> and
3358C<STDOUT> from getting messed up.
3359
3360=cut
3361
3362                $obj->_handle_sh_command;
3363
3364=head4 C<$rc I<pattern> $rc> - Search command history
3365
3366Another command to manipulate C<@hist>: this one searches it with a pattern.
3367If a command is found, it is placed in C<$cmd> and executed via C<redo>.
3368
3369=cut
3370
3371                $obj->_handle_rc_search_history_command;
3372
3373=head4 C<$sh> - Invoke a shell
3374
3375Uses C<_db_system()> to invoke a shell.
3376
3377=cut
3378
3379=head4 C<$sh I<command>> - Force execution of a command in a shell
3380
3381Like the above, but the command is passed to the shell. Again, we use
3382C<_db_system()> to avoid problems with C<STDIN> and C<STDOUT>.
3383
3384=head4 C<H> - display commands in history
3385
3386Prints the contents of C<@hist> (if any).
3387
3388=head4 C<man, doc, perldoc> - look up documentation
3389
3390Just calls C<runman()> to print the appropriate document.
3391
3392=cut
3393
3394                $obj->_handle_doc_command;
3395
3396=head4 C<p> - print
3397
3398Builds a C<print EXPR> expression in the C<$cmd>; this will get executed at
3399the bottom of the loop.
3400
3401=head4 C<=> - define command alias
3402
3403Manipulates C<%alias> to add or list command aliases.
3404
3405=head4 C<source> - read commands from a file.
3406
3407Opens a lexical filehandle and stacks it on C<@cmdfhs>; C<DB::readline> will
3408pick it up.
3409
3410=head4 C<enable> C<disable> - enable or disable breakpoints
3411
3412This enables or disables breakpoints.
3413
3414=head4 C<save> - send current history to a file
3415
3416Takes the complete history, (not the shrunken version you see with C<H>),
3417and saves it to the given filename, so it can be replayed using C<source>.
3418
3419Note that all C<^(save|source)>'s are commented out with a view to minimise recursion.
3420
3421=head4 C<R> - restart
3422
3423Restart the debugger session.
3424
3425=head4 C<rerun> - rerun the current session
3426
3427Return to any given position in the B<true>-history list
3428
3429=head4 C<|, ||> - pipe output through the pager.
3430
3431For C<|>, we save C<OUT> (the debugger's output filehandle) and C<STDOUT>
3432(the program's standard output). For C<||>, we only save C<OUT>. We open a
3433pipe to the pager (restoring the output filehandles if this fails). If this
3434is the C<|> command, we also set up a C<SIGPIPE> handler which will simply
3435set C<$signal>, sending us back into the debugger.
3436
3437We then trim off the pipe symbols and C<redo> the command loop at the
3438C<PIPE> label, causing us to evaluate the command in C<$cmd> without
3439reading another.
3440
3441=cut
3442
3443                # || - run command in the pager, with output to DB::OUT.
3444                _DB__handle_run_command_in_pager_command($obj);
3445
3446=head3 END OF COMMAND PARSING
3447
3448Anything left in C<$cmd> at this point is a Perl expression that we want to
3449evaluate. We'll always evaluate in the user's context, and fully qualify
3450any variables we might want to address in the C<DB> package.
3451
3452=cut
3453
3454            }    # PIPE:
3455
3456            # trace an expression
3457            $cmd =~ s/^t\s/\$DB::trace |= 1;\n/;
3458
3459            # Make sure the flag that says "the debugger's running" is
3460            # still on, to make sure we get control again.
3461            $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd";
3462
3463            # Run *our* eval that executes in the caller's context.
3464            # The &-call is here to ascertain the mutability of @_.
3465            &DB::eval;
3466
3467            # Turn off the one-time-dump stuff now.
3468            if ($onetimeDump) {
3469                $onetimeDump      = undef;
3470                $onetimedumpDepth = undef;
3471            }
3472            elsif ( $term_pid == $$ ) {
3473                eval { # May run under miniperl, when not available...
3474                    STDOUT->flush();
3475                    STDERR->flush();
3476                };
3477
3478                # XXX If this is the master pid, print a newline.
3479                print {$OUT} "\n";
3480            }
3481        } ## end while (($term || &setterm...
3482
3483=head3 POST-COMMAND PROCESSING
3484
3485After each command, we check to see if the command output was piped anywhere.
3486If so, we go through the necessary code to unhook the pipe and go back to
3487our standard filehandles for input and output.
3488
3489=cut
3490
3491        continue {    # CMD:
3492            _DB__at_end_of_every_command($obj);
3493        }    # CMD:
3494
3495=head3 COMMAND LOOP TERMINATION
3496
3497When commands have finished executing, we come here. If the user closed the
3498input filehandle, we turn on C<$fall_off_end> to emulate a C<q> command. We
3499evaluate any post-prompt items. We restore C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>,
3500C<$\>, and C<$^W>, and return a null list as expected by the Perl interpreter.
3501The interpreter will then execute the next line and then return control to us
3502again.
3503
3504=cut
3505
3506        # No more commands? Quit.
3507        unless (defined $cmd) {
3508            DB::Obj::_do_quit();
3509        }
3510
3511        # Evaluate post-prompt commands.
3512        foreach $evalarg (@$post) {
3513            # The &-call is here to ascertain the mutability of @_.
3514            &DB::eval;
3515        }
3516    }    # if ($single || $signal)
3517
3518    # Put the user's globals back where you found them.
3519    ( $@, $!, $^E, $,, $/, $\, $^W ) = @saved;
3520    ();
3521} ## end sub DB
3522
3523# Because DB::Obj is used above,
3524#
3525#   my $obj = DB::Obj->new(
3526#
3527# The following package declaration must come before that,
3528# or else runtime errors will occur with
3529#
3530#   PERLDB_OPTS="autotrace nonstop"
3531#
3532# ( rt#116771 )
3533BEGIN {
3534
3535package DB::Obj;
3536
3537sub new {
3538    my $class = shift;
3539
3540    my $self = bless {}, $class;
3541
3542    $self->_init(@_);
3543
3544    return $self;
3545}
3546
3547sub _init {
3548    my ($self, $args) = @_;
3549
3550    %{$self} = (%$self, %$args);
3551
3552    return;
3553}
3554
3555{
3556    no strict 'refs';
3557    foreach my $slot_name (qw(
3558        after explicit_stop infix pat piped position prefix selected cmd_verb
3559        cmd_args
3560        )) {
3561        my $slot = $slot_name;
3562        *{$slot} = sub {
3563            my $self = shift;
3564
3565            if (@_) {
3566                ${ $self->{$slot} } = shift;
3567            }
3568
3569            return ${ $self->{$slot} };
3570        };
3571
3572        *{"append_to_$slot"} = sub {
3573            my $self = shift;
3574            my $s = shift;
3575
3576            return $self->$slot($self->$slot . $s);
3577        };
3578    }
3579}
3580
3581sub _DB_on_init__initialize_globals
3582{
3583    my $self = shift;
3584
3585    # Check for whether we should be running continuously or not.
3586    # _After_ the perl program is compiled, $single is set to 1:
3587    if ( $single and not $second_time++ ) {
3588
3589        # Options say run non-stop. Run until we get an interrupt.
3590        if ($runnonstop) {    # Disable until signal
3591                # If there's any call stack in place, turn off single
3592                # stepping into subs throughout the stack.
3593            for my $i (0 .. $stack_depth) {
3594                $stack[ $i ] &= ~1;
3595            }
3596
3597            # And we are now no longer in single-step mode.
3598            $single = 0;
3599
3600            # If we simply returned at this point, we wouldn't get
3601            # the trace info. Fall on through.
3602            # return;
3603        } ## end if ($runnonstop)
3604
3605        elsif ($ImmediateStop) {
3606
3607            # We are supposed to stop here; XXX probably a break.
3608            $ImmediateStop = 0;    # We've processed it; turn it off
3609            $signal        = 1;    # Simulate an interrupt to force
3610                                   # us into the command loop
3611        }
3612    } ## end if ($single and not $second_time...
3613
3614    # If we're in single-step mode, or an interrupt (real or fake)
3615    # has occurred, turn off non-stop mode.
3616    $runnonstop = 0 if $single or $signal;
3617
3618    return;
3619}
3620
3621sub _my_print_lineinfo
3622{
3623    my ($self, $i, $incr_pos) = @_;
3624
3625    if ($frame) {
3626        # Print it indented if tracing is on.
3627        DB::print_lineinfo( ' ' x $stack_depth,
3628            "$i:\t$DB::dbline[$i]" . $self->after );
3629    }
3630    else {
3631        DB::depth_print_lineinfo($self->explicit_stop, $incr_pos);
3632    }
3633}
3634
3635sub _curr_line {
3636    return $DB::dbline[$line];
3637}
3638
3639sub _is_full {
3640    my ($self, $letter) = @_;
3641
3642    return ($DB::cmd eq $letter);
3643}
3644
3645sub _DB__grab_control
3646{
3647    my $self = shift;
3648
3649    # Yes, grab control.
3650    if ($client_editor) {
3651
3652        # Tell the editor to update its position.
3653        $self->position("$sub_twice${DB::filename}:$line:0\n");
3654        DB::print_lineinfo($self->position());
3655    }
3656
3657=pod
3658
3659Special check: if we're in package C<DB::fake>, we've gone through the
3660C<END> block at least once. We set up everything so that we can continue
3661to enter commands and have a valid context to be in.
3662
3663=cut
3664
3665    elsif ( $DB::package eq 'DB::fake' ) {
3666
3667        # Fallen off the end already.
3668        if (!$DB::term) {
3669            DB::setterm();
3670        }
3671
3672        DB::print_help(<<EOP);
3673Debugged program terminated.  Use B<q> to quit or B<R> to restart,
3674use B<o> I<inhibit_exit> to avoid stopping after program termination,
3675S<B<h q>>, S<B<h R>> or S<B<h o>> to get additional info.
3676EOP
3677
3678        $DB::package     = 'main';
3679        $DB::usercontext = DB::_calc_usercontext($DB::package);
3680    } ## end elsif ($package eq 'DB::fake')
3681
3682=pod
3683
3684If the program hasn't finished executing, we scan forward to the
3685next executable line, print that out, build the prompt from the file and line
3686number information, and print that.
3687
3688=cut
3689
3690    else {
3691
3692
3693        # Still somewhere in the midst of execution. Set up the
3694        #  debugger prompt.
3695        $DB::sub =~ s/\'/::/;    # Swap Perl 4 package separators (') to
3696                             # Perl 5 ones (sorry, we don't print Klingon
3697                             #module names)
3698
3699        $self->prefix($DB::sub =~ /::/ ? "" : ($DB::package . '::'));
3700        $self->append_to_prefix( "$DB::sub(${DB::filename}:" );
3701        $self->after( $self->_curr_line =~ /\n$/ ? '' : "\n" );
3702
3703        # Break up the prompt if it's really long.
3704        if ( length($self->prefix()) > 30 ) {
3705            $self->position($self->prefix . "$line):\n$line:\t" . $self->_curr_line . $self->after);
3706            $self->prefix("");
3707            $self->infix(":\t");
3708        }
3709        else {
3710            $self->infix("):\t");
3711            $self->position(
3712                $self->prefix . $line. $self->infix
3713                . $self->_curr_line . $self->after
3714            );
3715        }
3716
3717        # Print current line info, indenting if necessary.
3718        $self->_my_print_lineinfo($line, $self->position);
3719
3720        my $i;
3721        my $line_i = sub { return $DB::dbline[$i]; };
3722
3723        # Scan forward, stopping at either the end or the next
3724        # unbreakable line.
3725        for ( $i = $line + 1 ; $i <= $DB::max && $line_i->() == 0 ; ++$i )
3726        {    #{ vi
3727
3728            # Drop out on null statements, block closers, and comments.
3729            last if $line_i->() =~ /^\s*[\;\}\#\n]/;
3730
3731            # Drop out if the user interrupted us.
3732            last if $signal;
3733
3734            # Append a newline if the line doesn't have one. Can happen
3735            # in eval'ed text, for instance.
3736            $self->after( $line_i->() =~ /\n$/ ? '' : "\n" );
3737
3738            # Next executable line.
3739            my $incr_pos = $self->prefix . $i . $self->infix . $line_i->()
3740                . $self->after;
3741            $self->append_to_position($incr_pos);
3742            $self->_my_print_lineinfo($i, $incr_pos);
3743        } ## end for ($i = $line + 1 ; $i...
3744    } ## end else [ if ($client_editor)
3745
3746    return;
3747}
3748
3749sub _handle_t_command {
3750    my $self = shift;
3751
3752    my $levels = $self->cmd_args();
3753
3754    if ((!length($levels)) or ($levels !~ /\D/)) {
3755        $trace ^= 1;
3756        local $\ = '';
3757        $DB::trace_to_depth = $levels ? $stack_depth + $levels : 1E9;
3758        print {$OUT} "Trace = "
3759        . ( ( $trace & 1 )
3760            ? ( $levels ? "on (to level $DB::trace_to_depth)" : "on" )
3761            : "off" ) . "\n";
3762        next CMD;
3763    }
3764
3765    return;
3766}
3767
3768
3769sub _handle_S_command {
3770    my $self = shift;
3771
3772    if (my ($print_all_subs, $should_reverse, $Spatt)
3773        = $self->cmd_args =~ /\A((!)?(.+))?\z/) {
3774        # $Spatt is the pattern (if any) to use.
3775        # Reverse scan?
3776        my $Srev     = defined $should_reverse;
3777        # No args - print all subs.
3778        my $Snocheck = !defined $print_all_subs;
3779
3780        # Need to make these sane here.
3781        local $\ = '';
3782        local $, = '';
3783
3784        # Search through the debugger's magical hash of subs.
3785        # If $nocheck is true, just print the sub name.
3786        # Otherwise, check it against the pattern. We then use
3787        # the XOR trick to reverse the condition as required.
3788        foreach $subname ( sort( keys %sub ) ) {
3789            if ( $Snocheck or $Srev ^ ( $subname =~ /$Spatt/ ) ) {
3790                print $OUT $subname, "\n";
3791            }
3792        }
3793        next CMD;
3794    }
3795
3796    return;
3797}
3798
3799sub _handle_V_command_and_X_command {
3800    my $self = shift;
3801
3802    $DB::cmd =~ s/^X\b/V $DB::package/;
3803
3804    # Bare V commands get the currently-being-debugged package
3805    # added.
3806    if ($self->_is_full('V')) {
3807        $DB::cmd = "V $DB::package";
3808    }
3809
3810    # V - show variables in package.
3811    if (my ($new_packname, $new_vars_str) =
3812        $DB::cmd =~ /\AV\b\s*(\S+)\s*(.*)/) {
3813
3814        # Save the currently selected filehandle and
3815        # force output to debugger's filehandle (dumpvar
3816        # just does "print" for output).
3817        my $savout = select($OUT);
3818
3819        # Grab package name and variables to dump.
3820        $packname = $new_packname;
3821        my @vars     = split( ' ', $new_vars_str );
3822
3823        # If main::dumpvar isn't here, get it.
3824        do 'dumpvar.pl' || die $@ unless defined &main::dumpvar;
3825        if ( defined &main::dumpvar ) {
3826
3827            # We got it. Turn off subroutine entry/exit messages
3828            # for the moment, along with return values.
3829            local $frame = 0;
3830            local $doret = -2;
3831
3832            # must detect sigpipe failures  - not catching
3833            # then will cause the debugger to die.
3834            eval {
3835                main::dumpvar(
3836                    $packname,
3837                    defined $option{dumpDepth}
3838                    ? $option{dumpDepth}
3839                    : -1,    # assume -1 unless specified
3840                    @vars
3841                );
3842            };
3843
3844            # The die doesn't need to include the $@, because
3845            # it will automatically get propagated for us.
3846            if ($@) {
3847                die unless $@ =~ /dumpvar print failed/;
3848            }
3849        } ## end if (defined &main::dumpvar)
3850        else {
3851
3852            # Couldn't load dumpvar.
3853            print $OUT "dumpvar.pl not available.\n";
3854        }
3855
3856        # Restore the output filehandle, and go round again.
3857        select($savout);
3858        next CMD;
3859    }
3860
3861    return;
3862}
3863
3864sub _handle_dash_command {
3865    my $self = shift;
3866
3867    if ($self->_is_full('-')) {
3868
3869        # back up by a window; go to 1 if back too far.
3870        $start -= $incr + $window + 1;
3871        $start = 1 if $start <= 0;
3872        $incr  = $window - 1;
3873
3874        # Generate and execute a "l +" command (handled below).
3875        $DB::cmd = 'l ' . ($start) . '+';
3876        redo CMD;
3877    }
3878    return;
3879}
3880
3881sub _n_or_s_commands_generic {
3882    my ($self, $new_val) = @_;
3883    # n - next
3884    next CMD if DB::_DB__is_finished();
3885
3886    # Single step, but don't enter subs.
3887    $single = $new_val;
3888
3889    # Save for empty command (repeat last).
3890    $laststep = $DB::cmd;
3891    last CMD;
3892}
3893
3894sub _n_or_s {
3895    my ($self, $letter, $new_val) = @_;
3896
3897    if ($self->_is_full($letter)) {
3898        $self->_n_or_s_commands_generic($new_val);
3899    }
3900    else {
3901        $self->_n_or_s_and_arg_commands_generic($letter, $new_val);
3902    }
3903
3904    return;
3905}
3906
3907sub _handle_n_command {
3908    my $self = shift;
3909
3910    return $self->_n_or_s('n', 2);
3911}
3912
3913sub _handle_s_command {
3914    my $self = shift;
3915
3916    return $self->_n_or_s('s', 1);
3917}
3918
3919sub _handle_r_command {
3920    my $self = shift;
3921
3922    # r - return from the current subroutine.
3923    if ($self->_is_full('r')) {
3924
3925        # Can't do anything if the program's over.
3926        next CMD if DB::_DB__is_finished();
3927
3928        # Turn on stack trace.
3929        $stack[$stack_depth] |= 1;
3930
3931        # Print return value unless the stack is empty.
3932        $doret = $option{PrintRet} ? $stack_depth - 1 : -2;
3933        last CMD;
3934    }
3935
3936    return;
3937}
3938
3939sub _handle_T_command {
3940    my $self = shift;
3941
3942    if ($self->_is_full('T')) {
3943        DB::print_trace( $OUT, 1 );    # skip DB
3944        next CMD;
3945    }
3946
3947    return;
3948}
3949
3950sub _handle_w_command {
3951    my $self = shift;
3952
3953    DB::cmd_w( 'w', $self->cmd_args() );
3954    next CMD;
3955
3956    return;
3957}
3958
3959sub _handle_W_command {
3960    my $self = shift;
3961
3962    if (my $arg = $self->cmd_args) {
3963        DB::cmd_W( 'W', $arg );
3964        next CMD;
3965    }
3966
3967    return;
3968}
3969
3970sub _handle_rc_recall_command {
3971    my $self = shift;
3972
3973    # $rc - recall command.
3974    if (my ($minus, $arg) = $DB::cmd =~ m#\A$rc+\s*(-)?(\d+)?\z#) {
3975
3976        # No arguments, take one thing off history.
3977        pop(@hist) if length($DB::cmd) > 1;
3978
3979        # Relative (- found)?
3980        #  Y - index back from most recent (by 1 if bare minus)
3981        #  N - go to that particular command slot or the last
3982        #      thing if nothing following.
3983
3984        $self->cmd_verb(
3985            scalar($minus ? ( $#hist - ( $arg || 1 ) ) : ( $arg || $#hist ))
3986        );
3987
3988        # Pick out the command desired.
3989        $DB::cmd = $hist[$self->cmd_verb];
3990
3991        # Print the command to be executed and restart the loop
3992        # with that command in the buffer.
3993        print {$OUT} $DB::cmd, "\n";
3994        redo CMD;
3995    }
3996
3997    return;
3998}
3999
4000sub _handle_rc_search_history_command {
4001    my $self = shift;
4002
4003    # $rc pattern $rc - find a command in the history.
4004    if (my ($arg) = $DB::cmd =~ /\A$rc([^$rc].*)\z/) {
4005
4006        # Create the pattern to use.
4007        my $pat = "^$arg";
4008        $self->pat($pat);
4009
4010        # Toss off last entry if length is >1 (and it always is).
4011        pop(@hist) if length($DB::cmd) > 1;
4012
4013        my $i;
4014
4015        # Look backward through the history.
4016        SEARCH_HIST:
4017        for ( $i = $#hist ; $i ; --$i ) {
4018            # Stop if we find it.
4019            last SEARCH_HIST if $hist[$i] =~ /$pat/;
4020        }
4021
4022        if ( !$i ) {
4023
4024            # Never found it.
4025            print $OUT "No such command!\n\n";
4026            next CMD;
4027        }
4028
4029        # Found it. Put it in the buffer, print it, and process it.
4030        $DB::cmd = $hist[$i];
4031        print $OUT $DB::cmd, "\n";
4032        redo CMD;
4033    }
4034
4035    return;
4036}
4037
4038sub _handle_H_command {
4039    my $self = shift;
4040
4041    if ($self->cmd_args =~ m#\A\*#) {
4042        @hist = @truehist = ();
4043        print $OUT "History cleansed\n";
4044        next CMD;
4045    }
4046
4047    if (my ($num) = $self->cmd_args =~ /\A(?:-(\d+))?/) {
4048
4049        # Anything other than negative numbers is ignored by
4050        # the (incorrect) pattern, so this test does nothing.
4051        $end = $num ? ( $#hist - $num ) : 0;
4052
4053        # Set to the minimum if less than zero.
4054        $hist = 0 if $hist < 0;
4055
4056        # Start at the end of the array.
4057        # Stay in while we're still above the ending value.
4058        # Tick back by one each time around the loop.
4059        my $i;
4060
4061        for ( $i = $#hist ; $i > $end ; $i-- ) {
4062            print $OUT "$i: ", $hist[$i], "\n";
4063        }
4064
4065        next CMD;
4066    }
4067
4068    return;
4069}
4070
4071sub _handle_doc_command {
4072    my $self = shift;
4073
4074    # man, perldoc, doc - show manual pages.
4075    if (my ($man_page)
4076        = $DB::cmd =~ /\A(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?\z/) {
4077        DB::runman($man_page);
4078        next CMD;
4079    }
4080
4081    return;
4082}
4083
4084sub _handle_p_command {
4085    my $self = shift;
4086
4087    my $print_cmd = 'print {$DB::OUT} ';
4088    # p - print (no args): print $_.
4089    if ($self->_is_full('p')) {
4090        $DB::cmd = $print_cmd . '$_';
4091    }
4092    else {
4093        # p - print the given expression.
4094        $DB::cmd =~ s/\Ap\b/$print_cmd /;
4095    }
4096
4097    return;
4098}
4099
4100sub _handle_equal_sign_command {
4101    my $self = shift;
4102
4103    if ($DB::cmd =~ s/\A=\s*//) {
4104        my @keys;
4105        if ( length $DB::cmd == 0 ) {
4106
4107            # No args, get current aliases.
4108            @keys = sort keys %alias;
4109        }
4110        elsif ( my ( $k, $v ) = ( $DB::cmd =~ /^(\S+)\s+(\S.*)/ ) ) {
4111
4112            # Creating a new alias. $k is alias name, $v is
4113            # alias value.
4114
4115            # can't use $_ or kill //g state
4116            for my $x ( $k, $v ) {
4117
4118                # Escape "alarm" characters.
4119                $x =~ s/\a/\\a/g;
4120            }
4121
4122            # Substitute key for value, using alarm chars
4123            # as separators (which is why we escaped them in
4124            # the command).
4125            $alias{$k} = "s\a$k\a$v\a";
4126
4127            # Turn off standard warn and die behavior.
4128            local $SIG{__DIE__};
4129            local $SIG{__WARN__};
4130
4131            # Is it valid Perl?
4132            unless ( eval "sub { s\a$k\a$v\a }; 1" ) {
4133
4134                # Nope. Bad alias. Say so and get out.
4135                print $OUT "Can't alias $k to $v: $@\n";
4136                delete $alias{$k};
4137                next CMD;
4138            }
4139
4140            # We'll only list the new one.
4141            @keys = ($k);
4142        } ## end elsif (my ($k, $v) = ($DB::cmd...
4143
4144        # The argument is the alias to list.
4145        else {
4146            @keys = ($DB::cmd);
4147        }
4148
4149        # List aliases.
4150        for my $k (@keys) {
4151
4152            # Messy metaquoting: Trim the substitution code off.
4153            # We use control-G as the delimiter because it's not
4154            # likely to appear in the alias.
4155            if ( ( my $v = $alias{$k} ) =~ ss\a$k\a(.*)\a$1 ) {
4156
4157                # Print the alias.
4158                print $OUT "$k\t= $1\n";
4159            }
4160            elsif ( defined $alias{$k} ) {
4161
4162                # Couldn't trim it off; just print the alias code.
4163                print $OUT "$k\t$alias{$k}\n";
4164            }
4165            else {
4166
4167                # No such, dude.
4168                print "No alias for $k\n";
4169            }
4170        } ## end for my $k (@keys)
4171        next CMD;
4172    }
4173
4174    return;
4175}
4176
4177sub _handle_source_command {
4178    my $self = shift;
4179
4180    # source - read commands from a file (or pipe!) and execute.
4181    if (my $sourced_fn = $self->cmd_args) {
4182        if ( open my $fh, $sourced_fn ) {
4183
4184            # Opened OK; stick it in the list of file handles.
4185            push @cmdfhs, $fh;
4186        }
4187        else {
4188
4189            # Couldn't open it.
4190            DB::_db_warn("Can't execute '$sourced_fn': $!\n");
4191        }
4192        next CMD;
4193    }
4194
4195    return;
4196}
4197
4198sub _handle_enable_disable_commands {
4199    my $self = shift;
4200
4201    my $which_cmd = $self->cmd_verb;
4202    my $position = $self->cmd_args;
4203
4204    if ($position !~ /\s/) {
4205        my ($fn, $line_num);
4206        if ($position =~ m{\A\d+\z})
4207        {
4208            $fn = $DB::filename;
4209            $line_num = $position;
4210        }
4211        elsif (my ($new_fn, $new_line_num)
4212            = $position =~ m{\A(.*):(\d+)\z}) {
4213            ($fn, $line_num) = ($new_fn, $new_line_num);
4214        }
4215        else
4216        {
4217            DB::_db_warn("Wrong spec for enable/disable argument.\n");
4218        }
4219
4220        if (defined($fn)) {
4221            if (DB::_has_breakpoint_data_ref($fn, $line_num)) {
4222                DB::_set_breakpoint_enabled_status($fn, $line_num,
4223                    ($which_cmd eq 'enable' ? 1 : '')
4224                );
4225            }
4226            else {
4227                DB::_db_warn("No breakpoint set at ${fn}:${line_num}\n");
4228            }
4229        }
4230
4231        next CMD;
4232    }
4233
4234    return;
4235}
4236
4237sub _handle_save_command {
4238    my $self = shift;
4239
4240    if (my $new_fn = $self->cmd_args) {
4241        my $filename = $new_fn || '.perl5dbrc';    # default?
4242        if ( open my $fh, '>', $filename ) {
4243
4244            # chomp to remove extraneous newlines from source'd files
4245            chomp( my @truelist =
4246                map { m/\A\s*(save|source)/ ? "#$_" : $_ }
4247                @truehist );
4248            print {$fh} join( "\n", @truelist );
4249            print "commands saved in $filename\n";
4250        }
4251        else {
4252            DB::_db_warn("Can't save debugger commands in '$new_fn': $!\n");
4253        }
4254        next CMD;
4255    }
4256
4257    return;
4258}
4259
4260sub _n_or_s_and_arg_commands_generic {
4261    my ($self, $letter, $new_val) = @_;
4262
4263    # s - single-step. Remember the last command was 's'.
4264    if ($DB::cmd =~ s#\A\Q$letter\E\s#\$DB::single = $new_val;\n#) {
4265        $laststep = $letter;
4266    }
4267
4268    return;
4269}
4270
4271sub _handle_sh_command {
4272    my $self = shift;
4273
4274    # $sh$sh - run a shell command (if it's all ASCII).
4275    # Can't run shell commands with Unicode in the debugger, hmm.
4276    my $my_cmd = $DB::cmd;
4277    if ($my_cmd =~ m#\A$sh#gms) {
4278
4279        if ($my_cmd =~ m#\G\z#cgms) {
4280            # Run the user's shell. If none defined, run Bourne.
4281            # We resume execution when the shell terminates.
4282            DB::_db_system( $ENV{SHELL} || "/bin/sh" );
4283            next CMD;
4284        }
4285        elsif ($my_cmd =~ m#\G$sh\s*(.*)#cgms) {
4286            # System it.
4287            DB::_db_system($1);
4288            next CMD;
4289        }
4290        elsif ($my_cmd =~ m#\G\s*(.*)#cgms) {
4291            DB::_db_system( $ENV{SHELL} || "/bin/sh", "-c", $1 );
4292            next CMD;
4293        }
4294    }
4295}
4296
4297sub _handle_x_command {
4298    my $self = shift;
4299
4300    if ($DB::cmd =~ s#\Ax\b# #) {    # Remainder gets done by DB::eval()
4301        $onetimeDump = 'dump';    # main::dumpvar shows the output
4302
4303        # handle special  "x 3 blah" syntax XXX propagate
4304        # doc back to special variables.
4305        if ( $DB::cmd =~ s#\A\s*(\d+)(?=\s)# #) {
4306            $onetimedumpDepth = $1;
4307        }
4308    }
4309
4310    return;
4311}
4312
4313sub _do_quit {
4314    $fall_off_end = 1;
4315    DB::clean_ENV();
4316    exit $?;
4317}
4318
4319sub _handle_q_command {
4320    my $self = shift;
4321
4322    if ($self->_is_full('q')) {
4323        _do_quit();
4324    }
4325
4326    return;
4327}
4328
4329sub _handle_cmd_wrapper_commands {
4330    my $self = shift;
4331
4332    DB::cmd_wrapper( $self->cmd_verb, $self->cmd_args, $line );
4333    next CMD;
4334}
4335
4336sub _handle_special_char_cmd_wrapper_commands {
4337    my $self = shift;
4338
4339    # All of these commands were remapped in perl 5.8.0;
4340    # we send them off to the secondary dispatcher (see below).
4341    if (my ($cmd_letter, $my_arg) = $DB::cmd =~ /\A([<>\{]{1,2})\s*(.*)/so) {
4342        DB::cmd_wrapper( $cmd_letter, $my_arg, $line );
4343        next CMD;
4344    }
4345
4346    return;
4347}
4348
4349} ## end DB::Obj
4350
4351package DB;
4352
4353# The following code may be executed now:
4354# BEGIN {warn 4}
4355
4356=head2 sub
4357
4358C<sub> is called whenever a subroutine call happens in the program being
4359debugged. The variable C<$DB::sub> contains the name of the subroutine
4360being called.
4361
4362The core function of this subroutine is to actually call the sub in the proper
4363context, capturing its output. This of course causes C<DB::DB> to get called
4364again, repeating until the subroutine ends and returns control to C<DB::sub>
4365again. Once control returns, C<DB::sub> figures out whether or not to dump the
4366return value, and returns its captured copy of the return value as its own
4367return value. The value then feeds back into the program being debugged as if
4368C<DB::sub> hadn't been there at all.
4369
4370C<sub> does all the work of printing the subroutine entry and exit messages
4371enabled by setting C<$frame>. It notes what sub the autoloader got called for,
4372and also prints the return value if needed (for the C<r> command and if
4373the 16 bit is set in C<$frame>).
4374
4375It also tracks the subroutine call depth by saving the current setting of
4376C<$single> in the C<@stack> package global; if this exceeds the value in
4377C<$deep>, C<sub> automatically turns on printing of the current depth by
4378setting the C<4> bit in C<$single>. In any case, it keeps the current setting
4379of stop/don't stop on entry to subs set as it currently is set.
4380
4381=head3 C<caller()> support
4382
4383If C<caller()> is called from the package C<DB>, it provides some
4384additional data, in the following order:
4385
4386=over 4
4387
4388=item * C<$package>
4389
4390The package name the sub was in
4391
4392=item * C<$filename>
4393
4394The filename it was defined in
4395
4396=item * C<$line>
4397
4398The line number it was defined on
4399
4400=item * C<$subroutine>
4401
4402The subroutine name; C<(eval)> if an C<eval>().
4403
4404=item * C<$hasargs>
4405
44061 if it has arguments, 0 if not
4407
4408=item * C<$wantarray>
4409
44101 if array context, 0 if scalar context
4411
4412=item * C<$evaltext>
4413
4414The C<eval>() text, if any (undefined for S<C<eval BLOCK>>)
4415
4416=item * C<$is_require>
4417
4418frame was created by a C<use> or C<require> statement
4419
4420=item * C<$hints>
4421
4422pragma information; subject to change between versions
4423
4424=item * C<$bitmask>
4425
4426pragma information; subject to change between versions
4427
4428=item * C<@DB::args>
4429
4430arguments with which the subroutine was invoked
4431
4432=back
4433
4434=cut
4435
4436use vars qw($deep);
4437
4438# We need to fully qualify the name ("DB::sub") to make "use strict;"
4439# happy. -- Shlomi Fish
4440
4441sub _indent_print_line_info {
4442    my ($offset, $str) = @_;
4443
4444    print_lineinfo( ' ' x ($stack_depth - $offset), $str);
4445
4446    return;
4447}
4448
4449sub _print_frame_message {
4450    my ($al) = @_;
4451
4452    if ($frame) {
4453        if ($frame & 4) {   # Extended frame entry message
4454            _indent_print_line_info(-1, "in  ");
4455
4456            # Why -1? But it works! :-(
4457            # Because print_trace will call add 1 to it and then call
4458            # dump_trace; this results in our skipping -1+1 = 0 stack frames
4459            # in dump_trace.
4460            #
4461            # Now it's 0 because we extracted a function.
4462            print_trace( $LINEINFO, 0, 1, 1, "$sub$al" );
4463        }
4464        else {
4465            _indent_print_line_info(-1, "entering $sub$al\n" );
4466        }
4467    }
4468
4469    return;
4470}
4471
4472sub DB::sub {
4473    my ( $al, $ret, @ret ) = "";
4474
4475    # We stack the stack pointer and then increment it to protect us
4476    # from a situation that might unwind a whole bunch of call frames
4477    # at once. Localizing the stack pointer means that it will automatically
4478    # unwind the same amount when multiple stack frames are unwound.
4479    local $stack_depth = $stack_depth + 1;    # Protect from non-local exits
4480
4481    {
4482        # lock ourselves under threads
4483        # While lock() permits recursive locks, there's two cases where it's bad
4484        # that we keep a hold on the lock while we call the sub:
4485        #  - during cloning, Package::CLONE might be called in the context of the new
4486        #    thread, which will deadlock if we hold the lock across the threads::new call
4487        #  - for any function that waits any significant time
4488        # This also deadlocks if the parent thread joins(), since holding the lock
4489        # will prevent any child threads passing this point.
4490        # So release the lock for the function call.
4491        lock($DBGR);
4492
4493        # Whether or not the autoloader was running, a scalar to put the
4494        # sub's return value in (if needed), and an array to put the sub's
4495        # return value in (if needed).
4496        if ($sub eq 'threads::new' && $ENV{PERL5DB_THREADED}) {
4497            print "creating new thread\n";
4498        }
4499
4500        # If the last ten characters are '::AUTOLOAD', note we've traced
4501        # into AUTOLOAD for $sub.
4502        if ( length($sub) > 10 && substr( $sub, -10, 10 ) eq '::AUTOLOAD' ) {
4503            no strict 'refs';
4504            $al = " for $$sub" if defined $$sub;
4505        }
4506
4507        # Expand @stack.
4508        $#stack = $stack_depth;
4509
4510        # Save current single-step setting.
4511        $stack[-1] = $single;
4512
4513        # Turn off all flags except single-stepping.
4514        $single &= 1;
4515
4516        # If we've gotten really deeply recursed, turn on the flag that will
4517        # make us stop with the 'deep recursion' message.
4518        $single |= 4 if $stack_depth == $deep;
4519
4520        # If frame messages are on ...
4521
4522        _print_frame_message($al);
4523    }
4524
4525    # Determine the sub's return type, and capture appropriately.
4526    if (wantarray) {
4527
4528        # Called in array context. call sub and capture output.
4529        # DB::DB will recursively get control again if appropriate; we'll come
4530        # back here when the sub is finished.
4531        no strict 'refs';
4532        @ret = &$sub;
4533    }
4534    elsif ( defined wantarray ) {
4535        no strict 'refs';
4536        # Save the value if it's wanted at all.
4537        $ret = &$sub;
4538    }
4539    else {
4540        no strict 'refs';
4541        # Void return, explicitly.
4542        &$sub;
4543        undef $ret;
4544    }
4545
4546    {
4547        lock($DBGR);
4548
4549        # Pop the single-step value back off the stack.
4550        $single |= $stack[ $stack_depth-- ];
4551
4552        if ($frame & 2) {
4553            if ($frame & 4) {   # Extended exit message
4554                _indent_print_line_info(0, "out ");
4555                print_trace( $LINEINFO, -1, 1, 1, "$sub$al" );
4556            }
4557            else {
4558                _indent_print_line_info(0, "exited $sub$al\n" );
4559            }
4560        }
4561
4562        if (wantarray) {
4563            # Print the return info if we need to.
4564            if ( $doret eq $stack_depth or $frame & 16 ) {
4565
4566                # Turn off output record separator.
4567                local $\ = '';
4568                my $fh = ( $doret eq $stack_depth ? $OUT : $LINEINFO );
4569
4570                # Indent if we're printing because of $frame tracing.
4571                if ($frame & 16)
4572                  {
4573                      print {$fh} ' ' x $stack_depth;
4574                  }
4575
4576                # Print the return value.
4577                print {$fh} "list context return from $sub:\n";
4578                dumpit( $fh, \@ret );
4579
4580                # And don't print it again.
4581                $doret = -2;
4582            } ## end if ($doret eq $stack_depth...
4583            # And we have to return the return value now.
4584            @ret;
4585        } ## end if (wantarray)
4586        # Scalar context.
4587        else {
4588            # If we are supposed to show the return value... same as before.
4589            if ( $doret eq $stack_depth or $frame & 16 and defined wantarray ) {
4590                local $\ = '';
4591                my $fh = ( $doret eq $stack_depth ? $OUT : $LINEINFO );
4592                print $fh ( ' ' x $stack_depth ) if $frame & 16;
4593                print $fh (
4594                           defined wantarray
4595                           ? "scalar context return from $sub: "
4596                           : "void context return from $sub\n"
4597                          );
4598                dumpit( $fh, $ret ) if defined wantarray;
4599                $doret = -2;
4600            } ## end if ($doret eq $stack_depth...
4601
4602            # Return the appropriate scalar value.
4603            $ret;
4604        } ## end else [ if (wantarray)
4605    }
4606} ## end sub _sub
4607
4608sub lsub : lvalue {
4609
4610    # We stack the stack pointer and then increment it to protect us
4611    # from a situation that might unwind a whole bunch of call frames
4612    # at once. Localizing the stack pointer means that it will automatically
4613    # unwind the same amount when multiple stack frames are unwound.
4614    local $stack_depth = $stack_depth + 1;    # Protect from non-local exits
4615
4616    # Expand @stack.
4617    $#stack = $stack_depth;
4618
4619    # Save current single-step setting.
4620    $stack[-1] = $single;
4621
4622    # Turn off all flags except single-stepping.
4623    # Use local so the single-step value is popped back off the
4624    # stack for us.
4625    local $single = $single & 1;
4626
4627    no strict 'refs';
4628    {
4629        # lock ourselves under threads
4630        lock($DBGR);
4631
4632        # Whether or not the autoloader was running, a scalar to put the
4633        # sub's return value in (if needed), and an array to put the sub's
4634        # return value in (if needed).
4635        my ( $al, $ret, @ret ) = "";
4636        if ($sub =~ /^threads::new$/ && $ENV{PERL5DB_THREADED}) {
4637            print "creating new thread\n";
4638        }
4639
4640        # If the last ten characters are C'::AUTOLOAD', note we've traced
4641        # into AUTOLOAD for $sub.
4642        if ( length($sub) > 10 && substr( $sub, -10, 10 ) eq '::AUTOLOAD' ) {
4643            $al = " for $$sub";
4644        }
4645
4646        # If we've gotten really deeply recursed, turn on the flag that will
4647        # make us stop with the 'deep recursion' message.
4648        $single |= 4 if $stack_depth == $deep;
4649
4650        # If frame messages are on ...
4651        _print_frame_message($al);
4652    }
4653
4654    # call the original lvalue sub.
4655    &$sub;
4656}
4657
4658# Abstracting common code from multiple places elsewhere:
4659sub depth_print_lineinfo {
4660    my $always_print = shift;
4661
4662    print_lineinfo( @_ ) if ($always_print or $stack_depth < $trace_to_depth);
4663}
4664
4665=head1 EXTENDED COMMAND HANDLING AND THE COMMAND API
4666
4667In Perl 5.8.0, there was a major realignment of the commands and what they did,
4668Most of the changes were to systematize the command structure and to eliminate
4669commands that threw away user input without checking.
4670
4671The following sections describe the code added to make it easy to support
4672multiple command sets with conflicting command names. This section is a start
4673at unifying all command processing to make it simpler to develop commands.
4674
4675Note that all the cmd_[a-zA-Z] subroutines require the command name, a line
4676number, and C<$dbline> (the current line) as arguments.
4677
4678Support functions in this section which have multiple modes of failure C<die>
4679on error; the rest simply return a false value.
4680
4681The user-interface functions (all of the C<cmd_*> functions) just output
4682error messages.
4683
4684=head2 C<%set>
4685
4686The C<%set> hash defines the mapping from command letter to subroutine
4687name suffix.
4688
4689C<%set> is a two-level hash, indexed by set name and then by command name.
4690Note that trying to set the CommandSet to C<foobar> simply results in the
46915.8.0 command set being used, since there's no top-level entry for C<foobar>.
4692
4693=cut
4694
4695### The API section
4696
4697my %set = (    #
4698    'pre580' => {
4699        'a' => 'pre580_a',
4700        'A' => 'pre580_null',
4701        'b' => 'pre580_b',
4702        'B' => 'pre580_null',
4703        'd' => 'pre580_null',
4704        'D' => 'pre580_D',
4705        'h' => 'pre580_h',
4706        'M' => 'pre580_null',
4707        'O' => 'o',
4708        'o' => 'pre580_null',
4709        'v' => 'M',
4710        'w' => 'v',
4711        'W' => 'pre580_W',
4712    },
4713    'pre590' => {
4714        '<'  => 'pre590_prepost',
4715        '<<' => 'pre590_prepost',
4716        '>'  => 'pre590_prepost',
4717        '>>' => 'pre590_prepost',
4718        '{'  => 'pre590_prepost',
4719        '{{' => 'pre590_prepost',
4720    },
4721);
4722
4723my %breakpoints_data;
4724
4725sub _has_breakpoint_data_ref {
4726    my ($filename, $line) = @_;
4727
4728    return (
4729        exists( $breakpoints_data{$filename} )
4730            and
4731        exists( $breakpoints_data{$filename}{$line} )
4732    );
4733}
4734
4735sub _get_breakpoint_data_ref {
4736    my ($filename, $line) = @_;
4737
4738    return ($breakpoints_data{$filename}{$line} ||= +{});
4739}
4740
4741sub _delete_breakpoint_data_ref {
4742    my ($filename, $line) = @_;
4743
4744    delete($breakpoints_data{$filename}{$line});
4745    if (! scalar(keys( %{$breakpoints_data{$filename}} )) ) {
4746        delete($breakpoints_data{$filename});
4747    }
4748
4749    return;
4750}
4751
4752sub _set_breakpoint_enabled_status {
4753    my ($filename, $line, $status) = @_;
4754
4755    _get_breakpoint_data_ref($filename, $line)->{'enabled'} =
4756        ($status ? 1 : '')
4757        ;
4758
4759    return;
4760}
4761
4762sub _enable_breakpoint_temp_enabled_status {
4763    my ($filename, $line) = @_;
4764
4765    _get_breakpoint_data_ref($filename, $line)->{'temp_enabled'} = 1;
4766
4767    return;
4768}
4769
4770sub _cancel_breakpoint_temp_enabled_status {
4771    my ($filename, $line) = @_;
4772
4773    my $ref = _get_breakpoint_data_ref($filename, $line);
4774
4775    delete ($ref->{'temp_enabled'});
4776
4777    if (! %$ref) {
4778        _delete_breakpoint_data_ref($filename, $line);
4779    }
4780
4781    return;
4782}
4783
4784sub _is_breakpoint_enabled {
4785    my ($filename, $line) = @_;
4786
4787    my $data_ref = _get_breakpoint_data_ref($filename, $line);
4788    return ($data_ref->{'enabled'} || $data_ref->{'temp_enabled'});
4789}
4790
4791=head2 C<cmd_wrapper()> (API)
4792
4793C<cmd_wrapper()> allows the debugger to switch command sets
4794depending on the value of the C<CommandSet> option.
4795
4796It tries to look up the command in the C<%set> package-level I<lexical>
4797(which means external entities can't fiddle with it) and create the name of
4798the sub to call based on the value found in the hash (if it's there). I<All>
4799of the commands to be handled in a set have to be added to C<%set>; if they
4800aren't found, the 5.8.0 equivalent is called (if there is one).
4801
4802This code uses symbolic references.
4803
4804=cut
4805
4806sub cmd_wrapper {
4807    my $cmd      = shift;
4808    my $line     = shift;
4809    my $dblineno = shift;
4810
4811    # Assemble the command subroutine's name by looking up the
4812    # command set and command name in %set. If we can't find it,
4813    # default to the older version of the command.
4814    my $call = 'cmd_'
4815      . ( $set{$CommandSet}{$cmd}
4816          || ( $cmd =~ /\A[<>{]+/o ? 'prepost' : $cmd ) );
4817
4818    # Call the command subroutine, call it by name.
4819    return __PACKAGE__->can($call)->( $cmd, $line, $dblineno );
4820} ## end sub cmd_wrapper
4821
4822=head3 C<cmd_a> (command)
4823
4824The C<a> command handles pre-execution actions. These are associated with a
4825particular line, so they're stored in C<%dbline>. We default to the current
4826line if none is specified.
4827
4828=cut
4829
4830sub cmd_a {
4831    my $cmd    = shift;
4832    my $line   = shift || '';    # [.|line] expr
4833    my $dbline = shift;
4834
4835    # If it's dot (here), or not all digits,  use the current line.
4836    $line =~ s/\A\./$dbline/;
4837
4838    # Should be a line number followed by an expression.
4839    if ( my ($lineno, $expr) = $line =~ /^\s*(\d*)\s*(\S.+)/ ) {
4840
4841        if (! length($lineno)) {
4842            $lineno = $dbline;
4843        }
4844
4845        # If we have an expression ...
4846        if ( length $expr ) {
4847
4848            # ... but the line isn't breakable, complain.
4849            if ( $dbline[$lineno] == 0 ) {
4850                print $OUT
4851                  "Line $lineno($dbline[$lineno]) does not have an action?\n";
4852            }
4853            else {
4854
4855                # It's executable. Record that the line has an action.
4856                $had_breakpoints{$filename} |= 2;
4857
4858                # Remove any action, temp breakpoint, etc.
4859                $dbline{$lineno} =~ s/\0[^\0]*//;
4860
4861                # Add the action to the line.
4862                $dbline{$lineno} .= "\0" . action($expr);
4863
4864                _set_breakpoint_enabled_status($filename, $lineno, 1);
4865            }
4866        } ## end if (length $expr)
4867    } ## end if ($line =~ /^\s*(\d*)\s*(\S.+)/)
4868    else {
4869
4870        # Syntax wrong.
4871        print $OUT
4872          "Adding an action requires an optional lineno and an expression\n"
4873          ;    # hint
4874    }
4875} ## end sub cmd_a
4876
4877=head3 C<cmd_A> (command)
4878
4879Delete actions. Similar to above, except the delete code is in a separate
4880subroutine, C<delete_action>.
4881
4882=cut
4883
4884sub cmd_A {
4885    my $cmd    = shift;
4886    my $line   = shift || '';
4887    my $dbline = shift;
4888
4889    # Dot is this line.
4890    $line =~ s/^\./$dbline/;
4891
4892    # Call delete_action with a null param to delete them all.
4893    # The '1' forces the eval to be true. It'll be false only
4894    # if delete_action blows up for some reason, in which case
4895    # we print $@ and get out.
4896    if ( $line eq '*' ) {
4897        if (! eval { _delete_all_actions(); 1 }) {
4898            print {$OUT} $@;
4899            return;
4900        }
4901    }
4902
4903    # There's a real line  number. Pass it to delete_action.
4904    # Error trapping is as above.
4905    elsif ( $line =~ /^(\S.*)/ ) {
4906        if (! eval { delete_action($1); 1 }) {
4907            print {$OUT} $@;
4908            return;
4909        }
4910    }
4911
4912    # Swing and a miss. Bad syntax.
4913    else {
4914        print $OUT
4915          "Deleting an action requires a line number, or '*' for all\n" ; # hint
4916    }
4917} ## end sub cmd_A
4918
4919=head3 C<delete_action> (API)
4920
4921C<delete_action> accepts either a line number or C<undef>. If a line number
4922is specified, we check for the line being executable (if it's not, it
4923couldn't have had an  action). If it is, we just take the action off (this
4924will get any kind of an action, including breakpoints).
4925
4926=cut
4927
4928sub _remove_action_from_dbline {
4929    my $i = shift;
4930
4931    $dbline{$i} =~ s/\0[^\0]*//;    # \^a
4932    delete $dbline{$i} if $dbline{$i} eq '';
4933
4934    return;
4935}
4936
4937sub _delete_all_actions {
4938    print {$OUT} "Deleting all actions...\n";
4939
4940    for my $file ( keys %had_breakpoints ) {
4941        local *dbline = $main::{ '_<' . $file };
4942        $max = $#dbline;
4943        my $was;
4944        for my $i (1 .. $max) {
4945            if ( defined $dbline{$i} ) {
4946                _remove_action_from_dbline($i);
4947            }
4948        }
4949
4950        unless ( $had_breakpoints{$file} &= ~2 ) {
4951            delete $had_breakpoints{$file};
4952        }
4953    }
4954
4955    return;
4956}
4957
4958sub delete_action {
4959    my $i = shift;
4960
4961    if ( defined($i) ) {
4962        # Can there be one?
4963        die "Line $i has no action .\n" if $dbline[$i] == 0;
4964
4965        # Nuke whatever's there.
4966        _remove_action_from_dbline($i);
4967    }
4968    else {
4969        _delete_all_actions();
4970    }
4971}
4972
4973=head3 C<cmd_b> (command)
4974
4975Set breakpoints. Since breakpoints can be set in so many places, in so many
4976ways, conditionally or not, the breakpoint code is kind of complex. Mostly,
4977we try to parse the command type, and then shuttle it off to an appropriate
4978subroutine to actually do the work of setting the breakpoint in the right
4979place.
4980
4981=cut
4982
4983sub cmd_b {
4984    my $cmd    = shift;
4985    my $line   = shift;    # [.|line] [cond]
4986    my $dbline = shift;
4987
4988    my $default_cond = sub {
4989        my $cond = shift;
4990        return length($cond) ? $cond : '1';
4991    };
4992
4993    # Make . the current line number if it's there..
4994    $line =~ s/^\.(\s|\z)/$dbline$1/;
4995
4996    # No line number, no condition. Simple break on current line.
4997    if ( $line =~ /^\s*$/ ) {
4998        cmd_b_line( $dbline, 1 );
4999    }
5000
5001    # Break on load for a file.
5002    elsif ( my ($file) = $line =~ /^load\b\s*(.*)/ ) {
5003        $file =~ s/\s+\z//;
5004        cmd_b_load($file);
5005    }
5006
5007    # b compile|postpone <some sub> [<condition>]
5008    # The interpreter actually traps this one for us; we just put the
5009    # necessary condition in the %postponed hash.
5010    elsif ( my ($action, $subname, $cond)
5011        = $line =~ /^(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/ ) {
5012
5013        # De-Perl4-ify the name - ' separators to ::.
5014        $subname =~ s/'/::/g;
5015
5016        # Qualify it into the current package unless it's already qualified.
5017        $subname = "${package}::" . $subname unless $subname =~ /::/;
5018
5019        # Add main if it starts with ::.
5020        $subname = "main" . $subname if substr( $subname, 0, 2 ) eq "::";
5021
5022        # Save the break type for this sub.
5023        $postponed{$subname} = (($action eq 'postpone')
5024            ? ( "break +0 if " . $default_cond->($cond) )
5025            : "compile");
5026    } ## end elsif ($line =~ ...
5027    # b <filename>:<line> [<condition>]
5028    elsif (my ($filename, $line_num, $cond)
5029        = $line =~ /\A(\S+[^:]):(\d+)\s*(.*)/ms) {
5030        cmd_b_filename_line(
5031            $filename,
5032            $line_num,
5033            (length($cond) ? $cond : '1'),
5034        );
5035    }
5036    # b <sub name> [<condition>]
5037    elsif ( my ($new_subname, $new_cond) =
5038        $line =~ /^([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/ ) {
5039
5040        #
5041        $subname = $new_subname;
5042        cmd_b_sub( $subname, $default_cond->($new_cond) );
5043    }
5044
5045    # b <line> [<condition>].
5046    elsif ( my ($line_n, $cond) = $line =~ /^(\d*)\s*(.*)/ ) {
5047
5048        # Capture the line. If none, it's the current line.
5049        $line = $line_n || $dbline;
5050
5051        # Break on line.
5052        cmd_b_line( $line, $default_cond->($cond) );
5053    }
5054
5055    # Line didn't make sense.
5056    else {
5057        print "confused by line($line)?\n";
5058    }
5059
5060    return;
5061} ## end sub cmd_b
5062
5063=head3 C<break_on_load> (API)
5064
5065We want to break when this file is loaded. Mark this file in the
5066C<%break_on_load> hash, and note that it has a breakpoint in
5067C<%had_breakpoints>.
5068
5069=cut
5070
5071sub break_on_load {
5072    my $file = shift;
5073    $break_on_load{$file} = 1;
5074    $had_breakpoints{$file} |= 1;
5075}
5076
5077=head3 C<report_break_on_load> (API)
5078
5079Gives us an array of filenames that are set to break on load. Note that
5080only files with break-on-load are in here, so simply showing the keys
5081suffices.
5082
5083=cut
5084
5085sub report_break_on_load {
5086    sort keys %break_on_load;
5087}
5088
5089=head3 C<cmd_b_load> (command)
5090
5091We take the file passed in and try to find it in C<%INC> (which maps modules
5092to files they came from). We mark those files for break-on-load via
5093C<break_on_load> and then report that it was done.
5094
5095=cut
5096
5097sub cmd_b_load {
5098    my $file = shift;
5099    my @files;
5100
5101    # This is a block because that way we can use a redo inside it
5102    # even without there being any looping structure at all outside it.
5103    {
5104
5105        # Save short name and full path if found.
5106        push @files, $file;
5107        push @files, $::INC{$file} if $::INC{$file};
5108
5109        # Tack on .pm and do it again unless there was a '.' in the name
5110        # already.
5111        $file .= '.pm', redo unless $file =~ /\./;
5112    }
5113
5114    # Do the real work here.
5115    break_on_load($_) for @files;
5116
5117    # All the files that have break-on-load breakpoints.
5118    @files = report_break_on_load;
5119
5120    # Normalize for the purposes of our printing this.
5121    local $\ = '';
5122    local $" = ' ';
5123    print $OUT "Will stop on load of '@files'.\n";
5124} ## end sub cmd_b_load
5125
5126=head3 C<$filename_error> (API package global)
5127
5128Several of the functions we need to implement in the API need to work both
5129on the current file and on other files. We don't want to duplicate code, so
5130C<$filename_error> is used to contain the name of the file that's being
5131worked on (if it's not the current one).
5132
5133We can now build functions in pairs: the basic function works on the current
5134file, and uses C<$filename_error> as part of its error message. Since this is
5135initialized to C<"">, no filename will appear when we are working on the
5136current file.
5137
5138The second function is a wrapper which does the following:
5139
5140=over 4
5141
5142=item *
5143
5144Localizes C<$filename_error> and sets it to the name of the file to be processed.
5145
5146=item *
5147
5148Localizes the C<*dbline> glob and reassigns it to point to the file we want to process.
5149
5150=item *
5151
5152Calls the first function.
5153
5154The first function works on the I<current> file (i.e., the one we changed to),
5155and prints C<$filename_error> in the error message (the name of the other file)
5156if it needs to. When the functions return, C<*dbline> is restored to point
5157to the actual current file (the one we're executing in) and
5158C<$filename_error> is restored to C<"">. This restores everything to
5159the way it was before the second function was called at all.
5160
5161See the comments in L<S<C<sub breakable_line>>|/breakable_line(from, to) (API)>
5162and
5163L<S<C<sub breakable_line_in_filename>>|/breakable_line_in_filename(file, from, to) (API)>
5164for more details.
5165
5166=back
5167
5168=cut
5169
5170use vars qw($filename_error);
5171$filename_error = '';
5172
5173=head3 breakable_line(from, to) (API)
5174
5175The subroutine decides whether or not a line in the current file is breakable.
5176It walks through C<@dbline> within the range of lines specified, looking for
5177the first line that is breakable.
5178
5179If C<$to> is greater than C<$from>, the search moves forwards, finding the
5180first line I<after> C<$to> that's breakable, if there is one.
5181
5182If C<$from> is greater than C<$to>, the search goes I<backwards>, finding the
5183first line I<before> C<$to> that's breakable, if there is one.
5184
5185=cut
5186
5187sub breakable_line {
5188
5189    my ( $from, $to ) = @_;
5190
5191    # $i is the start point. (Where are the FORTRAN programs of yesteryear?)
5192    my $i = $from;
5193
5194    # If there are at least 2 arguments, we're trying to search a range.
5195    if ( @_ >= 2 ) {
5196
5197        # $delta is positive for a forward search, negative for a backward one.
5198        my $delta = $from < $to ? +1 : -1;
5199
5200        # Keep us from running off the ends of the file.
5201        my $limit = $delta > 0 ? $#dbline : 1;
5202
5203        # Clever test. If you're a mathematician, it's obvious why this
5204        # test works. If not:
5205        # If $delta is positive (going forward), $limit will be $#dbline.
5206        #    If $to is less than $limit, ($limit - $to) will be positive, times
5207        #    $delta of 1 (positive), so the result is > 0 and we should use $to
5208        #    as the stopping point.
5209        #
5210        #    If $to is greater than $limit, ($limit - $to) is negative,
5211        #    times $delta of 1 (positive), so the result is < 0 and we should
5212        #    use $limit ($#dbline) as the stopping point.
5213        #
5214        # If $delta is negative (going backward), $limit will be 1.
5215        #    If $to is zero, ($limit - $to) will be 1, times $delta of -1
5216        #    (negative) so the result is > 0, and we use $to as the stopping
5217        #    point.
5218        #
5219        #    If $to is less than zero, ($limit - $to) will be positive,
5220        #    times $delta of -1 (negative), so the result is not > 0, and
5221        #    we use $limit (1) as the stopping point.
5222        #
5223        #    If $to is 1, ($limit - $to) will zero, times $delta of -1
5224        #    (negative), still giving zero; the result is not > 0, and
5225        #    we use $limit (1) as the stopping point.
5226        #
5227        #    if $to is >1, ($limit - $to) will be negative, times $delta of -1
5228        #    (negative), giving a positive (>0) value, so we'll set $limit to
5229        #    $to.
5230
5231        $limit = $to if ( $limit - $to ) * $delta > 0;
5232
5233        # The real search loop.
5234        # $i starts at $from (the point we want to start searching from).
5235        # We move through @dbline in the appropriate direction (determined
5236        # by $delta: either -1 (back) or +1 (ahead).
5237        # We stay in as long as we haven't hit an executable line
5238        # ($dbline[$i] == 0 means not executable) and we haven't reached
5239        # the limit yet (test similar to the above).
5240        $i += $delta while $dbline[$i] == 0 and ( $limit - $i ) * $delta > 0;
5241
5242    } ## end if (@_ >= 2)
5243
5244    # If $i points to a line that is executable, return that.
5245    return $i unless $dbline[$i] == 0;
5246
5247    # Format the message and print it: no breakable lines in range.
5248    my ( $pl, $upto ) = ( '', '' );
5249    ( $pl, $upto ) = ( 's', "..$to" ) if @_ >= 2 and $from != $to;
5250
5251    # If there's a filename in filename_error, we'll see it.
5252    # If not, not.
5253    die "Line$pl $from$upto$filename_error not breakable\n";
5254} ## end sub breakable_line
5255
5256=head3 breakable_line_in_filename(file, from, to) (API)
5257
5258Like C<breakable_line>, but look in another file.
5259
5260=cut
5261
5262sub breakable_line_in_filename {
5263
5264    # Capture the file name.
5265    my ($f) = shift;
5266
5267    # Swap the magic line array over there temporarily.
5268    local *dbline = $main::{ '_<' . $f };
5269
5270    # If there's an error, it's in this other file.
5271    local $filename_error = " of '$f'";
5272
5273    # Find the breakable line.
5274    breakable_line(@_);
5275
5276    # *dbline and $filename_error get restored when this block ends.
5277
5278} ## end sub breakable_line_in_filename
5279
5280=head3 break_on_line(lineno, [condition]) (API)
5281
5282Adds a breakpoint with the specified condition (or 1 if no condition was
5283specified) to the specified line. Dies if it can't.
5284
5285=cut
5286
5287sub break_on_line {
5288    my $i = shift;
5289    my $cond = @_ ? shift(@_) : 1;
5290
5291    my $inii  = $i;
5292    my $after = '';
5293    my $pl    = '';
5294
5295    # Woops, not a breakable line. $filename_error allows us to say
5296    # if it was in a different file.
5297    die "Line $i$filename_error not breakable.\n" if $dbline[$i] == 0;
5298
5299    # Mark this file as having breakpoints in it.
5300    $had_breakpoints{$filename} |= 1;
5301
5302    # If there is an action or condition here already ...
5303    if ( $dbline{$i} ) {
5304
5305        # ... swap this condition for the existing one.
5306        $dbline{$i} =~ s/^[^\0]*/$cond/;
5307    }
5308    else {
5309
5310        # Nothing here - just add the condition.
5311        $dbline{$i} = $cond;
5312
5313        _set_breakpoint_enabled_status($filename, $i, 1);
5314    }
5315
5316    return;
5317} ## end sub break_on_line
5318
5319=head3 cmd_b_line(line, [condition]) (command)
5320
5321Wrapper for C<break_on_line>. Prints the failure message if it
5322doesn't work.
5323
5324=cut
5325
5326sub cmd_b_line {
5327    if (not eval { break_on_line(@_); 1 }) {
5328        local $\ = '';
5329        print $OUT $@ and return;
5330    }
5331
5332    return;
5333} ## end sub cmd_b_line
5334
5335=head3 cmd_b_filename_line(line, [condition]) (command)
5336
5337Wrapper for C<break_on_filename_line>. Prints the failure message if it
5338doesn't work.
5339
5340=cut
5341
5342sub cmd_b_filename_line {
5343    if (not eval { break_on_filename_line(@_); 1 }) {
5344        local $\ = '';
5345        print $OUT $@ and return;
5346    }
5347
5348    return;
5349}
5350
5351=head3 break_on_filename_line(file, line, [condition]) (API)
5352
5353Switches to the file specified and then calls C<break_on_line> to set
5354the breakpoint.
5355
5356=cut
5357
5358sub break_on_filename_line {
5359    my $f = shift;
5360    my $i = shift;
5361    my $cond = @_ ? shift(@_) : 1;
5362
5363    # Switch the magical hash temporarily.
5364    local *dbline = $main::{ '_<' . $f };
5365
5366    # Localize the variables that break_on_line uses to make its message.
5367    local $filename_error = " of '$f'";
5368    local $filename       = $f;
5369
5370    # Add the breakpoint.
5371    break_on_line( $i, $cond );
5372
5373    return;
5374} ## end sub break_on_filename_line
5375
5376=head3 break_on_filename_line_range(file, from, to, [condition]) (API)
5377
5378Switch to another file, search the range of lines specified for an
5379executable one, and put a breakpoint on the first one you find.
5380
5381=cut
5382
5383sub break_on_filename_line_range {
5384    my $f = shift;
5385    my $from = shift;
5386    my $to = shift;
5387    my $cond = @_ ? shift(@_) : 1;
5388
5389    # Find a breakable line if there is one.
5390    my $i = breakable_line_in_filename( $f, $from, $to );
5391
5392    # Add the breakpoint.
5393    break_on_filename_line( $f, $i, $cond );
5394
5395    return;
5396} ## end sub break_on_filename_line_range
5397
5398=head3 subroutine_filename_lines(subname, [condition]) (API)
5399
5400Search for a subroutine within a given file. The condition is ignored.
5401Uses C<find_sub> to locate the desired subroutine.
5402
5403=cut
5404
5405sub subroutine_filename_lines {
5406    my ( $subname ) = @_;
5407
5408    # Returned value from find_sub() is fullpathname:startline-endline.
5409    # The match creates the list (fullpathname, start, end).
5410    return (find_sub($subname) =~ /^(.*):(\d+)-(\d+)$/);
5411} ## end sub subroutine_filename_lines
5412
5413=head3 break_subroutine(subname) (API)
5414
5415Places a break on the first line possible in the specified subroutine. Uses
5416C<subroutine_filename_lines> to find the subroutine, and
5417C<break_on_filename_line_range> to place the break.
5418
5419=cut
5420
5421sub break_subroutine {
5422    my $subname = shift;
5423
5424    # Get filename, start, and end.
5425    my ( $file, $s, $e ) = subroutine_filename_lines($subname)
5426      or die "Subroutine $subname not found.\n";
5427
5428
5429    # Null condition changes to '1' (always true).
5430    my $cond = @_ ? shift(@_) : 1;
5431
5432    # Put a break the first place possible in the range of lines
5433    # that make up this subroutine.
5434    break_on_filename_line_range( $file, $s, $e, $cond );
5435
5436    return;
5437} ## end sub break_subroutine
5438
5439=head3 cmd_b_sub(subname, [condition]) (command)
5440
5441We take the incoming subroutine name and fully-qualify it as best we can.
5442
5443=over 4
5444
5445=item 1. If it's already fully-qualified, leave it alone.
5446
5447=item 2. Try putting it in the current package.
5448
5449=item 3. If it's not there, try putting it in CORE::GLOBAL if it exists there.
5450
5451=item 4. If it starts with '::', put it in 'main::'.
5452
5453=back
5454
5455After all this cleanup, we call C<break_subroutine> to try to set the
5456breakpoint.
5457
5458=cut
5459
5460sub cmd_b_sub {
5461    my $subname = shift;
5462    my $cond = @_ ? shift : 1;
5463
5464    # If the subname isn't a code reference, qualify it so that
5465    # break_subroutine() will work right.
5466    if ( ref($subname) ne 'CODE' ) {
5467
5468        # Not Perl 4.
5469        $subname =~ s/'/::/g;
5470        my $s = $subname;
5471
5472        # Put it in this package unless it's already qualified.
5473        if ($subname !~ /::/)
5474        {
5475            $subname = $package . '::' . $subname;
5476        };
5477
5478        # Requalify it into CORE::GLOBAL if qualifying it into this
5479        # package resulted in its not being defined, but only do so
5480        # if it really is in CORE::GLOBAL.
5481        my $core_name = "CORE::GLOBAL::$s";
5482        if ((!defined(&$subname))
5483                and ($s !~ /::/)
5484                and (defined &{$core_name}))
5485        {
5486            $subname = $core_name;
5487        }
5488
5489        # Put it in package 'main' if it has a leading ::.
5490        if ($subname =~ /\A::/)
5491        {
5492            $subname = "main" . $subname;
5493        }
5494    } ## end if ( ref($subname) ne 'CODE' ) {
5495
5496    # Try to set the breakpoint.
5497    if (not eval { break_subroutine( $subname, $cond ); 1 }) {
5498        local $\ = '';
5499        print {$OUT} $@;
5500        return;
5501    }
5502
5503    return;
5504} ## end sub cmd_b_sub
5505
5506=head3 C<cmd_B> - delete breakpoint(s) (command)
5507
5508The command mostly parses the command line and tries to turn the argument
5509into a line spec. If it can't, it uses the current line. It then calls
5510C<delete_breakpoint> to actually do the work.
5511
5512If C<*> is  specified, C<cmd_B> calls C<delete_breakpoint> with no arguments,
5513thereby deleting all the breakpoints.
5514
5515=cut
5516
5517sub cmd_B {
5518    my $cmd = shift;
5519
5520    # No line spec? Use dbline.
5521    # If there is one, use it if it's non-zero, or wipe it out if it is.
5522    my $line   = ( $_[0] =~ /\A\./ ) ? $dbline : (shift || '');
5523    my $dbline = shift;
5524
5525    # If the line was dot, make the line the current one.
5526    $line =~ s/^\./$dbline/;
5527
5528    # If it's * we're deleting all the breakpoints.
5529    if ( $line eq '*' ) {
5530        if (not eval { delete_breakpoint(); 1 }) {
5531            print {$OUT} $@;
5532        }
5533    }
5534
5535    # If there is a line spec, delete the breakpoint on that line.
5536    elsif ( $line =~ /\A(\S.*)/ ) {
5537        if (not eval { delete_breakpoint( $line || $dbline ); 1 }) {
5538            local $\ = '';
5539            print {$OUT} $@;
5540        }
5541    } ## end elsif ($line =~ /^(\S.*)/)
5542
5543    # No line spec.
5544    else {
5545        print {$OUT}
5546          "Deleting a breakpoint requires a line number, or '*' for all\n"
5547          ;    # hint
5548    }
5549
5550    return;
5551} ## end sub cmd_B
5552
5553=head3 delete_breakpoint([line]) (API)
5554
5555This actually does the work of deleting either a single breakpoint, or all
5556of them.
5557
5558For a single line, we look for it in C<@dbline>. If it's nonbreakable, we
5559just drop out with a message saying so. If it is, we remove the condition
5560part of the 'condition\0action' that says there's a breakpoint here. If,
5561after we've done that, there's nothing left, we delete the corresponding
5562line in C<%dbline> to signal that no action needs to be taken for this line.
5563
5564For all breakpoints, we iterate through the keys of C<%had_breakpoints>,
5565which lists all currently-loaded files which have breakpoints. We then look
5566at each line in each of these files, temporarily switching the C<%dbline>
5567and C<@dbline> structures to point to the files in question, and do what
5568we did in the single line case: delete the condition in C<@dbline>, and
5569delete the key in C<%dbline> if nothing's left.
5570
5571We then wholesale delete C<%postponed>, C<%postponed_file>, and
5572C<%break_on_load>, because these structures contain breakpoints for files
5573and code that haven't been loaded yet. We can just kill these off because there
5574are no magical debugger structures associated with them.
5575
5576=cut
5577
5578sub _remove_breakpoint_entry {
5579    my ($fn, $i) = @_;
5580
5581    delete $dbline{$i};
5582    _delete_breakpoint_data_ref($fn, $i);
5583
5584    return;
5585}
5586
5587sub _delete_all_breakpoints {
5588    print {$OUT} "Deleting all breakpoints...\n";
5589
5590    # %had_breakpoints lists every file that had at least one
5591    # breakpoint in it.
5592    for my $fn ( keys %had_breakpoints ) {
5593
5594        # Switch to the desired file temporarily.
5595        local *dbline = $main::{ '_<' . $fn };
5596
5597        $max = $#dbline;
5598
5599        # For all lines in this file ...
5600        for my $i (1 .. $max) {
5601
5602            # If there's a breakpoint or action on this line ...
5603            if ( defined $dbline{$i} ) {
5604
5605                # ... remove the breakpoint.
5606                $dbline{$i} =~ s/\A[^\0]+//;
5607                if ( $dbline{$i} =~ s/\A\0?\z// ) {
5608                    # Remove the entry altogether if no action is there.
5609                    _remove_breakpoint_entry($fn, $i);
5610                }
5611            } ## end if (defined $dbline{$i...
5612        } ## end for $i (1 .. $max)
5613
5614        # If, after we turn off the "there were breakpoints in this file"
5615        # bit, the entry in %had_breakpoints for this file is zero,
5616        # we should remove this file from the hash.
5617        if ( not $had_breakpoints{$fn} &= (~1) ) {
5618            delete $had_breakpoints{$fn};
5619        }
5620    } ## end for my $fn (keys %had_breakpoints)
5621
5622    # Kill off all the other breakpoints that are waiting for files that
5623    # haven't been loaded yet.
5624    undef %postponed;
5625    undef %postponed_file;
5626    undef %break_on_load;
5627
5628    return;
5629}
5630
5631sub _delete_breakpoint_from_line {
5632    my ($i) = @_;
5633
5634    # Woops. This line wasn't breakable at all.
5635    die "Line $i not breakable.\n" if $dbline[$i] == 0;
5636
5637    # Kill the condition, but leave any action.
5638    $dbline{$i} =~ s/\A[^\0]*//;
5639
5640    # Remove the entry entirely if there's no action left.
5641    if ($dbline{$i} eq '') {
5642        _remove_breakpoint_entry($filename, $i);
5643    }
5644
5645    return;
5646}
5647
5648sub delete_breakpoint {
5649    my $i = shift;
5650
5651    # If we got a line, delete just that one.
5652    if ( defined($i) ) {
5653        _delete_breakpoint_from_line($i);
5654    }
5655    # No line; delete them all.
5656    else {
5657        _delete_all_breakpoints();
5658    }
5659
5660    return;
5661}
5662
5663=head3 cmd_stop (command)
5664
5665This is meant to be part of the new command API, but it isn't called or used
5666anywhere else in the debugger. XXX It is probably meant for use in development
5667of new commands.
5668
5669=cut
5670
5671sub cmd_stop {    # As on ^C, but not signal-safy.
5672    $signal = 1;
5673}
5674
5675=head3 C<cmd_e> - threads
5676
5677Display the current thread id:
5678
5679    e
5680
5681This could be how (when implemented) to send commands to this thread id (e cmd)
5682or that thread id (e tid cmd).
5683
5684=cut
5685
5686sub cmd_e {
5687    my $cmd  = shift;
5688    my $line = shift;
5689    unless (exists($INC{'threads.pm'})) {
5690        print "threads not loaded($ENV{PERL5DB_THREADED})
5691        please run the debugger with PERL5DB_THREADED=1 set in the environment\n";
5692    } else {
5693        my $tid = threads->tid;
5694        print "thread id: $tid\n";
5695    }
5696} ## end sub cmd_e
5697
5698=head3 C<cmd_E> - list of thread ids
5699
5700Display the list of available thread ids:
5701
5702    E
5703
5704This could be used (when implemented) to send commands to all threads (E cmd).
5705
5706=cut
5707
5708sub cmd_E {
5709    my $cmd  = shift;
5710    my $line = shift;
5711    unless (exists($INC{'threads.pm'})) {
5712        print "threads not loaded($ENV{PERL5DB_THREADED})
5713        please run the debugger with PERL5DB_THREADED=1 set in the environment\n";
5714    } else {
5715        my $tid = threads->tid;
5716        print "thread ids: ".join(', ',
5717            map { ($tid == $_->tid ? '<'.$_->tid.'>' : $_->tid) } threads->list
5718        )."\n";
5719    }
5720} ## end sub cmd_E
5721
5722=head3 C<cmd_h> - help command (command)
5723
5724Does the work of either
5725
5726=over 4
5727
5728=item *
5729
5730Showing all the debugger help
5731
5732=item *
5733
5734Showing help for a specific command
5735
5736=back
5737
5738=cut
5739
5740use vars qw($help);
5741use vars qw($summary);
5742
5743sub cmd_h {
5744    my $cmd = shift;
5745
5746    # If we have no operand, assume null.
5747    my $line = shift || '';
5748
5749    # 'h h'. Print the long-format help.
5750    if ( $line =~ /\Ah\s*\z/ ) {
5751        print_help($help);
5752    }
5753
5754    # 'h <something>'. Search for the command and print only its help.
5755    elsif ( my ($asked) = $line =~ /\A(\S.*)\z/ ) {
5756
5757        # support long commands; otherwise bogus errors
5758        # happen when you ask for h on <CR> for example
5759        my $qasked = quotemeta($asked);    # for searching; we don't
5760                                           # want to use it as a pattern.
5761                                           # XXX: finds CR but not <CR>
5762
5763        # Search the help string for the command.
5764        if (
5765            $help =~ /^                    # Start of a line
5766                      <?                   # Optional '<'
5767                      (?:[IB]<)            # Optional markup
5768                      $qasked              # The requested command
5769                     /mx
5770          )
5771        {
5772
5773            # It's there; pull it out and print it.
5774            while (
5775                $help =~ /^
5776                              (<?            # Optional '<'
5777                                 (?:[IB]<)   # Optional markup
5778                                 $qasked     # The command
5779                                 ([\s\S]*?)  # Description line(s)
5780                              \n)            # End of last description line
5781                              (?!\s)         # Next line not starting with
5782                                             # whitespace
5783                             /mgx
5784              )
5785            {
5786                print_help($1);
5787            }
5788        }
5789
5790        # Not found; not a debugger command.
5791        else {
5792            print_help("B<$asked> is not a debugger command.\n");
5793        }
5794    } ## end elsif ($line =~ /^(\S.*)$/)
5795
5796    # 'h' - print the summary help.
5797    else {
5798        print_help($summary);
5799    }
5800} ## end sub cmd_h
5801
5802=head3 C<cmd_L> - list breakpoints, actions, and watch expressions (command)
5803
5804To list breakpoints, the command has to look determine where all of them are
5805first. It starts a C<%had_breakpoints>, which tells us what all files have
5806breakpoints and/or actions. For each file, we switch the C<*dbline> glob (the
5807magic source and breakpoint data structures) to the file, and then look
5808through C<%dbline> for lines with breakpoints and/or actions, listing them
5809out. We look through C<%postponed> not-yet-compiled subroutines that have
5810breakpoints, and through C<%postponed_file> for not-yet-C<require>'d files
5811that have breakpoints.
5812
5813Watchpoints are simpler: we just list the entries in C<@to_watch>.
5814
5815=cut
5816
5817sub _cmd_L_calc_arg {
5818    # If no argument, list everything. Pre-5.8.0 version always lists
5819    # everything
5820    my $arg = shift || 'abw';
5821    if ($CommandSet ne '580')
5822    {
5823        $arg = 'abw';
5824    }
5825
5826    return $arg;
5827}
5828
5829sub _cmd_L_calc_wanted_flags {
5830    my $arg = _cmd_L_calc_arg(shift);
5831
5832    return (map { index($arg, $_) >= 0 ? 1 : 0 } qw(a b w));
5833}
5834
5835
5836sub _cmd_L_handle_breakpoints {
5837    my ($handle_db_line) = @_;
5838
5839    BREAKPOINTS_SCAN:
5840    # Look in all the files with breakpoints...
5841    for my $file ( keys %had_breakpoints ) {
5842
5843        # Temporary switch to this file.
5844        local *dbline = $main::{ '_<' . $file };
5845
5846        # Set up to look through the whole file.
5847        $max = $#dbline;
5848        my $was;    # Flag: did we print something
5849        # in this file?
5850
5851        # For each line in the file ...
5852        for my $i (1 .. $max) {
5853
5854            # We've got something on this line.
5855            if ( defined $dbline{$i} ) {
5856
5857                # Print the header if we haven't.
5858                if (not $was++) {
5859                    print {$OUT} "$file:\n";
5860                }
5861
5862                # Print the line.
5863                print {$OUT} " $i:\t", $dbline[$i];
5864
5865                $handle_db_line->($dbline{$i});
5866
5867                # Quit if the user hit interrupt.
5868                if ($signal) {
5869                    last BREAKPOINTS_SCAN;
5870                }
5871            } ## end if (defined $dbline{$i...
5872        } ## end for my $i (1 .. $max)
5873    } ## end for my $file (keys %had_breakpoints)
5874
5875    return;
5876}
5877
5878sub _cmd_L_handle_postponed_breakpoints {
5879    my ($handle_db_line) = @_;
5880
5881    print {$OUT} "Postponed breakpoints in files:\n";
5882
5883    POSTPONED_SCANS:
5884    for my $file ( keys %postponed_file ) {
5885        my $db = $postponed_file{$file};
5886        print {$OUT} " $file:\n";
5887        for my $line ( sort { $a <=> $b } keys %$db ) {
5888            print {$OUT} "  $line:\n";
5889
5890            $handle_db_line->($db->{$line});
5891
5892            if ($signal) {
5893                last POSTPONED_SCANS;
5894            }
5895        }
5896        if ($signal) {
5897            last POSTPONED_SCANS;
5898        }
5899    }
5900
5901    return;
5902}
5903
5904
5905sub cmd_L {
5906    my $cmd = shift;
5907
5908    my ($action_wanted, $break_wanted, $watch_wanted) =
5909        _cmd_L_calc_wanted_flags(shift);
5910
5911    my $handle_db_line = sub {
5912        my ($l) = @_;
5913
5914        my ( $stop, $action ) = split( /\0/, $l );
5915
5916        if ($stop and $break_wanted) {
5917            print {$OUT} "    break if (", $stop, ")\n"
5918        }
5919
5920        if ($action && $action_wanted) {
5921            print {$OUT} "    action:  ", $action, "\n"
5922        }
5923
5924        return;
5925    };
5926
5927    # Breaks and actions are found together, so we look in the same place
5928    # for both.
5929    if ( $break_wanted or $action_wanted ) {
5930        _cmd_L_handle_breakpoints($handle_db_line);
5931    }
5932
5933    # Look for breaks in not-yet-compiled subs:
5934    if ( %postponed and $break_wanted ) {
5935        print {$OUT} "Postponed breakpoints in subroutines:\n";
5936        my $subname;
5937        SUBS_SCAN:
5938        for $subname ( keys %postponed ) {
5939            print {$OUT} " $subname\t$postponed{$subname}\n";
5940            if ($signal) {
5941                last SUBS_SCAN;
5942            }
5943        }
5944    } ## end if (%postponed and $break_wanted)
5945
5946    # Find files that have not-yet-loaded breaks:
5947    my @have = map {    # Combined keys
5948        keys %{ $postponed_file{$_} }
5949    } keys %postponed_file;
5950
5951    # If there are any, list them.
5952    if ( @have and ( $break_wanted or $action_wanted ) ) {
5953        _cmd_L_handle_postponed_breakpoints($handle_db_line);
5954    } ## end if (@have and ($break_wanted...
5955
5956    if ( %break_on_load and $break_wanted ) {
5957        print {$OUT} "Breakpoints on load:\n";
5958        BREAK_ON_LOAD: for my $filename ( keys %break_on_load ) {
5959            print {$OUT} " $filename\n";
5960            last BREAK_ON_LOAD if $signal;
5961        }
5962    } ## end if (%break_on_load and...
5963
5964    if ($watch_wanted and ( $trace & 2 )) {
5965        print {$OUT} "Watch-expressions:\n" if @to_watch;
5966        TO_WATCH: for my $expr (@to_watch) {
5967            print {$OUT} " $expr\n";
5968            last TO_WATCH if $signal;
5969        }
5970    }
5971
5972    return;
5973} ## end sub cmd_L
5974
5975=head3 C<cmd_M> - list modules (command)
5976
5977Just call C<list_modules>.
5978
5979=cut
5980
5981sub cmd_M {
5982    list_modules();
5983
5984    return;
5985}
5986
5987=head3 C<cmd_o> - options (command)
5988
5989If this is just C<o> by itself, we list the current settings via
5990C<dump_option>. If there's a nonblank value following it, we pass that on to
5991C<parse_options> for processing.
5992
5993=cut
5994
5995sub cmd_o {
5996    my $cmd = shift;
5997    my $opt = shift || '';    # opt[=val]
5998
5999    # Nonblank. Try to parse and process.
6000    if ( $opt =~ /^(\S.*)/ ) {
6001        parse_options($1);
6002    }
6003
6004    # Blank. List the current option settings.
6005    else {
6006        for (@options) {
6007            dump_option($_);
6008        }
6009    }
6010} ## end sub cmd_o
6011
6012=head3 C<cmd_O> - nonexistent in 5.8.x (command)
6013
6014Advises the user that the O command has been renamed.
6015
6016=cut
6017
6018sub cmd_O {
6019    print $OUT "The old O command is now the o command.\n";             # hint
6020    print $OUT "Use 'h' to get current command help synopsis or\n";     #
6021    print $OUT "use 'o CommandSet=pre580' to revert to old usage\n";    #
6022}
6023
6024=head3 C<cmd_v> - view window (command)
6025
6026Uses the C<$preview> variable set in the second C<BEGIN> block (q.v.) to
6027move back a few lines to list the selected line in context. Uses C<_cmd_l_main>
6028to do the actual listing after figuring out the range of line to request.
6029
6030=cut
6031
6032use vars qw($preview);
6033
6034sub cmd_v {
6035    my $cmd  = shift;
6036    my $line = shift;
6037
6038    # Extract the line to list around. (Astute readers will have noted that
6039    # this pattern will match whether or not a numeric line is specified,
6040    # which means that we'll always enter this loop (though a non-numeric
6041    # argument results in no action at all)).
6042    if ( $line =~ /^(\d*)$/ ) {
6043
6044        # Total number of lines to list (a windowful).
6045        $incr = $window - 1;
6046
6047        # Set the start to the argument given (if there was one).
6048        $start = $1 if $1;
6049
6050        # Back up by the context amount.
6051        $start -= $preview;
6052
6053        # Put together a linespec that _cmd_l_main will like.
6054        $line = $start . '-' . ( $start + $incr );
6055
6056        # List the lines.
6057        _cmd_l_main( $line );
6058    } ## end if ($line =~ /^(\d*)$/)
6059} ## end sub cmd_v
6060
6061=head3 C<cmd_w> - add a watch expression (command)
6062
6063The 5.8 version of this command adds a watch expression if one is specified;
6064it does nothing if entered with no operands.
6065
6066We extract the expression, save it, evaluate it in the user's context, and
6067save the value. We'll re-evaluate it each time the debugger passes a line,
6068and will stop (see the code at the top of the command loop) if the value
6069of any of the expressions changes.
6070
6071=cut
6072
6073sub _add_watch_expr {
6074    my $expr = shift;
6075
6076    # ... save it.
6077    push @to_watch, $expr;
6078
6079    # Parameterize DB::eval and call it to get the expression's value
6080    # in the user's context. This version can handle expressions which
6081    # return a list value.
6082    $evalarg = $expr;
6083    # The &-call is here to ascertain the mutability of @_.
6084    my ($val) = join( ' ', &DB::eval);
6085    $val = ( defined $val ) ? "'$val'" : 'undef';
6086
6087    # Save the current value of the expression.
6088    push @old_watch, $val;
6089
6090    # We are now watching expressions.
6091    $trace |= 2;
6092
6093    return;
6094}
6095
6096sub cmd_w {
6097    my $cmd = shift;
6098
6099    # Null expression if no arguments.
6100    my $expr = shift || '';
6101
6102    # If expression is not null ...
6103    if ( $expr =~ /\A\S/ ) {
6104        _add_watch_expr($expr);
6105    } ## end if ($expr =~ /^(\S.*)/)
6106
6107    # You have to give one to get one.
6108    else {
6109        print $OUT "Adding a watch-expression requires an expression\n";  # hint
6110    }
6111
6112    return;
6113}
6114
6115=head3 C<cmd_W> - delete watch expressions (command)
6116
6117This command accepts either a watch expression to be removed from the list
6118of watch expressions, or C<*> to delete them all.
6119
6120If C<*> is specified, we simply empty the watch expression list and the
6121watch expression value list. We also turn off the bit that says we've got
6122watch expressions.
6123
6124If an expression (or partial expression) is specified, we pattern-match
6125through the expressions and remove the ones that match. We also discard
6126the corresponding values. If no watch expressions are left, we turn off
6127the I<watching expressions> bit.
6128
6129=cut
6130
6131sub cmd_W {
6132    my $cmd  = shift;
6133    my $expr = shift || '';
6134
6135    # Delete them all.
6136    if ( $expr eq '*' ) {
6137
6138        # Not watching now.
6139        $trace &= ~2;
6140
6141        print $OUT "Deleting all watch expressions ...\n";
6142
6143        # And all gone.
6144        @to_watch = @old_watch = ();
6145    }
6146
6147    # Delete one of them.
6148    elsif ( $expr =~ /^(\S.*)/ ) {
6149
6150        # Where we are in the list.
6151        my $i_cnt = 0;
6152
6153        # For each expression ...
6154        foreach (@to_watch) {
6155            my $val = $to_watch[$i_cnt];
6156
6157            # Does this one match the command argument?
6158            if ( $val eq $expr ) {    # =~ m/^\Q$i$/) {
6159                                      # Yes. Turn it off, and its value too.
6160                splice( @to_watch,  $i_cnt, 1 );
6161                splice( @old_watch, $i_cnt, 1 );
6162            }
6163            $i_cnt++;
6164        } ## end foreach (@to_watch)
6165
6166        # We don't bother to turn watching off because
6167        #  a) we don't want to stop calling watchfunction() if it exists
6168        #  b) foreach over a null list doesn't do anything anyway
6169
6170    } ## end elsif ($expr =~ /^(\S.*)/)
6171
6172    # No command arguments entered.
6173    else {
6174        print $OUT
6175          "Deleting a watch-expression requires an expression, or '*' for all\n"
6176          ;    # hint
6177    }
6178} ## end sub cmd_W
6179
6180### END of the API section
6181
6182=head1 SUPPORT ROUTINES
6183
6184These are general support routines that are used in a number of places
6185throughout the debugger.
6186
6187=head2 save
6188
6189save() saves the user's versions of globals that would mess us up in C<@saved>,
6190and installs the versions we like better.
6191
6192=cut
6193
6194sub save {
6195
6196    # Save eval failure, command failure, extended OS error, output field
6197    # separator, input record separator, output record separator and
6198    # the warning setting.
6199    @saved = ( $@, $!, $^E, $,, $/, $\, $^W );
6200
6201    $,  = "";      # output field separator is null string
6202    $/  = "\n";    # input record separator is newline
6203    $\  = "";      # output record separator is null string
6204    $^W = 0;       # warnings are off
6205} ## end sub save
6206
6207=head2 C<print_lineinfo> - show where we are now
6208
6209print_lineinfo prints whatever it is that it is handed; it prints it to the
6210C<$LINEINFO> filehandle instead of just printing it to STDOUT. This allows
6211us to feed line information to a client editor without messing up the
6212debugger output.
6213
6214=cut
6215
6216sub print_lineinfo {
6217
6218    # Make the terminal sensible if we're not the primary debugger.
6219    resetterm(1) if $LINEINFO eq $OUT and $term_pid != $$;
6220    local $\ = '';
6221    local $, = '';
6222    # $LINEINFO may be undef if $noTTY is set or some other issue.
6223    if ($LINEINFO)
6224    {
6225        print {$LINEINFO} @_;
6226    }
6227} ## end sub print_lineinfo
6228
6229=head2 C<postponed_sub>
6230
6231Handles setting postponed breakpoints in subroutines once they're compiled.
6232For breakpoints, we use C<DB::find_sub> to locate the source file and line
6233range for the subroutine, then mark the file as having a breakpoint,
6234temporarily switch the C<*dbline> glob over to the source file, and then
6235search the given range of lines to find a breakable line. If we find one,
6236we set the breakpoint on it, deleting the breakpoint from C<%postponed>.
6237
6238=cut
6239
6240# The following takes its argument via $evalarg to preserve current @_
6241
6242sub postponed_sub {
6243
6244    # Get the subroutine name.
6245    my $subname = shift;
6246
6247    # If this is a 'break +<n> if <condition>' ...
6248    if ( $postponed{$subname} =~ s/^break\s([+-]?\d+)\s+if\s// ) {
6249
6250        # If there's no offset, use '+0'.
6251        my $offset = $1 || 0;
6252
6253        # find_sub's value is 'fullpath-filename:start-stop'. It's
6254        # possible that the filename might have colons in it too.
6255        my ( $file, $i ) = ( find_sub($subname) =~ /^(.*):(\d+)-.*$/ );
6256        if ($i) {
6257
6258            # We got the start line. Add the offset '+<n>' from
6259            # $postponed{subname}.
6260            $i += $offset;
6261
6262            # Switch to the file this sub is in, temporarily.
6263            local *dbline = $main::{ '_<' . $file };
6264
6265            # No warnings, please.
6266            local $^W = 0;    # != 0 is magical below
6267
6268            # This file's got a breakpoint in it.
6269            $had_breakpoints{$file} |= 1;
6270
6271            # Last line in file.
6272            $max = $#dbline;
6273
6274            # Search forward until we hit a breakable line or get to
6275            # the end of the file.
6276            ++$i until $dbline[$i] != 0 or $i >= $max;
6277
6278            # Copy the breakpoint in and delete it from %postponed.
6279            $dbline{$i} = delete $postponed{$subname};
6280        } ## end if ($i)
6281
6282        # find_sub didn't find the sub.
6283        else {
6284            local $\ = '';
6285            print $OUT "Subroutine $subname not found.\n";
6286        }
6287        return;
6288    } ## end if ($postponed{$subname...
6289    elsif ( $postponed{$subname} eq 'compile' ) { $signal = 1 }
6290
6291    #print $OUT "In postponed_sub for '$subname'.\n";
6292} ## end sub postponed_sub
6293
6294=head2 C<postponed>
6295
6296Called after each required file is compiled, but before it is executed;
6297also called if the name of a just-compiled subroutine is a key of
6298C<%postponed>. Propagates saved breakpoints (from S<C<b compile>>,
6299S<C<b load>>, etc.) into the just-compiled code.
6300
6301If this is a C<require>'d file, the incoming parameter is the glob
6302C<*{"_<$filename"}>, with C<$filename> the name of the C<require>'d file.
6303
6304If it's a subroutine, the incoming parameter is the subroutine name.
6305
6306=cut
6307
6308sub postponed {
6309
6310    # If there's a break, process it.
6311    if ($ImmediateStop) {
6312
6313        # Right, we've stopped. Turn it off.
6314        $ImmediateStop = 0;
6315
6316        # Enter the command loop when DB::DB gets called.
6317        $signal = 1;
6318    }
6319
6320    # If this is a subroutine, let postponed_sub() deal with it.
6321    if (ref(\$_[0]) ne 'GLOB') {
6322        return postponed_sub(@_);
6323    }
6324
6325    # Not a subroutine. Deal with the file.
6326    local *dbline = shift;
6327    my $filename = $dbline;
6328    $filename =~ s/^_<//;
6329    local $\ = '';
6330    $signal = 1, print $OUT "'$filename' loaded...\n"
6331      if $break_on_load{$filename};
6332    print_lineinfo( ' ' x $stack_depth, "Package $filename.\n" ) if $frame;
6333
6334    # Do we have any breakpoints to put in this file?
6335    return unless $postponed_file{$filename};
6336
6337    # Yes. Mark this file as having breakpoints.
6338    $had_breakpoints{$filename} |= 1;
6339
6340    # "Cannot be done: insufficient magic" - we can't just put the
6341    # breakpoints saved in %postponed_file into %dbline by assigning
6342    # the whole hash; we have to do it one item at a time for the
6343    # breakpoints to be set properly.
6344    #%dbline = %{$postponed_file{$filename}};
6345
6346    # Set the breakpoints, one at a time.
6347    my $key;
6348
6349    for $key ( keys %{ $postponed_file{$filename} } ) {
6350
6351        # Stash the saved breakpoint into the current file's magic line array.
6352        $dbline{$key} = ${ $postponed_file{$filename} }{$key};
6353    }
6354
6355    # This file's been compiled; discard the stored breakpoints.
6356    delete $postponed_file{$filename};
6357
6358} ## end sub postponed
6359
6360=head2 C<dumpit>
6361
6362C<dumpit> is the debugger's wrapper around dumpvar.pl.
6363
6364It gets a filehandle (to which C<dumpvar.pl>'s output will be directed) and
6365a reference to a variable (the thing to be dumped) as its input.
6366
6367The incoming filehandle is selected for output (C<dumpvar.pl> is printing to
6368the currently-selected filehandle, thank you very much). The current
6369values of the package globals C<$single> and C<$trace> are backed up in
6370lexicals, and they are turned off (this keeps the debugger from trying
6371to single-step through C<dumpvar.pl> (I think.)). C<$frame> is localized to
6372preserve its current value and it is set to zero to prevent entry/exit
6373messages from printing, and C<$doret> is localized as well and set to -2 to
6374prevent return values from being shown.
6375
6376C<dumpit()> then checks to see if it needs to load C<dumpvar.pl> and
6377tries to load it (note: if you have a C<dumpvar.pl>  ahead of the
6378installed version in C<@INC>, yours will be used instead. Possible security
6379problem?).
6380
6381It then checks to see if the subroutine C<main::dumpValue> is now defined
6382it should have been defined by C<dumpvar.pl>). If it has, C<dumpit()>
6383localizes the globals necessary for things to be sane when C<main::dumpValue()>
6384is called, and picks up the variable to be dumped from the parameter list.
6385
6386It checks the package global C<%options> to see if there's a C<dumpDepth>
6387specified. If not, -1 is assumed; if so, the supplied value gets passed on to
6388C<dumpvar.pl>. This tells C<dumpvar.pl> where to leave off when dumping a
6389structure: -1 means dump everything.
6390
6391C<dumpValue()> is then called if possible; if not, C<dumpit()>just prints a
6392warning.
6393
6394In either case, C<$single>, C<$trace>, C<$frame>, and C<$doret> are restored
6395and we then return to the caller.
6396
6397=cut
6398
6399sub dumpit {
6400
6401    # Save the current output filehandle and switch to the one
6402    # passed in as the first parameter.
6403    my $savout = select(shift);
6404
6405    # Save current settings of $single and $trace, and then turn them off.
6406    my $osingle = $single;
6407    my $otrace  = $trace;
6408    $single = $trace = 0;
6409
6410    # XXX Okay, what do $frame and $doret do, again?
6411    local $frame = 0;
6412    local $doret = -2;
6413
6414    # Load dumpvar.pl unless we've already got the sub we need from it.
6415    unless ( defined &main::dumpValue ) {
6416        do 'dumpvar.pl' or die $@;
6417    }
6418
6419    # If the load succeeded (or we already had dumpvalue()), go ahead
6420    # and dump things.
6421    if ( defined &main::dumpValue ) {
6422        local $\ = '';
6423        local $, = '';
6424        local $" = ' ';
6425        my $v = shift;
6426        my $maxdepth = shift || $option{dumpDepth};
6427        $maxdepth = -1 unless defined $maxdepth;    # -1 means infinite depth
6428        main::dumpValue( $v, $maxdepth );
6429    } ## end if (defined &main::dumpValue)
6430
6431    # Oops, couldn't load dumpvar.pl.
6432    else {
6433        local $\ = '';
6434        print $OUT "dumpvar.pl not available.\n";
6435    }
6436
6437    # Reset $single and $trace to their old values.
6438    $single = $osingle;
6439    $trace  = $otrace;
6440
6441    # Restore the old filehandle.
6442    select($savout);
6443} ## end sub dumpit
6444
6445=head2 C<print_trace>
6446
6447C<print_trace>'s job is to print a stack trace. It does this via the
6448C<dump_trace> routine, which actually does all the ferreting-out of the
6449stack trace data. C<print_trace> takes care of formatting it nicely and
6450printing it to the proper filehandle.
6451
6452Parameters:
6453
6454=over 4
6455
6456=item *
6457
6458The filehandle to print to.
6459
6460=item *
6461
6462How many frames to skip before starting trace.
6463
6464=item *
6465
6466How many frames to print.
6467
6468=item *
6469
6470A flag: if true, print a I<short> trace without filenames, line numbers, or arguments
6471
6472=back
6473
6474The original comment below seems to be noting that the traceback may not be
6475correct if this routine is called in a tied method.
6476
6477=cut
6478
6479# Tied method do not create a context, so may get wrong message:
6480
6481sub print_trace {
6482    local $\ = '';
6483    my $fh = shift;
6484
6485    # If this is going to a client editor, but we're not the primary
6486    # debugger, reset it first.
6487    resetterm(1)
6488      if $fh        eq $LINEINFO    # client editor
6489      and $LINEINFO eq $OUT         # normal output
6490      and $term_pid != $$;          # not the primary
6491
6492    # Collect the actual trace information to be formatted.
6493    # This is an array of hashes of subroutine call info.
6494    my @sub = dump_trace( $_[0] + 1, $_[1] );
6495
6496    # Grab the "short report" flag from @_.
6497    my $short = $_[2];              # Print short report, next one for sub name
6498
6499    # Run through the traceback info, format it, and print it.
6500    my $s;
6501    for my $i (0 .. $#sub) {
6502
6503        # Drop out if the user has lost interest and hit control-C.
6504        last if $signal;
6505
6506        # Set the separator so arrays print nice.
6507        local $" = ', ';
6508
6509        # Grab and stringify the arguments if they are there.
6510        my $args =
6511          defined $sub[$i]{args}
6512          ? "(@{ $sub[$i]{args} })"
6513          : '';
6514
6515        # Shorten them up if $maxtrace says they're too long.
6516        $args = ( substr $args, 0, $maxtrace - 3 ) . '...'
6517          if length $args > $maxtrace;
6518
6519        # Get the file name.
6520        my $file = $sub[$i]{file};
6521
6522        # Put in a filename header if short is off.
6523        $file = $file eq '-e' ? $file : "file '$file'" unless $short;
6524
6525        # Get the actual sub's name, and shorten to $maxtrace's requirement.
6526        $s = $sub[$i]{'sub'};
6527        $s = ( substr $s, 0, $maxtrace - 3 ) . '...' if length $s > $maxtrace;
6528
6529        # Short report uses trimmed file and sub names.
6530        if ($short) {
6531            my $sub = @_ >= 4 ? $_[3] : $s;
6532            print $fh "$sub[$i]{context}=$sub$args from $file:$sub[$i]{line}\n";
6533        } ## end if ($short)
6534
6535        # Non-short report includes full names.
6536        else {
6537            print $fh "$sub[$i]{context} = $s$args"
6538              . " called from $file"
6539              . " line $sub[$i]{line}\n";
6540        }
6541    } ## end for my $i (0 .. $#sub)
6542} ## end sub print_trace
6543
6544=head2 dump_trace(skip[,count])
6545
6546Actually collect the traceback information available via C<caller()>. It does
6547some filtering and cleanup of the data, but mostly it just collects it to
6548make C<print_trace()>'s job easier.
6549
6550C<skip> defines the number of stack frames to be skipped, working backwards
6551from the most current. C<count> determines the total number of frames to
6552be returned; all of them (well, the first 10^9) are returned if C<count>
6553is omitted.
6554
6555This routine returns a list of hashes, from most-recent to least-recent
6556stack frame. Each has the following keys and values:
6557
6558=over 4
6559
6560=item * C<context> - C<.> (null), C<$> (scalar), or C<@> (array)
6561
6562=item * C<sub> - subroutine name, or C<eval> information
6563
6564=item * C<args> - undef, or a reference to an array of arguments
6565
6566=item * C<file> - the file in which this item was defined (if any)
6567
6568=item * C<line> - the line on which it was defined
6569
6570=back
6571
6572=cut
6573
6574sub _dump_trace_calc_saved_single_arg
6575{
6576    my ($nothard, $arg) = @_;
6577
6578    my $type;
6579    if ( not defined $arg ) {    # undefined parameter
6580        return "undef";
6581    }
6582
6583    elsif ( $nothard and tied $arg ) {    # tied parameter
6584        return "tied";
6585    }
6586    elsif ( $nothard and $type = ref $arg ) {    # reference
6587        return "ref($type)";
6588    }
6589    else {                                       # can be stringified
6590        local $_ =
6591        "$arg";    # Safe to stringify now - should not call f().
6592
6593        # Backslash any single-quotes or backslashes.
6594        s/([\'\\])/\\$1/g;
6595
6596        # Single-quote it unless it's a number or a colon-separated
6597        # name.
6598        s/(.*)/'$1'/s
6599        unless /^(?: -?[\d.]+ | \*[\w:]* )$/x;
6600
6601        # Turn high-bit characters into meta-whatever, and controls into like
6602        # '^D'.
6603        require 'meta_notation.pm';
6604        $_ = _meta_notation($_) if /[[:^print:]]/a;
6605
6606        return $_;
6607    }
6608}
6609
6610sub _dump_trace_calc_save_args {
6611    my ($nothard) = @_;
6612
6613    return [
6614        map { _dump_trace_calc_saved_single_arg($nothard, $_) } @args
6615    ];
6616}
6617
6618sub dump_trace {
6619
6620    # How many levels to skip.
6621    my $skip = shift;
6622
6623    # How many levels to show. (1e9 is a cheap way of saying "all of them";
6624    # it's unlikely that we'll have more than a billion stack frames. If you
6625    # do, you've got an awfully big machine...)
6626    my $count = shift || 1e9;
6627
6628    # We increment skip because caller(1) is the first level *back* from
6629    # the current one.  Add $skip to the count of frames so we have a
6630    # simple stop criterion, counting from $skip to $count+$skip.
6631    $skip++;
6632    $count += $skip;
6633
6634    # These variables are used to capture output from caller();
6635    my ( $p, $file, $line, $sub, $h, $context );
6636
6637    my ( $e, $r, @sub, $args );
6638
6639    # XXX Okay... why'd we do that?
6640    my $nothard = not $frame & 8;
6641    local $frame = 0;
6642
6643    # Do not want to trace this.
6644    my $otrace = $trace;
6645    $trace = 0;
6646
6647    # Start out at the skip count.
6648    # If we haven't reached the number of frames requested, and caller() is
6649    # still returning something, stay in the loop. (If we pass the requested
6650    # number of stack frames, or we run out - caller() returns nothing - we
6651    # quit.
6652    # Up the stack frame index to go back one more level each time.
6653    for (
6654        my $i = $skip ;
6655        $i < $count
6656        and ( $p, $file, $line, $sub, $h, $context, $e, $r ) = caller($i) ;
6657        $i++
6658    )
6659    {
6660        # if the sub has args ($h true), make an anonymous array of the
6661        # dumped args.
6662        my $args = $h ? _dump_trace_calc_save_args($nothard) : undef;
6663
6664        # If context is true, this is array (@)context.
6665        # If context is false, this is scalar ($) context.
6666        # If neither, context isn't defined. (This is apparently a 'can't
6667        # happen' trap.)
6668        $context = $context ? '@' : ( defined $context ? "\$" : '.' );
6669
6670        # remove trailing newline-whitespace-semicolon-end of line sequence
6671        # from the eval text, if any.
6672        $e =~ s/\n\s*\;\s*\Z// if $e;
6673
6674        # Escape backslashed single-quotes again if necessary.
6675        $e =~ s/([\\\'])/\\$1/g if $e;
6676
6677        # if the require flag is true, the eval text is from a require.
6678        if ($r) {
6679            $sub = "require '$e'";
6680        }
6681
6682        # if it's false, the eval text is really from an eval.
6683        elsif ( defined $r ) {
6684            $sub = "eval '$e'";
6685        }
6686
6687        # If the sub is '(eval)', this is a block eval, meaning we don't
6688        # know what the eval'ed text actually was.
6689        elsif ( $sub eq '(eval)' ) {
6690            $sub = "eval {...}";
6691        }
6692
6693        # Stick the collected information into @sub as an anonymous hash.
6694        push(
6695            @sub,
6696            {
6697                context => $context,
6698                sub     => $sub,
6699                args    => $args,
6700                file    => $file,
6701                line    => $line
6702            }
6703        );
6704
6705        # Stop processing frames if the user hit control-C.
6706        last if $signal;
6707    } ## end for ($i = $skip ; $i < ...
6708
6709    # Restore the trace value again.
6710    $trace = $otrace;
6711    @sub;
6712} ## end sub dump_trace
6713
6714=head2 C<action()>
6715
6716C<action()> takes input provided as the argument to an add-action command,
6717either pre- or post-, and makes sure it's a complete command. It doesn't do
6718any fancy parsing; it just keeps reading input until it gets a string
6719without a trailing backslash.
6720
6721=cut
6722
6723sub action {
6724    my $action = shift;
6725
6726    while ( $action =~ s/\\$// ) {
6727
6728        # We have a backslash on the end. Read more.
6729        $action .= gets();
6730    } ## end while ($action =~ s/\\$//)
6731
6732    # Return the assembled action.
6733    $action;
6734} ## end sub action
6735
6736=head2 unbalanced
6737
6738This routine mostly just packages up a regular expression to be used
6739to check that the thing it's being matched against has properly-matched
6740curly braces.
6741
6742Of note is the definition of the C<$balanced_brace_re> global via C<||=>, which
6743speeds things up by only creating the qr//'ed expression once; if it's
6744already defined, we don't try to define it again. A speed hack.
6745
6746=cut
6747
6748use vars qw($balanced_brace_re);
6749
6750sub unbalanced {
6751
6752    # I hate using globals!
6753    $balanced_brace_re ||= qr{
6754        ^ \{
6755             (?:
6756                 (?> [^{}] + )              # Non-parens without backtracking
6757                |
6758                 (??{ $balanced_brace_re }) # Group with matching parens
6759              ) *
6760          \} $
6761   }x;
6762    return $_[0] !~ m/$balanced_brace_re/;
6763} ## end sub unbalanced
6764
6765=head2 C<gets()>
6766
6767C<gets()> is a primitive (very primitive) routine to read continuations.
6768It was devised for reading continuations for actions.
6769it just reads more input with C<readline()> and returns it.
6770
6771=cut
6772
6773sub gets {
6774    return DB::readline("cont: ");
6775}
6776
6777=head2 C<_db_system()> - handle calls to<system()> without messing up the debugger
6778
6779The C<system()> function assumes that it can just go ahead and use STDIN and
6780STDOUT, but under the debugger, we want it to use the debugger's input and
6781outout filehandles.
6782
6783C<_db_system()> socks away the program's STDIN and STDOUT, and then substitutes
6784the debugger's IN and OUT filehandles for them. It does the C<system()> call,
6785and then puts everything back again.
6786
6787=cut
6788
6789sub _db_system {
6790
6791    # We save, change, then restore STDIN and STDOUT to avoid fork() since
6792    # some non-Unix systems can do system() but have problems with fork().
6793    open( SAVEIN,  "<&STDIN" )  || _db_warn("Can't save STDIN");
6794    open( SAVEOUT, ">&STDOUT" ) || _db_warn("Can't save STDOUT");
6795    open( STDIN,   "<&IN" )     || _db_warn("Can't redirect STDIN");
6796    open( STDOUT,  ">&OUT" )    || _db_warn("Can't redirect STDOUT");
6797
6798    # XXX: using csh or tcsh destroys sigint retvals!
6799    system(@_);
6800    open( STDIN,  "<&SAVEIN" )  || _db_warn("Can't restore STDIN");
6801    open( STDOUT, ">&SAVEOUT" ) || _db_warn("Can't restore STDOUT");
6802    close(SAVEIN);
6803    close(SAVEOUT);
6804
6805    # most of the $? crud was coping with broken cshisms
6806    if ( $? >> 8 ) {
6807        _db_warn( "(Command exited ", ( $? >> 8 ), ")\n" );
6808    }
6809    elsif ($?) {
6810        _db_warn(
6811            "(Command died of SIG#",
6812            ( $? & 127 ),
6813            ( ( $? & 128 ) ? " -- core dumped" : "" ),
6814            ")", "\n"
6815        );
6816    } ## end elsif ($?)
6817
6818    return $?;
6819
6820} ## end sub system
6821
6822*system = \&_db_system;
6823
6824=head1 TTY MANAGEMENT
6825
6826The subs here do some of the terminal management for multiple debuggers.
6827
6828=head2 setterm
6829
6830Top-level function called when we want to set up a new terminal for use
6831by the debugger.
6832
6833If the C<noTTY> debugger option was set, we'll either use the terminal
6834supplied (the value of the C<noTTY> option), or we'll use C<Term::Rendezvous>
6835to find one. If we're a forked debugger, we call C<resetterm> to try to
6836get a whole new terminal if we can.
6837
6838In either case, we set up the terminal next. If the C<ReadLine> option was
6839true, we'll get a C<Term::ReadLine> object for the current terminal and save
6840the appropriate attributes. We then
6841
6842=cut
6843
6844use vars qw($ornaments);
6845use vars qw($rl_attribs);
6846sub setterm {
6847
6848    # Load Term::Readline, but quietly; don't debug it and don't trace it.
6849    local $frame = 0;
6850    local $doret = -2;
6851    _DB__use_full_path(sub {
6852	require Term::ReadLine;
6853    });
6854
6855
6856    # If noTTY is set, but we have a TTY name, go ahead and hook up to it.
6857    if ($notty) {
6858        if ($tty) {
6859            my ( $i, $o ) = split $tty, /,/;
6860            $o = $i unless defined $o;
6861            open( IN,  '<', $i ) or die "Cannot open TTY '$i' for read: $!";
6862            open( OUT, '>', $o ) or die "Cannot open TTY '$o' for write: $!";
6863            $IN  = \*IN;
6864            $OUT = \*OUT;
6865            _autoflush($OUT);
6866        } ## end if ($tty)
6867
6868        # We don't have a TTY - try to find one via Term::Rendezvous.
6869        else {
6870            require Term::Rendezvous;
6871
6872            # See if we have anything to pass to Term::Rendezvous.
6873            # Use $HOME/.perldbtty$$ if not.
6874            my $rv = $ENV{PERLDB_NOTTY} || "$ENV{HOME}/.perldbtty$$";
6875
6876            # Rendezvous and get the filehandles.
6877            my $term_rv = Term::Rendezvous->new( $rv );
6878            $IN  = $term_rv->IN;
6879            $OUT = $term_rv->OUT;
6880        } ## end else [ if ($tty)
6881    } ## end if ($notty)
6882
6883    # We're a daughter debugger. Try to fork off another TTY.
6884    if ( $term_pid eq '-1' ) {    # In a TTY with another debugger
6885        resetterm(2);
6886    }
6887
6888    # If we shouldn't use Term::ReadLine, don't.
6889    if ( !$rl ) {
6890        $term = Term::ReadLine::Stub->new( 'perldb', $IN, $OUT );
6891    }
6892
6893    # We're using Term::ReadLine. Get all the attributes for this terminal.
6894    else {
6895        $term = Term::ReadLine->new( 'perldb', $IN, $OUT );
6896
6897        $rl_attribs = $term->Attribs;
6898        $rl_attribs->{basic_word_break_characters} .= '-:+/*,[])}'
6899          if defined $rl_attribs->{basic_word_break_characters}
6900          and index( $rl_attribs->{basic_word_break_characters}, ":" ) == -1;
6901        $rl_attribs->{special_prefixes} = '$@&%';
6902        $rl_attribs->{completer_word_break_characters} .= '$@&%';
6903        $rl_attribs->{completion_function} = \&db_complete;
6904    } ## end else [ if (!$rl)
6905
6906    # Set up the LINEINFO filehandle.
6907    $LINEINFO = $OUT     unless defined $LINEINFO;
6908    $lineinfo = $console unless defined $lineinfo;
6909
6910    $term->MinLine(2);
6911
6912    load_hist();
6913
6914    if ( $term->Features->{setHistory} and "@hist" ne "?" ) {
6915        $term->SetHistory(@hist);
6916    }
6917
6918    # XXX Ornaments are turned on unconditionally, which is not
6919    # always a good thing.
6920    ornaments($ornaments) if defined $ornaments;
6921    $term_pid = $$;
6922} ## end sub setterm
6923
6924sub load_hist {
6925    $histfile //= option_val("HistFile", undef);
6926    return unless defined $histfile;
6927    open my $fh, "<", $histfile or return;
6928    local $/ = "\n";
6929    @hist = ();
6930    while (<$fh>) {
6931        chomp;
6932        push @hist, $_;
6933    }
6934    close $fh;
6935}
6936
6937sub save_hist {
6938    return unless defined $histfile;
6939    eval { require File::Path } or return;
6940    eval { require File::Basename } or return;
6941    File::Path::mkpath(File::Basename::dirname($histfile));
6942    open my $fh, ">", $histfile or die "Could not open '$histfile': $!";
6943    $histsize //= option_val("HistSize",100);
6944    my @copy = grep { $_ ne '?' } @hist;
6945    my $start = scalar(@copy) > $histsize ? scalar(@copy)-$histsize : 0;
6946    for ($start .. $#copy) {
6947        print $fh "$copy[$_]\n";
6948    }
6949    close $fh or die "Could not write '$histfile': $!";
6950}
6951
6952=head1 GET_FORK_TTY EXAMPLE FUNCTIONS
6953
6954When the process being debugged forks, or the process invokes a command
6955via C<system()> which starts a new debugger, we need to be able to get a new
6956C<IN> and C<OUT> filehandle for the new debugger. Otherwise, the two processes
6957fight over the terminal, and you can never quite be sure who's going to get the
6958input you're typing.
6959
6960C<get_fork_TTY> is a glob-aliased function which calls the real function that
6961is tasked with doing all the necessary operating system mojo to get a new
6962TTY (and probably another window) and to direct the new debugger to read and
6963write there.
6964
6965The debugger provides C<get_fork_TTY> functions which work for TCP
6966socket servers, X11, OS/2, and Mac OS X. Other systems are not
6967supported. You are encouraged to write C<get_fork_TTY> functions which
6968work for I<your> platform and contribute them.
6969
6970=head3 C<socket_get_fork_TTY>
6971
6972=cut
6973
6974sub connect_remoteport {
6975    require IO::Socket;
6976
6977    my $socket = IO::Socket::INET->new(
6978        Timeout  => '10',
6979        PeerAddr => $remoteport,
6980        Proto    => 'tcp',
6981    );
6982    if ( ! $socket ) {
6983        die "Unable to connect to remote host: $remoteport\n";
6984    }
6985    return $socket;
6986}
6987
6988sub socket_get_fork_TTY {
6989    $tty = $LINEINFO = $IN = $OUT = connect_remoteport();
6990
6991    # Do I need to worry about setting $term?
6992
6993    reset_IN_OUT( $IN, $OUT );
6994    return '';
6995}
6996
6997=head3 C<xterm_get_fork_TTY>
6998
6999This function provides the C<get_fork_TTY> function for X11. If a
7000program running under the debugger forks, a new <xterm> window is opened and
7001the subsidiary debugger is directed there.
7002
7003The C<open()> call is of particular note here. We have the new C<xterm>
7004we're spawning route file number 3 to STDOUT, and then execute the C<tty>
7005command (which prints the device name of the TTY we'll want to use for input
7006and output to STDOUT, then C<sleep> for a very long time, routing this output
7007to file number 3. This way we can simply read from the <XT> filehandle (which
7008is STDOUT from the I<commands> we ran) to get the TTY we want to use.
7009
7010Only works if C<xterm> is in your path and C<$ENV{DISPLAY}>, etc. are
7011properly set up.
7012
7013=cut
7014
7015sub xterm_get_fork_TTY {
7016    ( my $name = $0 ) =~ s,^.*[/\\],,s;
7017    open XT,
7018qq[3>&1 xterm -title "Daughter Perl debugger $pids $name" -e sh -c 'tty 1>&3;\
7019 sleep 10000000' |];
7020
7021    # Get the output from 'tty' and clean it up a little.
7022    my $tty = <XT>;
7023    chomp $tty;
7024
7025    $pidprompt = '';    # Shown anyway in titlebar
7026
7027    # We need $term defined or we can not switch to the newly created xterm
7028    if ($tty ne '' && !defined $term) {
7029    	_DB__use_full_path(sub {
7030	    require Term::ReadLine;
7031	});
7032        if ( !$rl ) {
7033            $term = Term::ReadLine::Stub->new( 'perldb', $IN, $OUT );
7034        }
7035        else {
7036            $term = Term::ReadLine->new( 'perldb', $IN, $OUT );
7037        }
7038    }
7039    # There's our new TTY.
7040    return $tty;
7041} ## end sub xterm_get_fork_TTY
7042
7043=head3 C<os2_get_fork_TTY>
7044
7045XXX It behooves an OS/2 expert to write the necessary documentation for this!
7046
7047=cut
7048
7049# This example function resets $IN, $OUT itself
7050my $c_pipe = 0;
7051sub os2_get_fork_TTY { # A simplification of the following (and works without):
7052    local $\  = '';
7053    ( my $name = $0 ) =~ s,^.*[/\\],,s;
7054    my %opt = ( title => "Daughter Perl debugger $pids $name",
7055        ($rl ? (read_by_key => 1) : ()) );
7056    require OS2::Process;
7057    my ($in, $out, $pid) = eval { OS2::Process::io_term(related => 0, %opt) }
7058      or return;
7059    $pidprompt = '';    # Shown anyway in titlebar
7060    reset_IN_OUT($in, $out);
7061    $tty = '*reset*';
7062    return '';          # Indicate that reset_IN_OUT is called
7063} ## end sub os2_get_fork_TTY
7064
7065=head3 C<macosx_get_fork_TTY>
7066
7067The Mac OS X version uses AppleScript to tell Terminal.app to create
7068a new window.
7069
7070=cut
7071
7072# Notes about Terminal.app's AppleScript support,
7073# (aka things that might break in future OS versions).
7074#
7075# The "do script" command doesn't return a reference to the new window
7076# it creates, but since it appears frontmost and windows are enumerated
7077# front to back, we can use "first window" === "window 1".
7078#
7079# Since "do script" is implemented by supplying the argument (plus a
7080# return character) as terminal input, there's a potential race condition
7081# where the debugger could beat the shell to reading the command.
7082# To prevent this, we wait for the screen to clear before proceeding.
7083#
7084# 10.3 and 10.4:
7085# There's no direct accessor for the tty device name, so we fiddle
7086# with the window title options until it says what we want.
7087#
7088# 10.5:
7089# There _is_ a direct accessor for the tty device name, _and_ there's
7090# a new possible component of the window title (the name of the settings
7091# set).  A separate version is needed.
7092
7093my @script_versions=
7094
7095    ([237, <<'__LEOPARD__'],
7096tell application "Terminal"
7097    do script "clear;exec sleep 100000"
7098    tell first tab of first window
7099        copy tty to thetty
7100        set custom title to "forked perl debugger"
7101        set title displays custom title to true
7102        repeat while (length of first paragraph of (get contents)) > 0
7103            delay 0.1
7104        end repeat
7105    end tell
7106end tell
7107thetty
7108__LEOPARD__
7109
7110     [100, <<'__JAGUAR_TIGER__'],
7111tell application "Terminal"
7112    do script "clear;exec sleep 100000"
7113    tell first window
7114        set title displays shell path to false
7115        set title displays window size to false
7116        set title displays file name to false
7117        set title displays device name to true
7118        set title displays custom title to true
7119        set custom title to ""
7120        copy "/dev/" & name to thetty
7121        set custom title to "forked perl debugger"
7122        repeat while (length of first paragraph of (get contents)) > 0
7123            delay 0.1
7124        end repeat
7125    end tell
7126end tell
7127thetty
7128__JAGUAR_TIGER__
7129
7130);
7131
7132sub macosx_get_fork_TTY
7133{
7134    my($version,$script,$pipe,$tty);
7135
7136    return unless $version=$ENV{TERM_PROGRAM_VERSION};
7137    foreach my $entry (@script_versions) {
7138        if ($version>=$entry->[0]) {
7139            $script=$entry->[1];
7140            last;
7141        }
7142    }
7143    return unless defined($script);
7144    return unless open($pipe,'-|','/usr/bin/osascript','-e',$script);
7145    $tty=readline($pipe);
7146    close($pipe);
7147    return unless defined($tty) && $tty =~ m(^/dev/);
7148    chomp $tty;
7149    return $tty;
7150}
7151
7152=head3 C<tmux_get_fork_TTY>
7153
7154Creates a split window for subprocesses when a process running under the
7155perl debugger in Tmux forks.
7156
7157=cut
7158
7159sub tmux_get_fork_TTY {
7160    return unless $ENV{TMUX};
7161
7162    my $pipe;
7163
7164    my $status = open $pipe, '-|', 'tmux', 'split-window',
7165        '-P', '-F', '#{pane_tty}', 'sleep 100000';
7166
7167    if ( !$status ) {
7168        return;
7169    }
7170
7171    my $tty = <$pipe>;
7172    close $pipe;
7173
7174    if ( $tty ) {
7175        chomp $tty;
7176
7177        if ( !defined $term ) {
7178            require Term::ReadLine;
7179            if ( !$rl ) {
7180                $term = Term::ReadLine::Stub->new( 'perldb', $IN, $OUT );
7181            }
7182            else {
7183                $term = Term::ReadLine->new( 'perldb', $IN, $OUT );
7184            }
7185        }
7186    }
7187
7188    return $tty;
7189}
7190
7191=head2 C<create_IN_OUT($flags)>
7192
7193Create a new pair of filehandles, pointing to a new TTY. If impossible,
7194try to diagnose why.
7195
7196Flags are:
7197
7198=over 4
7199
7200=item * 1 - Don't know how to create a new TTY.
7201
7202=item * 2 - Debugger has forked, but we can't get a new TTY.
7203
7204=item * 4 - standard debugger startup is happening.
7205
7206=back
7207
7208=cut
7209
7210use vars qw($fork_TTY);
7211
7212sub create_IN_OUT {    # Create a window with IN/OUT handles redirected there
7213
7214    # If we know how to get a new TTY, do it! $in will have
7215    # the TTY name if get_fork_TTY works.
7216    my $in = get_fork_TTY(@_) if defined &get_fork_TTY;
7217
7218    # It used to be that
7219    $in = $fork_TTY if defined $fork_TTY;    # Backward compatibility
7220
7221    if ( not defined $in ) {
7222        my $why = shift;
7223
7224        # We don't know how.
7225        print_help(<<EOP) if $why == 1;
7226I<#########> Forked, but do not know how to create a new B<TTY>. I<#########>
7227EOP
7228
7229        # Forked debugger.
7230        print_help(<<EOP) if $why == 2;
7231I<#########> Daughter session, do not know how to change a B<TTY>. I<#########>
7232  This may be an asynchronous session, so the parent debugger may be active.
7233EOP
7234
7235        # Note that both debuggers are fighting over the same input.
7236        print_help(<<EOP) if $why != 4;
7237  Since two debuggers fight for the same TTY, input is severely entangled.
7238
7239EOP
7240        print_help(<<EOP);
7241  I know how to switch the output to a different window in xterms, OS/2
7242  consoles, and Mac OS X Terminal.app only.  For a manual switch, put the name
7243  of the created I<TTY> in B<\$DB::fork_TTY>, or define a function
7244  B<DB::get_fork_TTY()> returning this.
7245
7246  On I<UNIX>-like systems one can get the name of a I<TTY> for the given window
7247  by typing B<tty>, and disconnect the I<shell> from I<TTY> by S<B<sleep 1000000>>.
7248
7249EOP
7250    } ## end if (not defined $in)
7251    elsif ( $in ne '' ) {
7252        TTY($in);
7253    }
7254    else {
7255        $console = '';    # Indicate no need to open-from-the-console
7256    }
7257    undef $fork_TTY;
7258} ## end sub create_IN_OUT
7259
7260=head2 C<resetterm>
7261
7262Handles rejiggering the prompt when we've forked off a new debugger.
7263
7264If the new debugger happened because of a C<system()> that invoked a
7265program under the debugger, the arrow between the old pid and the new
7266in the prompt has I<two> dashes instead of one.
7267
7268We take the current list of pids and add this one to the end. If there
7269isn't any list yet, we make one up out of the initial pid associated with
7270the terminal and our new pid, sticking an arrow (either one-dashed or
7271two dashed) in between them.
7272
7273If C<CreateTTY> is off, or C<resetterm> was called with no arguments,
7274we don't try to create a new IN and OUT filehandle. Otherwise, we go ahead
7275and try to do that.
7276
7277=cut
7278
7279sub resetterm {    # We forked, so we need a different TTY
7280
7281    # Needs to be passed to create_IN_OUT() as well.
7282    my $in = shift;
7283
7284    # resetterm(2): got in here because of a system() starting a debugger.
7285    # resetterm(1): just forked.
7286    my $systemed = $in > 1 ? '-' : '';
7287
7288    # If there's already a list of pids, add this to the end.
7289    if ($pids) {
7290        $pids =~ s/\]/$systemed->$$]/;
7291    }
7292
7293    # No pid list. Time to make one.
7294    else {
7295        $pids = "[$term_pid->$$]";
7296    }
7297
7298    # The prompt we're going to be using for this debugger.
7299    $pidprompt = $pids;
7300
7301    # We now 0wnz this terminal.
7302    $term_pid = $$;
7303
7304    # Just return if we're not supposed to try to create a new TTY.
7305    return unless $CreateTTY & $in;
7306
7307    # Try to create a new IN/OUT pair.
7308    create_IN_OUT($in);
7309} ## end sub resetterm
7310
7311=head2 C<readline>
7312
7313First, we handle stuff in the typeahead buffer. If there is any, we shift off
7314the next line, print a message saying we got it, add it to the terminal
7315history (if possible), and return it.
7316
7317If there's nothing in the typeahead buffer, check the command filehandle stack.
7318If there are any filehandles there, read from the last one, and return the line
7319if we got one. If not, we pop the filehandle off and close it, and try the
7320next one up the stack.
7321
7322If we've emptied the filehandle stack, we check to see if we've got a socket
7323open, and we read that and return it if we do. If we don't, we just call the
7324core C<readline()> and return its value.
7325
7326=cut
7327
7328sub readline {
7329
7330    # Localize to prevent it from being smashed in the program being debugged.
7331    local $.;
7332
7333    # If there are stacked filehandles to read from ...
7334    # (Handle it before the typeahead, because we may call source/etc. from
7335    # the typeahead.)
7336    while (@cmdfhs) {
7337
7338        # Read from the last one in the stack.
7339        my $line = CORE::readline( $cmdfhs[-1] );
7340
7341        # If we got a line ...
7342        defined $line
7343          ? ( print $OUT ">> $line" and return $line )    # Echo and return
7344          : close pop @cmdfhs;                            # Pop and close
7345    } ## end while (@cmdfhs)
7346
7347    # Pull a line out of the typeahead if there's stuff there.
7348    if (@typeahead) {
7349
7350        # How many lines left.
7351        my $left = @typeahead;
7352
7353        # Get the next line.
7354        my $got = shift @typeahead;
7355
7356        # Print a message saying we got input from the typeahead.
7357        local $\ = '';
7358        print $OUT "auto(-$left)", shift, $got, "\n";
7359
7360        # Add it to the terminal history (if possible).
7361        $term->AddHistory($got)
7362          if length($got) >= option_val("HistItemMinLength", 2)
7363          and defined $term->Features->{addHistory};
7364        return $got;
7365    } ## end if (@typeahead)
7366
7367    # We really need to read some input. Turn off entry/exit trace and
7368    # return value printing.
7369    local $frame = 0;
7370    local $doret = -2;
7371
7372    # Nothing on the filehandle stack. Socket?
7373    if ( ref $OUT and UNIVERSAL::isa( $OUT, 'IO::Socket::INET' ) ) {
7374
7375        # Send anything we have to send.
7376        $OUT->write( join( '', @_ ) );
7377
7378        # Receive anything there is to receive.
7379        my $stuff = '';
7380        my $buf;
7381        my $first_time = 1;
7382
7383        while ($first_time or (length($buf) && ($stuff .= $buf) !~ /\n/))
7384        {
7385            $first_time = 0;
7386            $IN->recv( $buf = '', 2048 );   # XXX "what's wrong with sysread?"
7387                                            # XXX Don't know. You tell me.
7388        }
7389
7390        # What we got.
7391        return $stuff;
7392    } ## end if (ref $OUT and UNIVERSAL::isa...
7393
7394    # No socket. Just read from the terminal.
7395    else {
7396        return $term->readline(@_);
7397    }
7398} ## end sub readline
7399
7400=head1 OPTIONS SUPPORT ROUTINES
7401
7402These routines handle listing and setting option values.
7403
7404=head2 C<dump_option> - list the current value of an option setting
7405
7406This routine uses C<option_val> to look up the value for an option.
7407It cleans up escaped single-quotes and then displays the option and
7408its value.
7409
7410=cut
7411
7412sub dump_option {
7413    my ( $opt, $val ) = @_;
7414    $val = option_val( $opt, 'N/A' );
7415    $val =~ s/([\\\'])/\\$1/g;
7416    printf $OUT "%20s = '%s'\n", $opt, $val;
7417} ## end sub dump_option
7418
7419sub options2remember {
7420    foreach my $k (@RememberOnROptions) {
7421        $option{$k} = option_val( $k, 'N/A' );
7422    }
7423    return %option;
7424}
7425
7426=head2 C<option_val> - find the current value of an option
7427
7428This can't just be a simple hash lookup because of the indirect way that
7429the option values are stored. Some are retrieved by calling a subroutine,
7430some are just variables.
7431
7432You must supply a default value to be used in case the option isn't set.
7433
7434=cut
7435
7436sub option_val {
7437    my ( $opt, $default ) = @_;
7438    my $val;
7439
7440    # Does this option exist, and is it a variable?
7441    # If so, retrieve the value via the value in %optionVars.
7442    if (    defined $optionVars{$opt}
7443        and defined ${ $optionVars{$opt} } )
7444    {
7445        $val = ${ $optionVars{$opt} };
7446    }
7447
7448    # Does this option exist, and it's a subroutine?
7449    # If so, call the subroutine via the ref in %optionAction
7450    # and capture the value.
7451    elsif ( defined $optionAction{$opt}
7452        and defined &{ $optionAction{$opt} } )
7453    {
7454        $val = &{ $optionAction{$opt} }();
7455    }
7456
7457    # If there's an action or variable for the supplied option,
7458    # but no value was set, use the default.
7459    elsif (defined $optionAction{$opt} and not defined $option{$opt}
7460        or defined $optionVars{$opt} and not defined ${ $optionVars{$opt} } )
7461    {
7462        $val = $default;
7463    }
7464
7465    # Otherwise, do the simple hash lookup.
7466    else {
7467        $val = $option{$opt};
7468    }
7469
7470    # If the value isn't defined, use the default.
7471    # Then return whatever the value is.
7472    $val = $default unless defined $val;
7473    $val;
7474} ## end sub option_val
7475
7476=head2 C<parse_options>
7477
7478Handles the parsing and execution of option setting/displaying commands.
7479
7480An option entered by itself is assumed to be I<set me to 1> (the default value)
7481if the option is a boolean one. If not, the user is prompted to enter a valid
7482value or to query the current value (via C<option? >).
7483
7484If C<option=value> is entered, we try to extract a quoted string from the
7485value (if it is quoted). If it's not, we just use the whole value as-is.
7486
7487We load any modules required to service this option, and then we set it: if
7488it just gets stuck in a variable, we do that; if there's a subroutine to
7489handle setting the option, we call that.
7490
7491Finally, if we're running in interactive mode, we display the effect of the
7492user's command back to the terminal, skipping this if we're setting things
7493during initialization.
7494
7495=cut
7496
7497sub parse_options {
7498    my ($s) = @_;
7499    local $\ = '';
7500
7501    my $option;
7502
7503    # These options need a value. Don't allow them to be clobbered by accident.
7504    my %opt_needs_val = map { ( $_ => 1 ) } qw{
7505      dumpDepth arrayDepth hashDepth LineInfo maxTraceLen ornaments windowSize
7506      pager quote ReadLine recallCommand RemotePort ShellBang TTY CommandSet
7507    };
7508
7509    while (length($s)) {
7510        my $val_defaulted;
7511
7512        # Clean off excess leading whitespace.
7513        $s =~ s/^\s+// && next;
7514
7515        # Options are always all word characters, followed by a non-word
7516        # separator.
7517        if ($s !~ s/^(\w+)(\W?)//) {
7518            print {$OUT} "Invalid option '$s'\n";
7519            last;
7520        }
7521        my ( $opt, $sep ) = ( $1, $2 );
7522
7523        # Make sure that such an option exists.
7524        my $matches = ( grep { /^\Q$opt/ && ( $option = $_ ) } @options )
7525          || ( grep { /^\Q$opt/i && ( $option = $_ ) } @options );
7526
7527        unless ($matches) {
7528            print {$OUT} "Unknown option '$opt'\n";
7529            next;
7530        }
7531        if ($matches > 1) {
7532            print {$OUT} "Ambiguous option '$opt'\n";
7533            next;
7534        }
7535        my $val;
7536
7537        # '?' as separator means query, but must have whitespace after it.
7538        if ( "?" eq $sep ) {
7539            if ($s =~ /\A\S/) {
7540                print {$OUT} "Option query '$opt?' followed by non-space '$s'\n" ;
7541
7542                last;
7543            }
7544
7545            #&dump_option($opt);
7546        } ## end if ("?" eq $sep)
7547
7548        # Separator is whitespace (or just a carriage return).
7549        # They're going for a default, which we assume is 1.
7550        elsif ( $sep !~ /\S/ ) {
7551            $val_defaulted = 1;
7552            $val           = "1";   #  this is an evil default; make 'em set it!
7553        }
7554
7555        # Separator is =. Trying to set a value.
7556        elsif ( $sep eq "=" ) {
7557
7558            # If quoted, extract a quoted string.
7559            if ($s =~ s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x) {
7560                my $quote = $1;
7561                ( $val = $2 ) =~ s/\\([$quote\\])/$1/g;
7562            }
7563
7564            # Not quoted. Use the whole thing. Warn about 'option='.
7565            else {
7566                $s =~ s/^(\S*)//;
7567                $val = $1;
7568                print OUT qq(Option better cleared using $opt=""\n)
7569                  unless length $val;
7570            } ## end else [ if (s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x)
7571
7572        } ## end elsif ($sep eq "=")
7573
7574        # "Quoted" with [], <>, or {}.
7575        else {    #{ to "let some poor schmuck bounce on the % key in B<vi>."
7576            my ($end) =
7577              "\\" . substr( ")]>}$sep", index( "([<{", $sep ), 1 );    #}
7578            $s =~ s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)//
7579              or print( $OUT "Unclosed option value '$opt$sep$_'\n" ), last;
7580            ( $val = $1 ) =~ s/\\([\\$end])/$1/g;
7581        } ## end else [ if ("?" eq $sep)
7582
7583        # Exclude non-booleans from getting set to 1 by default.
7584        if ( $opt_needs_val{$option} && $val_defaulted ) {
7585            my $cmd = ( $CommandSet eq '580' ) ? 'o' : 'O';
7586            print {$OUT}
7587"Option '$opt' is non-boolean.  Use '$cmd $option=VAL' to set, '$cmd $option?' to query\n";
7588            next;
7589        } ## end if ($opt_needs_val{$option...
7590
7591        # Save the option value.
7592        $option{$option} = $val if defined $val;
7593
7594        # Load any module that this option requires.
7595        if ( defined($optionRequire{$option}) && defined($val) ) {
7596            eval qq{
7597            local \$frame = 0;
7598            local \$doret = -2;
7599            require '$optionRequire{$option}';
7600            1;
7601            } || die $@   # XXX: shouldn't happen
7602        }
7603
7604        # Set it.
7605        # Stick it in the proper variable if it goes in a variable.
7606        if (defined($optionVars{$option}) && defined($val)) {
7607            ${ $optionVars{$option} } = $val;
7608        }
7609
7610        # Call the appropriate sub if it gets set via sub.
7611        if (defined($optionAction{$option})
7612          && defined (&{ $optionAction{$option} })
7613          && defined ($val))
7614        {
7615          &{ $optionAction{$option} }($val);
7616        }
7617
7618        # Not initialization - echo the value we set it to.
7619        dump_option($option) if ($OUT ne \*STDERR);
7620    } ## end while (length)
7621} ## end sub parse_options
7622
7623=head1 RESTART SUPPORT
7624
7625These routines are used to store (and restore) lists of items in environment
7626variables during a restart.
7627
7628=head2 set_list
7629
7630Set_list packages up items to be stored in a set of environment variables
7631(VAR_n, containing the number of items, and VAR_0, VAR_1, etc., containing
7632the values). Values outside the standard ASCII charset are stored by encoding
7633them as hexadecimal values.
7634
7635=cut
7636
7637sub set_list {
7638    my ( $stem, @list ) = @_;
7639    my $val;
7640
7641    # VAR_n: how many we have. Scalar assignment gets the number of items.
7642    $ENV{"${stem}_n"} = @list;
7643
7644    # Grab each item in the list, escape the backslashes, encode the non-ASCII
7645    # as hex, and then save in the appropriate VAR_0, VAR_1, etc.
7646    for my $i ( 0 .. $#list ) {
7647        $val = $list[$i];
7648        $val =~ s/\\/\\\\/g;
7649        $val =~ s/ ( (?[ [\000-\xFF] & [:^print:] ]) ) /
7650                                                "\\0x" . unpack('H2',$1)/xaeg;
7651        $ENV{"${stem}_$i"} = $val;
7652    } ## end for $i (0 .. $#list)
7653} ## end sub set_list
7654
7655=head2 get_list
7656
7657Reverse the set_list operation: grab VAR_n to see how many we should be getting
7658back, and then pull VAR_0, VAR_1. etc. back out.
7659
7660=cut
7661
7662sub get_list {
7663    my $stem = shift;
7664    my @list;
7665    my $n = delete $ENV{"${stem}_n"};
7666    my $val;
7667    for my $i ( 0 .. $n - 1 ) {
7668        $val = delete $ENV{"${stem}_$i"};
7669        $val =~ s/\\((\\)|0x(..))/ $2 ? $2 : pack('H2', $3) /ge;
7670        push @list, $val;
7671    }
7672    @list;
7673} ## end sub get_list
7674
7675=head1 MISCELLANEOUS SIGNAL AND I/O MANAGEMENT
7676
7677=head2 catch()
7678
7679The C<catch()> subroutine is the essence of fast and low-impact. We simply
7680set an already-existing global scalar variable to a constant value. This
7681avoids allocating any memory possibly in the middle of something that will
7682get all confused if we do, particularly under I<unsafe signals>.
7683
7684=cut
7685
7686sub catch {
7687    $signal = 1;
7688    return;    # Put nothing on the stack - malloc/free land!
7689}
7690
7691=head2 C<warn()>
7692
7693C<warn> emits a warning, by joining together its arguments and printing
7694them, with couple of fillips.
7695
7696If the composited message I<doesn't> end with a newline, we automatically
7697add C<$!> and a newline to the end of the message. The subroutine expects $OUT
7698to be set to the filehandle to be used to output warnings; it makes no
7699assumptions about what filehandles are available.
7700
7701=cut
7702
7703sub _db_warn {
7704    my ($msg) = join( "", @_ );
7705    $msg .= ": $!\n" unless $msg =~ /\n$/;
7706    local $\ = '';
7707    print $OUT $msg;
7708} ## end sub warn
7709
7710*warn = \&_db_warn;
7711
7712=head1 INITIALIZATION TTY SUPPORT
7713
7714=head2 C<reset_IN_OUT>
7715
7716This routine handles restoring the debugger's input and output filehandles
7717after we've tried and failed to move them elsewhere.  In addition, it assigns
7718the debugger's output filehandle to $LINEINFO if it was already open there.
7719
7720=cut
7721
7722sub reset_IN_OUT {
7723    my $switch_li = $LINEINFO eq $OUT;
7724
7725    # If there's a term and it's able to get a new tty, try to get one.
7726    if ( $term and $term->Features->{newTTY} ) {
7727        ( $IN, $OUT ) = ( shift, shift );
7728        $term->newTTY( $IN, $OUT );
7729    }
7730
7731    # This term can't get a new tty now. Better luck later.
7732    elsif ($term) {
7733        _db_warn("Too late to set IN/OUT filehandles, enabled on next 'R'!\n");
7734    }
7735
7736    # Set the filehndles up as they were.
7737    else {
7738        ( $IN, $OUT ) = ( shift, shift );
7739    }
7740
7741    # Unbuffer the output filehandle.
7742    _autoflush($OUT);
7743
7744    # Point LINEINFO to the same output filehandle if it was there before.
7745    $LINEINFO = $OUT if $switch_li;
7746} ## end sub reset_IN_OUT
7747
7748=head1 OPTION SUPPORT ROUTINES
7749
7750The following routines are used to process some of the more complicated
7751debugger options.
7752
7753=head2 C<TTY>
7754
7755Sets the input and output filehandles to the specified files or pipes.
7756If the terminal supports switching, we go ahead and do it. If not, and
7757there's already a terminal in place, we save the information to take effect
7758on restart.
7759
7760If there's no terminal yet (for instance, during debugger initialization),
7761we go ahead and set C<$console> and C<$tty> to the file indicated.
7762
7763=cut
7764
7765sub TTY {
7766
7767    if ( @_ and $term and $term->Features->{newTTY} ) {
7768
7769        # This terminal supports switching to a new TTY.
7770        # Can be a list of two files, or on string containing both names,
7771        # comma-separated.
7772        # XXX Should this perhaps be an assignment from @_?
7773        my ( $in, $out ) = shift;
7774        if ( $in =~ /,/ ) {
7775
7776            # Split list apart if supplied.
7777            ( $in, $out ) = split /,/, $in, 2;
7778        }
7779        else {
7780
7781            # Use the same file for both input and output.
7782            $out = $in;
7783        }
7784
7785        # Open file onto the debugger's filehandles, if you can.
7786        open IN,  '<', $in or die "cannot open '$in' for read: $!";
7787        open OUT, '>', $out or die "cannot open '$out' for write: $!";
7788
7789        # Swap to the new filehandles.
7790        reset_IN_OUT( \*IN, \*OUT );
7791
7792        # Save the setting for later.
7793        return $tty = $in;
7794    } ## end if (@_ and $term and $term...
7795
7796    # Terminal doesn't support new TTY, or doesn't support readline.
7797    # Can't do it now, try restarting.
7798    if ($term and @_) {
7799        _db_warn("Too late to set TTY, enabled on next 'R'!\n");
7800    }
7801
7802    # Useful if done through PERLDB_OPTS:
7803    $console = $tty = shift if @_;
7804
7805    # Return whatever the TTY is.
7806    $tty or $console;
7807} ## end sub TTY
7808
7809=head2 C<noTTY>
7810
7811Sets the C<$notty> global, controlling whether or not the debugger tries to
7812get a terminal to read from. If called after a terminal is already in place,
7813we save the value to use it if we're restarted.
7814
7815=cut
7816
7817sub noTTY {
7818    if ($term) {
7819        _db_warn("Too late to set noTTY, enabled on next 'R'!\n") if @_;
7820    }
7821    $notty = shift if @_;
7822    $notty;
7823} ## end sub noTTY
7824
7825=head2 C<ReadLine>
7826
7827Sets the C<$rl> option variable. If 0, we use C<Term::ReadLine::Stub>
7828(essentially, no C<readline> processing on this I<terminal>). Otherwise, we
7829use C<Term::ReadLine>. Can't be changed after a terminal's in place; we save
7830the value in case a restart is done so we can change it then.
7831
7832=cut
7833
7834sub ReadLine {
7835    if ($term) {
7836        _db_warn("Too late to set ReadLine, enabled on next 'R'!\n") if @_;
7837    }
7838    $rl = shift if @_;
7839    $rl;
7840} ## end sub ReadLine
7841
7842=head2 C<RemotePort>
7843
7844Sets the port that the debugger will try to connect to when starting up.
7845If the terminal's already been set up, we can't do it, but we remember the
7846setting in case the user does a restart.
7847
7848=cut
7849
7850sub RemotePort {
7851    if ($term) {
7852        _db_warn("Too late to set RemotePort, enabled on next 'R'!\n") if @_;
7853    }
7854    $remoteport = shift if @_;
7855    $remoteport;
7856} ## end sub RemotePort
7857
7858=head2 C<tkRunning>
7859
7860Checks with the terminal to see if C<Tk> is running, and returns true or
7861false. Returns false if the current terminal doesn't support C<readline>.
7862
7863=cut
7864
7865sub tkRunning {
7866    if ( ${ $term->Features }{tkRunning} ) {
7867        return $term->tkRunning(@_);
7868    }
7869    else {
7870        local $\ = '';
7871        print $OUT "tkRunning not supported by current ReadLine package.\n";
7872        0;
7873    }
7874} ## end sub tkRunning
7875
7876=head2 C<NonStop>
7877
7878Sets nonstop mode. If a terminal's already been set up, it's too late; the
7879debugger remembers the setting in case you restart, though.
7880
7881=cut
7882
7883sub NonStop {
7884    if ($term) {
7885        _db_warn("Too late to set up NonStop mode, enabled on next 'R'!\n")
7886          if @_;
7887    }
7888    $runnonstop = shift if @_;
7889    $runnonstop;
7890} ## end sub NonStop
7891
7892sub DollarCaretP {
7893    if ($term) {
7894        _db_warn("Some flag changes could not take effect until next 'R'!\n")
7895          if @_;
7896    }
7897    $^P = parse_DollarCaretP_flags(shift) if @_;
7898    expand_DollarCaretP_flags($^P);
7899}
7900
7901=head2 C<pager>
7902
7903Set up the C<$pager> variable. Adds a pipe to the front unless there's one
7904there already.
7905
7906=cut
7907
7908sub pager {
7909    if (@_) {
7910        $pager = shift;
7911        $pager = "|" . $pager unless $pager =~ /^(\+?\>|\|)/;
7912    }
7913    $pager;
7914} ## end sub pager
7915
7916=head2 C<shellBang>
7917
7918Sets the shell escape command, and generates a printable copy to be used
7919in the help.
7920
7921=cut
7922
7923sub shellBang {
7924
7925    # If we got an argument, meta-quote it, and add '\b' if it
7926    # ends in a word character.
7927    if (@_) {
7928        $sh = quotemeta shift;
7929        $sh .= "\\b" if $sh =~ /\w$/;
7930    }
7931
7932    # Generate the printable version for the help:
7933    $psh = $sh;    # copy it
7934    $psh =~ s/\\b$//;        # Take off trailing \b if any
7935    $psh =~ s/\\(.)/$1/g;    # De-escape
7936    $psh;                    # return the printable version
7937} ## end sub shellBang
7938
7939=head2 C<ornaments>
7940
7941If the terminal has its own ornaments, fetch them. Otherwise accept whatever
7942was passed as the argument. (This means you can't override the terminal's
7943ornaments.)
7944
7945=cut
7946
7947sub ornaments {
7948    if ( defined $term ) {
7949
7950        # We don't want to show warning backtraces, but we do want die() ones.
7951        local $warnLevel = 0;
7952        local $dieLevel = 1;
7953
7954        # No ornaments if the terminal doesn't support them.
7955        if (not $term->Features->{ornaments}) {
7956            return '';
7957        }
7958
7959        return (eval { $term->ornaments(@_) } || '');
7960    }
7961
7962    # Use what was passed in if we can't determine it ourselves.
7963    else {
7964        $ornaments = shift;
7965
7966        return $ornaments;
7967    }
7968
7969} ## end sub ornaments
7970
7971=head2 C<recallCommand>
7972
7973Sets the recall command, and builds a printable version which will appear in
7974the help text.
7975
7976=cut
7977
7978sub recallCommand {
7979
7980    # If there is input, metaquote it. Add '\b' if it ends with a word
7981    # character.
7982    if (@_) {
7983        $rc = quotemeta shift;
7984        $rc .= "\\b" if $rc =~ /\w$/;
7985    }
7986
7987    # Build it into a printable version.
7988    $prc = $rc;              # Copy it
7989    $prc =~ s/\\b$//;        # Remove trailing \b
7990    $prc =~ s/\\(.)/$1/g;    # Remove escapes
7991    return $prc;             # Return the printable version
7992} ## end sub recallCommand
7993
7994=head2 C<LineInfo> - where the line number information goes
7995
7996Called with no arguments, returns the file or pipe that line info should go to.
7997
7998Called with an argument (a file or a pipe), it opens that onto the
7999C<LINEINFO> filehandle, unbuffers the filehandle, and then returns the
8000file or pipe again to the caller.
8001
8002=cut
8003
8004sub LineInfo {
8005    if (@_) {
8006        $lineinfo = shift;
8007
8008        #  If this is a valid "thing to be opened for output", tack a
8009        # '>' onto the front.
8010        my $stream = ( $lineinfo =~ /^(\+?\>|\|)/ ) ? $lineinfo : ">$lineinfo";
8011
8012        # If this is a pipe, the stream points to a client editor.
8013        $client_editor = ( $stream =~ /^\|/ );
8014
8015        my $new_lineinfo_fh;
8016        # Open it up and unbuffer it.
8017        open ($new_lineinfo_fh , $stream )
8018            or _db_warn("Cannot open '$stream' for write");
8019        $LINEINFO = $new_lineinfo_fh;
8020        _autoflush($LINEINFO);
8021    }
8022
8023    return $lineinfo;
8024} ## end sub LineInfo
8025
8026=head1 COMMAND SUPPORT ROUTINES
8027
8028These subroutines provide functionality for various commands.
8029
8030=head2 C<list_modules>
8031
8032For the C<M> command: list modules loaded and their versions.
8033Essentially just runs through the keys in %INC, picks each package's
8034C<$VERSION> variable, gets the file name, and formats the information
8035for output.
8036
8037=cut
8038
8039sub list_modules {    # versions
8040    my %version;
8041    my $file;
8042
8043    # keys are the "as-loaded" name, values are the fully-qualified path
8044    # to the file itself.
8045    for ( keys %INC ) {
8046        $file = $_;                                # get the module name
8047        s,\.p[lm]$,,i;                             # remove '.pl' or '.pm'
8048        s,/,::,g;                                  # change '/' to '::'
8049        s/^perl5db$/DB/;                           # Special case: debugger
8050                                                   # moves to package DB
8051        s/^Term::ReadLine::readline$/readline/;    # simplify readline
8052
8053        # If the package has a $VERSION package global (as all good packages
8054        # should!) decode it and save as partial message.
8055        my $pkg_version = do { no strict 'refs'; ${ $_ . '::VERSION' } };
8056        if ( defined $pkg_version ) {
8057            $version{$file} = "$pkg_version from ";
8058        }
8059
8060        # Finish up the message with the file the package came from.
8061        $version{$file} .= $INC{$file};
8062    } ## end for (keys %INC)
8063
8064    # Hey, dumpit() formats a hash nicely, so why not use it?
8065    dumpit( $OUT, \%version );
8066} ## end sub list_modules
8067
8068=head2 C<sethelp()>
8069
8070Sets up the monster string used to format and print the help.
8071
8072=head3 HELP MESSAGE FORMAT
8073
8074The help message is a peculiar format unto itself; it mixes C<pod> I<ornaments>
8075(C<< B<> >> C<< I<> >>) with tabs to come up with a format that's fairly
8076easy to parse and portable, but which still allows the help to be a little
8077nicer than just plain text.
8078
8079Essentially, you define the command name (usually marked up with C<< B<> >>
8080and C<< I<> >>), followed by a tab, and then the descriptive text, ending in a
8081newline. The descriptive text can also be marked up in the same way. If you
8082need to continue the descriptive text to another line, start that line with
8083just tabs and then enter the marked-up text.
8084
8085If you are modifying the help text, I<be careful>. The help-string parser is
8086not very sophisticated, and if you don't follow these rules it will mangle the
8087help beyond hope until you fix the string.
8088
8089=cut
8090
8091use vars qw($pre580_help);
8092use vars qw($pre580_summary);
8093
8094sub sethelp {
8095
8096    # XXX: make sure there are tabs between the command and explanation,
8097    #      or print_help will screw up your formatting if you have
8098    #      eeevil ornaments enabled.  This is an insane mess.
8099
8100    $help = "
8101Help is currently only available for the new 5.8 command set.
8102No help is available for the old command set.
8103We assume you know what you're doing if you switch to it.
8104
8105B<T>        Stack trace.
8106B<s> [I<expr>]    Single step [in I<expr>].
8107B<n> [I<expr>]    Next, steps over subroutine calls [in I<expr>].
8108<B<CR>>        Repeat last B<n> or B<s> command.
8109B<r>        Return from current subroutine.
8110B<c> [I<line>|I<sub>]    Continue; optionally inserts a one-time-only breakpoint
8111        at the specified position.
8112B<l> I<min>B<+>I<incr>    List I<incr>+1 lines starting at I<min>.
8113B<l> I<min>B<->I<max>    List lines I<min> through I<max>.
8114B<l> I<line>        List single I<line>.
8115B<l> I<subname>    List first window of lines from subroutine.
8116B<l> I<\$var>        List first window of lines from subroutine referenced by I<\$var>.
8117B<l>        List next window of lines.
8118B<->        List previous window of lines.
8119B<v> [I<line>]    View window around I<line>.
8120B<.>        Return to the executed line.
8121B<f> I<filename>    Switch to viewing I<filename>. File must be already loaded.
8122        I<filename> may be either the full name of the file, or a regular
8123        expression matching the full file name:
8124        B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
8125        Evals (with saved bodies) are considered to be filenames:
8126        B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
8127        (in the order of execution).
8128B</>I<pattern>B</>    Search forwards for I<pattern>; final B</> is optional.
8129B<?>I<pattern>B<?>    Search backwards for I<pattern>; final B<?> is optional.
8130B<L> [I<a|b|w>]        List actions and or breakpoints and or watch-expressions.
8131B<S> [[B<!>]I<pattern>]    List subroutine names [not] matching I<pattern>.
8132B<t> [I<n>]       Toggle trace mode (to max I<n> levels below current stack depth).
8133B<t> [I<n>] I<expr>        Trace through execution of I<expr>.
8134B<b>        Sets breakpoint on current line)
8135B<b> [I<line>] [I<condition>]
8136        Set breakpoint; I<line> defaults to the current execution line;
8137        I<condition> breaks if it evaluates to true, defaults to '1'.
8138B<b> I<subname> [I<condition>]
8139        Set breakpoint at first line of subroutine.
8140B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
8141B<b> B<load> I<filename> Set breakpoint on 'require'ing the given file.
8142B<b> B<postpone> I<subname> [I<condition>]
8143        Set breakpoint at first line of subroutine after
8144        it is compiled.
8145B<b> B<compile> I<subname>
8146        Stop after the subroutine is compiled.
8147B<B> [I<line>]    Delete the breakpoint for I<line>.
8148B<B> I<*>             Delete all breakpoints.
8149B<a> [I<line>] I<command>
8150        Set an action to be done before the I<line> is executed;
8151        I<line> defaults to the current execution line.
8152        Sequence is: check for breakpoint/watchpoint, print line
8153        if necessary, do action, prompt user if necessary,
8154        execute line.
8155B<a>        Does nothing
8156B<A> [I<line>]    Delete the action for I<line>.
8157B<A> I<*>             Delete all actions.
8158B<w> I<expr>        Add a global watch-expression.
8159B<w>             Does nothing
8160B<W> I<expr>        Delete a global watch-expression.
8161B<W> I<*>             Delete all watch-expressions.
8162B<V> [I<pkg> [I<vars>]]    List some (default all) variables in package (default current).
8163        Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
8164B<X> [I<vars>]    Same as \"B<V> I<currentpackage> [I<vars>]\".
8165B<x> I<expr>        Evals expression in list context, dumps the result.
8166B<m> I<expr>        Evals expression in list context, prints methods callable
8167        on the first element of the result.
8168B<m> I<class>        Prints methods callable via the given class.
8169B<M>        Show versions of loaded modules.
8170B<i> I<class>       Prints nested parents of given class.
8171B<e>         Display current thread id.
8172B<E>         Display all thread ids the current one will be identified: <n>.
8173B<y> [I<n> [I<Vars>]]   List lexicals in higher scope <n>.  Vars same as B<V>.
8174
8175B<<> ?            List Perl commands to run before each prompt.
8176B<<> I<expr>        Define Perl command to run before each prompt.
8177B<<<> I<expr>        Add to the list of Perl commands to run before each prompt.
8178B<< *>                Delete the list of perl commands to run before each prompt.
8179B<>> ?            List Perl commands to run after each prompt.
8180B<>> I<expr>        Define Perl command to run after each prompt.
8181B<>>B<>> I<expr>        Add to the list of Perl commands to run after each prompt.
8182B<>>B< *>        Delete the list of Perl commands to run after each prompt.
8183B<{> I<db_command>    Define debugger command to run before each prompt.
8184B<{> ?            List debugger commands to run before each prompt.
8185B<{{> I<db_command>    Add to the list of debugger commands to run before each prompt.
8186B<{ *>             Delete the list of debugger commands to run before each prompt.
8187B<$prc> I<number>    Redo a previous command (default previous command).
8188B<$prc> I<-number>    Redo number'th-to-last command.
8189B<$prc> I<pattern>    Redo last command that started with I<pattern>.
8190        See 'B<O> I<recallCommand>' too.
8191B<$psh$psh> I<cmd>      Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
8192      . (
8193        $rc eq $sh
8194        ? ""
8195        : "
8196B<$psh> [I<cmd>] Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")."
8197      ) . "
8198        See 'B<O> I<shellBang>' too.
8199B<source> I<file>     Execute I<file> containing debugger commands (may nest).
8200B<save> I<file>       Save current debugger session (actual history) to I<file>.
8201B<rerun>           Rerun session to current position.
8202B<rerun> I<n>         Rerun session to numbered command.
8203B<rerun> I<-n>        Rerun session to number'th-to-last command.
8204B<H> I<-number>    Display last number commands (default all).
8205B<H> I<*>          Delete complete history.
8206B<p> I<expr>        Same as \"I<print {DB::OUT} expr>\" in current package.
8207B<|>I<dbcmd>        Run debugger command, piping DB::OUT to current pager.
8208B<||>I<dbcmd>        Same as B<|>I<dbcmd> but DB::OUT is temporarily select()ed as well.
8209B<\=> [I<alias> I<value>]    Define a command alias, or list current aliases.
8210I<command>        Execute as a perl statement in current package.
8211B<R>        Poor man's restart of the debugger, some of debugger state
8212        and command-line options may be lost.
8213        Currently the following settings are preserved:
8214        history, breakpoints and actions, debugger B<O>ptions
8215        and the following command-line options: I<-w>, I<-I>, I<-e>.
8216
8217B<o> [I<opt>] ...    Set boolean option to true
8218B<o> [I<opt>B<?>]    Query options
8219B<o> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ...
8220        Set options.  Use quotes if spaces in value.
8221    I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
8222    I<pager>            program for output of \"|cmd\";
8223    I<tkRunning>            run Tk while prompting (with ReadLine);
8224    I<signalLevel> I<warnLevel> I<dieLevel>    level of verbosity;
8225    I<inhibit_exit>        Allows stepping off the end of the script.
8226    I<ImmediateStop>        Debugger should stop as early as possible.
8227    I<RemotePort>            Remote hostname:port for remote debugging
8228  The following options affect what happens with B<V>, B<X>, and B<x> commands:
8229    I<arrayDepth>, I<hashDepth>     print only first N elements ('' for all);
8230    I<compactDump>, I<veryCompact>     change style of array and hash dump;
8231    I<globPrint>             whether to print contents of globs;
8232    I<DumpDBFiles>         dump arrays holding debugged files;
8233    I<DumpPackages>         dump symbol tables of packages;
8234    I<DumpReused>             dump contents of \"reused\" addresses;
8235    I<quote>, I<HighBit>, I<undefPrint>     change style of string dump;
8236    I<bareStringify>         Do not print the overload-stringified value;
8237  Other options include:
8238    I<PrintRet>        affects printing of return value after B<r> command,
8239    I<frame>        affects printing messages on subroutine entry/exit.
8240    I<AutoTrace>    affects printing messages on possible breaking points.
8241    I<maxTraceLen>    gives max length of evals/args listed in stack trace.
8242    I<ornaments>     affects screen appearance of the command line.
8243    I<CreateTTY>     bits control attempts to create a new TTY on events:
8244            1: on fork()    2: debugger is started inside debugger
8245            4: on startup
8246    During startup options are initialized from \$ENV{PERLDB_OPTS}.
8247    You can put additional initialization options I<TTY>, I<noTTY>,
8248    I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
8249    B<R> after you set them).
8250
8251B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction.
8252B<h>        Summary of debugger commands.
8253B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
8254B<h h>        Long help for debugger commands
8255B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the
8256        named Perl I<manpage>, or on B<$doccmd> itself if omitted.
8257        Set B<\$DB::doccmd> to change viewer.
8258
8259Type '|h h' for a paged display if this was too hard to read.
8260
8261";    # Fix balance of vi % matching: }}}}
8262
8263    #  note: tabs in the following section are not-so-helpful
8264    $summary = <<"END_SUM";
8265I<List/search source lines:>               I<Control script execution:>
8266  B<l> [I<ln>|I<sub>]  List source code            B<T>           Stack trace
8267  B<-> or B<.>      List previous/current line  B<s> [I<expr>]    Single step [in expr]
8268  B<v> [I<line>]    View around line            B<n> [I<expr>]    Next, steps over subs
8269  B<f> I<filename>  View source in file         <B<CR>/B<Enter>>  Repeat last B<n> or B<s>
8270  B</>I<pattern>B</> B<?>I<patt>B<?>   Search forw/backw    B<r>           Return from subroutine
8271  B<M>           Show module versions        B<c> [I<ln>|I<sub>]  Continue until position
8272I<Debugger controls:>                        B<L>           List break/watch/actions
8273  B<o> [...]     Set debugger options        B<t> [I<n>] [I<expr>] Toggle trace [max depth] ][trace expr]
8274  B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
8275  B<$prc> [I<N>|I<pat>]   Redo a previous command     B<B> I<ln|*>      Delete a/all breakpoints
8276  B<H> [I<-num>]    Display last num commands   B<a> [I<ln>] I<cmd>  Do cmd before line
8277  B<=> [I<a> I<val>]   Define/list an alias        B<A> I<ln|*>      Delete a/all actions
8278  B<h> [I<db_cmd>]  Get help on command         B<w> I<expr>      Add a watch expression
8279  B<h h>         Complete help page          B<W> I<expr|*>    Delete a/all watch exprs
8280  B<|>[B<|>]I<db_cmd>  Send output to pager        B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
8281  B<q> or B<^D>     Quit                        B<R>           Attempt a restart
8282I<Data Examination:>     B<expr>     Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
8283  B<x>|B<m> I<expr>       Evals expr in list context, dumps the result or lists methods.
8284  B<p> I<expr>         Print expression (uses script's current package).
8285  B<S> [[B<!>]I<pat>]     List subroutine names [not] matching pattern
8286  B<V> [I<Pk> [I<Vars>]]  List Variables in Package.  Vars can be ~pattern or !pattern.
8287  B<X> [I<Vars>]       Same as \"B<V> I<current_package> [I<Vars>]\".  B<i> I<class> inheritance tree.
8288  B<y> [I<n> [I<Vars>]]   List lexicals in higher scope <n>.  Vars same as B<V>.
8289  B<e>     Display thread id     B<E> Display all thread ids.
8290For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
8291END_SUM
8292
8293    # ')}}; # Fix balance of vi % matching
8294
8295    # and this is really numb...
8296    $pre580_help = "
8297B<T>        Stack trace.
8298B<s> [I<expr>]    Single step [in I<expr>].
8299B<n> [I<expr>]    Next, steps over subroutine calls [in I<expr>].
8300B<CR>>        Repeat last B<n> or B<s> command.
8301B<r>        Return from current subroutine.
8302B<c> [I<line>|I<sub>]    Continue; optionally inserts a one-time-only breakpoint
8303        at the specified position.
8304B<l> I<min>B<+>I<incr>    List I<incr>+1 lines starting at I<min>.
8305B<l> I<min>B<->I<max>    List lines I<min> through I<max>.
8306B<l> I<line>        List single I<line>.
8307B<l> I<subname>    List first window of lines from subroutine.
8308B<l> I<\$var>        List first window of lines from subroutine referenced by I<\$var>.
8309B<l>        List next window of lines.
8310B<->        List previous window of lines.
8311B<w> [I<line>]    List window around I<line>.
8312B<.>        Return to the executed line.
8313B<f> I<filename>    Switch to viewing I<filename>. File must be already loaded.
8314        I<filename> may be either the full name of the file, or a regular
8315        expression matching the full file name:
8316        B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
8317        Evals (with saved bodies) are considered to be filenames:
8318        B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
8319        (in the order of execution).
8320B</>I<pattern>B</>    Search forwards for I<pattern>; final B</> is optional.
8321B<?>I<pattern>B<?>    Search backwards for I<pattern>; final B<?> is optional.
8322B<L>        List all breakpoints and actions.
8323B<S> [[B<!>]I<pattern>]    List subroutine names [not] matching I<pattern>.
8324B<t> [I<n>]       Toggle trace mode (to max I<n> levels below current stack depth) .
8325B<t> [I<n>] I<expr>        Trace through execution of I<expr>.
8326B<b> [I<line>] [I<condition>]
8327        Set breakpoint; I<line> defaults to the current execution line;
8328        I<condition> breaks if it evaluates to true, defaults to '1'.
8329B<b> I<subname> [I<condition>]
8330        Set breakpoint at first line of subroutine.
8331B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
8332B<b> B<load> I<filename> Set breakpoint on 'require'ing the given file.
8333B<b> B<postpone> I<subname> [I<condition>]
8334        Set breakpoint at first line of subroutine after
8335        it is compiled.
8336B<b> B<compile> I<subname>
8337        Stop after the subroutine is compiled.
8338B<d> [I<line>]    Delete the breakpoint for I<line>.
8339B<D>        Delete all breakpoints.
8340B<a> [I<line>] I<command>
8341        Set an action to be done before the I<line> is executed;
8342        I<line> defaults to the current execution line.
8343        Sequence is: check for breakpoint/watchpoint, print line
8344        if necessary, do action, prompt user if necessary,
8345        execute line.
8346B<a> [I<line>]    Delete the action for I<line>.
8347B<A>        Delete all actions.
8348B<W> I<expr>        Add a global watch-expression.
8349B<W>        Delete all watch-expressions.
8350B<V> [I<pkg> [I<vars>]]    List some (default all) variables in package (default current).
8351        Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
8352B<X> [I<vars>]    Same as \"B<V> I<currentpackage> [I<vars>]\".
8353B<x> I<expr>        Evals expression in list context, dumps the result.
8354B<m> I<expr>        Evals expression in list context, prints methods callable
8355        on the first element of the result.
8356B<m> I<class>        Prints methods callable via the given class.
8357
8358B<<> ?            List Perl commands to run before each prompt.
8359B<<> I<expr>        Define Perl command to run before each prompt.
8360B<<<> I<expr>        Add to the list of Perl commands to run before each prompt.
8361B<>> ?            List Perl commands to run after each prompt.
8362B<>> I<expr>        Define Perl command to run after each prompt.
8363B<>>B<>> I<expr>        Add to the list of Perl commands to run after each prompt.
8364B<{> I<db_command>    Define debugger command to run before each prompt.
8365B<{> ?            List debugger commands to run before each prompt.
8366B<{{> I<db_command>    Add to the list of debugger commands to run before each prompt.
8367B<$prc> I<number>    Redo a previous command (default previous command).
8368B<$prc> I<-number>    Redo number'th-to-last command.
8369B<$prc> I<pattern>    Redo last command that started with I<pattern>.
8370        See 'B<O> I<recallCommand>' too.
8371B<$psh$psh> I<cmd>      Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
8372      . (
8373        $rc eq $sh
8374        ? ""
8375        : "
8376B<$psh> [I<cmd>]     Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")."
8377      ) . "
8378        See 'B<O> I<shellBang>' too.
8379B<source> I<file>        Execute I<file> containing debugger commands (may nest).
8380B<H> I<-number>    Display last number commands (default all).
8381B<p> I<expr>        Same as \"I<print {DB::OUT} expr>\" in current package.
8382B<|>I<dbcmd>        Run debugger command, piping DB::OUT to current pager.
8383B<||>I<dbcmd>        Same as B<|>I<dbcmd> but DB::OUT is temporarilly select()ed as well.
8384B<\=> [I<alias> I<value>]    Define a command alias, or list current aliases.
8385I<command>        Execute as a perl statement in current package.
8386B<v>        Show versions of loaded modules.
8387B<R>        Poor man's restart of the debugger, some of debugger state
8388        and command-line options may be lost.
8389        Currently the following settings are preserved:
8390        history, breakpoints and actions, debugger B<O>ptions
8391        and the following command-line options: I<-w>, I<-I>, I<-e>.
8392
8393B<O> [I<opt>] ...    Set boolean option to true
8394B<O> [I<opt>B<?>]    Query options
8395B<O> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ...
8396        Set options.  Use quotes if spaces in value.
8397    I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
8398    I<pager>            program for output of \"|cmd\";
8399    I<tkRunning>            run Tk while prompting (with ReadLine);
8400    I<signalLevel> I<warnLevel> I<dieLevel>    level of verbosity;
8401    I<inhibit_exit>        Allows stepping off the end of the script.
8402    I<ImmediateStop>        Debugger should stop as early as possible.
8403    I<RemotePort>            Remote hostname:port for remote debugging
8404  The following options affect what happens with B<V>, B<X>, and B<x> commands:
8405    I<arrayDepth>, I<hashDepth>     print only first N elements ('' for all);
8406    I<compactDump>, I<veryCompact>     change style of array and hash dump;
8407    I<globPrint>             whether to print contents of globs;
8408    I<DumpDBFiles>         dump arrays holding debugged files;
8409    I<DumpPackages>         dump symbol tables of packages;
8410    I<DumpReused>             dump contents of \"reused\" addresses;
8411    I<quote>, I<HighBit>, I<undefPrint>     change style of string dump;
8412    I<bareStringify>         Do not print the overload-stringified value;
8413  Other options include:
8414    I<PrintRet>        affects printing of return value after B<r> command,
8415    I<frame>        affects printing messages on subroutine entry/exit.
8416    I<AutoTrace>    affects printing messages on possible breaking points.
8417    I<maxTraceLen>    gives max length of evals/args listed in stack trace.
8418    I<ornaments>     affects screen appearance of the command line.
8419    I<CreateTTY>     bits control attempts to create a new TTY on events:
8420            1: on fork()    2: debugger is started inside debugger
8421            4: on startup
8422    During startup options are initialized from \$ENV{PERLDB_OPTS}.
8423    You can put additional initialization options I<TTY>, I<noTTY>,
8424    I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
8425    B<R> after you set them).
8426
8427B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction.
8428B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
8429B<h h>        Summary of debugger commands.
8430B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the
8431        named Perl I<manpage>, or on B<$doccmd> itself if omitted.
8432        Set B<\$DB::doccmd> to change viewer.
8433
8434Type '|h' for a paged display if this was too hard to read.
8435
8436";    # Fix balance of vi % matching: }}}}
8437
8438    #  note: tabs in the following section are not-so-helpful
8439    $pre580_summary = <<"END_SUM";
8440I<List/search source lines:>               I<Control script execution:>
8441  B<l> [I<ln>|I<sub>]  List source code            B<T>           Stack trace
8442  B<-> or B<.>      List previous/current line  B<s> [I<expr>]    Single step [in expr]
8443  B<w> [I<line>]    List around line            B<n> [I<expr>]    Next, steps over subs
8444  B<f> I<filename>  View source in file         <B<CR>/B<Enter>>  Repeat last B<n> or B<s>
8445  B</>I<pattern>B</> B<?>I<patt>B<?>   Search forw/backw    B<r>           Return from subroutine
8446  B<v>           Show versions of modules    B<c> [I<ln>|I<sub>]  Continue until position
8447I<Debugger controls:>                        B<L>           List break/watch/actions
8448  B<O> [...]     Set debugger options        B<t> [I<expr>]    Toggle trace [trace expr]
8449  B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
8450  B<$prc> [I<N>|I<pat>]   Redo a previous command     B<d> [I<ln>] or B<D> Delete a/all breakpoints
8451  B<H> [I<-num>]    Display last num commands   B<a> [I<ln>] I<cmd>  Do cmd before line
8452  B<=> [I<a> I<val>]   Define/list an alias        B<W> I<expr>      Add a watch expression
8453  B<h> [I<db_cmd>]  Get help on command         B<A> or B<W>      Delete all actions/watch
8454  B<|>[B<|>]I<db_cmd>  Send output to pager        B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
8455  B<q> or B<^D>     Quit                        B<R>           Attempt a restart
8456I<Data Examination:>     B<expr>     Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
8457  B<x>|B<m> I<expr>       Evals expr in list context, dumps the result or lists methods.
8458  B<p> I<expr>         Print expression (uses script's current package).
8459  B<S> [[B<!>]I<pat>]     List subroutine names [not] matching pattern
8460  B<V> [I<Pk> [I<Vars>]]  List Variables in Package.  Vars can be ~pattern or !pattern.
8461  B<X> [I<Vars>]       Same as \"B<V> I<current_package> [I<Vars>]\".
8462  B<y> [I<n> [I<Vars>]]   List lexicals in higher scope <n>.  Vars same as B<V>.
8463For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
8464END_SUM
8465
8466    # ')}}; # Fix balance of vi % matching
8467
8468} ## end sub sethelp
8469
8470=head2 C<print_help()>
8471
8472Most of what C<print_help> does is just text formatting. It finds the
8473C<B> and C<I> ornaments, cleans them off, and substitutes the proper
8474terminal control characters to simulate them (courtesy of
8475C<Term::ReadLine::TermCap>).
8476
8477=cut
8478
8479sub print_help {
8480    my $help_str = shift;
8481
8482    # Restore proper alignment destroyed by eeevil I<> and B<>
8483    # ornaments: A pox on both their houses!
8484    #
8485    # A help command will have everything up to and including
8486    # the first tab sequence padded into a field 16 (or if indented 20)
8487    # wide.  If it's wider than that, an extra space will be added.
8488    $help_str =~ s{
8489        ^                       # only matters at start of line
8490          ( \ {4} | \t )*       # some subcommands are indented
8491          ( < ?                 # so <CR> works
8492            [BI] < [^\t\n] + )  # find an eeevil ornament
8493          ( \t+ )               # original separation, discarded
8494          ( .* )                # this will now start (no earlier) than
8495                                # column 16
8496    } {
8497        my($leadwhite, $command, $midwhite, $text) = ($1, $2, $3, $4);
8498        my $clean = $command;
8499        $clean =~ s/[BI]<([^>]*)>/$1/g;
8500
8501        # replace with this whole string:
8502        ($leadwhite ? " " x 4 : "")
8503      . $command
8504      . ((" " x (16 + ($leadwhite ? 4 : 0) - length($clean))) || " ")
8505      . $text;
8506
8507    }mgex;
8508
8509    $help_str =~ s{                          # handle bold ornaments
8510       B < ( [^>] + | > ) >
8511    } {
8512          $Term::ReadLine::TermCap::rl_term_set[2]
8513        . $1
8514        . $Term::ReadLine::TermCap::rl_term_set[3]
8515    }gex;
8516
8517    $help_str =~ s{                         # handle italic ornaments
8518       I < ( [^>] + | > ) >
8519    } {
8520          $Term::ReadLine::TermCap::rl_term_set[0]
8521        . $1
8522        . $Term::ReadLine::TermCap::rl_term_set[1]
8523    }gex;
8524
8525    local $\ = '';
8526    print {$OUT} $help_str;
8527
8528    return;
8529} ## end sub print_help
8530
8531=head2 C<fix_less>
8532
8533This routine does a lot of gyrations to be sure that the pager is C<less>.
8534It checks for C<less> masquerading as C<more> and records the result in
8535C<$fixed_less> so we don't have to go through doing the stats again.
8536
8537=cut
8538
8539use vars qw($fixed_less);
8540
8541sub _calc_is_less {
8542    if ($pager =~ /\bless\b/)
8543    {
8544        return 1;
8545    }
8546    elsif ($pager =~ /\bmore\b/)
8547    {
8548        # Nope, set to more. See what's out there.
8549        my @st_more = stat('/usr/bin/more');
8550        my @st_less = stat('/usr/bin/less');
8551
8552        # is it really less, pretending to be more?
8553        return (
8554            @st_more
8555            && @st_less
8556            && $st_more[0] == $st_less[0]
8557            && $st_more[1] == $st_less[1]
8558        );
8559    }
8560    else {
8561        return;
8562    }
8563}
8564
8565sub fix_less {
8566
8567    # We already know if this is set.
8568    return if $fixed_less;
8569
8570    # changes environment!
8571    # 'r' added so we don't do (slow) stats again.
8572    $fixed_less = 1 if _calc_is_less();
8573
8574    return;
8575} ## end sub fix_less
8576
8577=head1 DIE AND WARN MANAGEMENT
8578
8579=head2 C<diesignal>
8580
8581C<diesignal> is a just-drop-dead C<die> handler. It's most useful when trying
8582to debug a debugger problem.
8583
8584It does its best to report the error that occurred, and then forces the
8585program, debugger, and everything to die.
8586
8587=cut
8588
8589sub diesignal {
8590
8591    # No entry/exit messages.
8592    local $frame = 0;
8593
8594    # No return value prints.
8595    local $doret = -2;
8596
8597    # set the abort signal handling to the default (just terminate).
8598    $SIG{'ABRT'} = 'DEFAULT';
8599
8600    # If we enter the signal handler recursively, kill myself with an
8601    # abort signal (so we just terminate).
8602    kill 'ABRT', $$ if $panic++;
8603
8604    # If we can show detailed info, do so.
8605    if ( defined &Carp::longmess ) {
8606
8607        # Don't recursively enter the warn handler, since we're carping.
8608        local $SIG{__WARN__} = '';
8609
8610        # Skip two levels before reporting traceback: we're skipping
8611        # mydie and confess.
8612        local $Carp::CarpLevel = 2;    # mydie + confess
8613
8614        # Tell us all about it.
8615        _db_warn( Carp::longmess("Signal @_") );
8616    }
8617
8618    # No Carp. Tell us about the signal as best we can.
8619    else {
8620        local $\ = '';
8621        print $DB::OUT "Got signal @_\n";
8622    }
8623
8624    # Drop dead.
8625    kill 'ABRT', $$;
8626} ## end sub diesignal
8627
8628=head2 C<dbwarn>
8629
8630The debugger's own default C<$SIG{__WARN__}> handler. We load C<Carp> to
8631be able to get a stack trace, and output the warning message vi C<DB::dbwarn()>.
8632
8633=cut
8634
8635sub dbwarn {
8636
8637    # No entry/exit trace.
8638    local $frame = 0;
8639
8640    # No return value printing.
8641    local $doret = -2;
8642
8643    # Turn off warn and die handling to prevent recursive entries to this
8644    # routine.
8645    local $SIG{__WARN__} = '';
8646    local $SIG{__DIE__}  = '';
8647
8648    # Load Carp if we can. If $^S is false (current thing being compiled isn't
8649    # done yet), we may not be able to do a require.
8650    eval { require Carp }
8651      if defined $^S;    # If error/warning during compilation,
8652                         # require may be broken.
8653
8654    # Use the core warn() unless Carp loaded OK.
8655    CORE::warn( @_,
8656        "\nCannot print stack trace, load with -MCarp option to see stack" ),
8657      return
8658      unless defined &Carp::longmess;
8659
8660    # Save the current values of $single and $trace, and then turn them off.
8661    my ( $mysingle, $mytrace ) = ( $single, $trace );
8662    $single = 0;
8663    $trace  = 0;
8664
8665    # We can call Carp::longmess without its being "debugged" (which we
8666    # don't want - we just want to use it!). Capture this for later.
8667    my $mess = Carp::longmess(@_);
8668
8669    # Restore $single and $trace to their original values.
8670    ( $single, $trace ) = ( $mysingle, $mytrace );
8671
8672    # Use the debugger's own special way of printing warnings to print
8673    # the stack trace message.
8674    _db_warn($mess);
8675} ## end sub dbwarn
8676
8677=head2 C<dbdie>
8678
8679The debugger's own C<$SIG{__DIE__}> handler. Handles providing a stack trace
8680by loading C<Carp> and calling C<Carp::longmess()> to get it. We turn off
8681single stepping and tracing during the call to C<Carp::longmess> to avoid
8682debugging it - we just want to use it.
8683
8684If C<dieLevel> is zero, we let the program being debugged handle the
8685exceptions. If it's 1, you get backtraces for any exception. If it's 2,
8686the debugger takes over all exception handling, printing a backtrace and
8687displaying the exception via its C<dbwarn()> routine.
8688
8689=cut
8690
8691sub dbdie {
8692    local $frame         = 0;
8693    local $doret         = -2;
8694    local $SIG{__DIE__}  = '';
8695    local $SIG{__WARN__} = '';
8696    if ( $dieLevel > 2 ) {
8697        local $SIG{__WARN__} = \&dbwarn;
8698        _db_warn(@_);    # Yell no matter what
8699        return;
8700    }
8701    if ( $dieLevel < 2 ) {
8702        die @_ if $^S;    # in eval propagate
8703    }
8704
8705    # The code used to check $^S to see if compilation of the current thing
8706    # hadn't finished. We don't do it anymore, figuring eval is pretty stable.
8707    eval { require Carp };
8708
8709    die( @_,
8710        "\nCannot print stack trace, load with -MCarp option to see stack" )
8711      unless defined &Carp::longmess;
8712
8713    # We do not want to debug this chunk (automatic disabling works
8714    # inside DB::DB, but not in Carp). Save $single and $trace, turn them off,
8715    # get the stack trace from Carp::longmess (if possible), restore $signal
8716    # and $trace, and then die with the stack trace.
8717    my ( $mysingle, $mytrace ) = ( $single, $trace );
8718    $single = 0;
8719    $trace  = 0;
8720    my $mess = "@_";
8721    {
8722
8723        package Carp;    # Do not include us in the list
8724        eval { $mess = Carp::longmess(@_); };
8725    }
8726    ( $single, $trace ) = ( $mysingle, $mytrace );
8727    die $mess;
8728} ## end sub dbdie
8729
8730=head2 C<warnlevel()>
8731
8732Set the C<$DB::warnLevel> variable that stores the value of the
8733C<warnLevel> option. Calling C<warnLevel()> with a positive value
8734results in the debugger taking over all warning handlers. Setting
8735C<warnLevel> to zero leaves any warning handlers set up by the program
8736being debugged in place.
8737
8738=cut
8739
8740sub warnLevel {
8741    if (@_) {
8742        my $prevwarn = $SIG{__WARN__} unless $warnLevel;
8743        $warnLevel = shift;
8744        if ($warnLevel) {
8745            $SIG{__WARN__} = \&DB::dbwarn;
8746        }
8747        elsif ($prevwarn) {
8748            $SIG{__WARN__} = $prevwarn;
8749        } else {
8750            undef $SIG{__WARN__};
8751        }
8752    } ## end if (@_)
8753    $warnLevel;
8754} ## end sub warnLevel
8755
8756=head2 C<dielevel>
8757
8758Similar to C<warnLevel>. Non-zero values for C<dieLevel> result in the
8759C<DB::dbdie()> function overriding any other C<die()> handler. Setting it to
8760zero lets you use your own C<die()> handler.
8761
8762=cut
8763
8764sub dieLevel {
8765    local $\ = '';
8766    if (@_) {
8767        my $prevdie = $SIG{__DIE__} unless $dieLevel;
8768        $dieLevel = shift;
8769        if ($dieLevel) {
8770
8771            # Always set it to dbdie() for non-zero values.
8772            $SIG{__DIE__} = \&DB::dbdie;    # if $dieLevel < 2;
8773
8774            # No longer exists, so don't try  to use it.
8775            #$SIG{__DIE__} = \&DB::diehard if $dieLevel >= 2;
8776
8777            # If we've finished initialization, mention that stack dumps
8778            # are enabled, If dieLevel is 1, we won't stack dump if we die
8779            # in an eval().
8780            print $OUT "Stack dump during die enabled",
8781              ( $dieLevel == 1 ? " outside of evals" : "" ), ".\n"
8782              if $I_m_init;
8783
8784            # XXX This is probably obsolete, given that diehard() is gone.
8785            print $OUT "Dump printed too.\n" if $dieLevel > 2;
8786        } ## end if ($dieLevel)
8787
8788        # Put the old one back if there was one.
8789        elsif ($prevdie) {
8790            $SIG{__DIE__} = $prevdie;
8791            print $OUT "Default die handler restored.\n";
8792        } else {
8793            undef $SIG{__DIE__};
8794            print $OUT "Die handler removed.\n";
8795        }
8796    } ## end if (@_)
8797    $dieLevel;
8798} ## end sub dieLevel
8799
8800=head2 C<signalLevel>
8801
8802Number three in a series: set C<signalLevel> to zero to keep your own
8803signal handler for C<SIGSEGV> and/or C<SIGBUS>. Otherwise, the debugger
8804takes over and handles them with C<DB::diesignal()>.
8805
8806=cut
8807
8808sub signalLevel {
8809    if (@_) {
8810        my $prevsegv = $SIG{SEGV} unless $signalLevel;
8811        my $prevbus  = $SIG{BUS}  unless $signalLevel;
8812        $signalLevel = shift;
8813        if ($signalLevel) {
8814            $SIG{SEGV} = \&DB::diesignal;
8815            $SIG{BUS}  = \&DB::diesignal;
8816        }
8817        else {
8818            $SIG{SEGV} = $prevsegv;
8819            $SIG{BUS}  = $prevbus;
8820        }
8821    } ## end if (@_)
8822    $signalLevel;
8823} ## end sub signalLevel
8824
8825=head1 SUBROUTINE DECODING SUPPORT
8826
8827These subroutines are used during the C<x> and C<X> commands to try to
8828produce as much information as possible about a code reference. They use
8829L<Devel::Peek> to try to find the glob in which this code reference lives
8830(if it does) - this allows us to actually code references which correspond
8831to named subroutines (including those aliased via glob assignment).
8832
8833=head2 C<CvGV_name()>
8834
8835Wrapper for C<CvGV_name_or_bust>; tries to get the name of a reference
8836via that routine. If this fails, return the reference again (when the
8837reference is stringified, it'll come out as C<SOMETHING(0x...)>).
8838
8839=cut
8840
8841sub CvGV_name {
8842    my $in   = shift;
8843    my $name = CvGV_name_or_bust($in);
8844    defined $name ? $name : $in;
8845}
8846
8847=head2 C<CvGV_name_or_bust> I<coderef>
8848
8849Calls L<Devel::Peek> to try to find the glob the ref lives in; returns
8850C<undef> if L<Devel::Peek> can't be loaded, or if C<Devel::Peek::CvGV> can't
8851find a glob for this ref.
8852
8853Returns C<< I<package>::I<glob name> >> if the code ref is found in a glob.
8854
8855=cut
8856
8857use vars qw($skipCvGV);
8858
8859sub CvGV_name_or_bust {
8860    my $in = shift;
8861    return if $skipCvGV;    # Backdoor to avoid problems if XS broken...
8862    return unless ref $in;
8863    $in = \&$in;            # Hard reference...
8864    eval { _DB__use_full_path(sub { require Devel::Peek; 1; }); } or return;
8865    my $gv = Devel::Peek::CvGV($in) or return;
8866    *$gv{PACKAGE} . '::' . *$gv{NAME};
8867} ## end sub CvGV_name_or_bust
8868
8869=head2 C<find_sub>
8870
8871A utility routine used in various places; finds the file where a subroutine
8872was defined, and returns that filename and a line-number range.
8873
8874Tries to use C<@sub> first; if it can't find it there, it tries building a
8875reference to the subroutine and uses C<CvGV_name_or_bust> to locate it,
8876loading it into C<@sub> as a side effect (XXX I think). If it can't find it
8877this way, it brute-force searches C<%sub>, checking for identical references.
8878
8879=cut
8880
8881sub _find_sub_helper {
8882    my $subr = shift;
8883
8884    return unless defined &$subr;
8885    my $name = CvGV_name_or_bust($subr);
8886    my $data;
8887    $data = $sub{$name} if defined $name;
8888    return $data if defined $data;
8889
8890    # Old stupid way...
8891    $subr = \&$subr;    # Hard reference
8892    my $s;
8893    for ( keys %sub ) {
8894        $s = $_, last if $subr eq \&$_;
8895    }
8896    if ($s)
8897    {
8898        return $sub{$s};
8899    }
8900    else
8901    {
8902        return;
8903    }
8904
8905}
8906
8907sub find_sub {
8908    my $subr = shift;
8909    return ( $sub{$subr} || _find_sub_helper($subr) );
8910} ## end sub find_sub
8911
8912=head2 C<methods>
8913
8914A subroutine that uses the utility function C<methods_via> to find all the
8915methods in the class corresponding to the current reference and in
8916C<UNIVERSAL>.
8917
8918=cut
8919
8920use vars qw(%seen);
8921
8922sub methods {
8923
8924    # Figure out the class - either this is the class or it's a reference
8925    # to something blessed into that class.
8926    my $class = shift;
8927    $class = ref $class if ref $class;
8928
8929    local %seen;
8930
8931    # Show the methods that this class has.
8932    methods_via( $class, '', 1 );
8933
8934    # Show the methods that UNIVERSAL has.
8935    methods_via( 'UNIVERSAL', 'UNIVERSAL', 0 );
8936} ## end sub methods
8937
8938=head2 C<methods_via($class, $prefix, $crawl_upward)>
8939
8940C<methods_via> does the work of crawling up the C<@ISA> tree and reporting
8941all the parent class methods. C<$class> is the name of the next class to
8942try; C<$prefix> is the message prefix, which gets built up as we go up the
8943C<@ISA> tree to show parentage; C<$crawl_upward> is 1 if we should try to go
8944higher in the C<@ISA> tree, 0 if we should stop.
8945
8946=cut
8947
8948sub methods_via {
8949
8950    # If we've processed this class already, just quit.
8951    my $class = shift;
8952    return if $seen{$class}++;
8953
8954    # This is a package that is contributing the methods we're about to print.
8955    my $prefix  = shift;
8956    my $prepend = $prefix ? "via $prefix: " : '';
8957    my @to_print;
8958
8959    # Extract from all the symbols in this class.
8960    my $class_ref = do { no strict "refs"; \%{$class . '::'} };
8961    while (my ($name, $glob) = each %$class_ref) {
8962        # references directly in the symbol table are Proxy Constant
8963        # Subroutines, and are by their very nature defined
8964        # Otherwise, check if the thing is a typeglob, and if it is, it decays
8965        # to a subroutine reference, which can be tested by defined.
8966        # $glob might also be the value -1  (from sub foo;)
8967        # or (say) '$$' (from sub foo ($$);)
8968        # \$glob will be SCALAR in both cases.
8969        if ((ref $glob || ($glob && ref \$glob eq 'GLOB' && defined &$glob))
8970            && !$seen{$name}++) {
8971            push @to_print, "$prepend$name\n";
8972        }
8973    }
8974
8975    {
8976        local $\ = '';
8977        local $, = '';
8978        print $DB::OUT $_ foreach sort @to_print;
8979    }
8980
8981    # If the $crawl_upward argument is false, just quit here.
8982    return unless shift;
8983
8984    # $crawl_upward true: keep going up the tree.
8985    # Find all the classes this one is a subclass of.
8986    my $class_ISA_ref = do { no strict "refs"; \@{"${class}::ISA"} };
8987    for my $name ( @$class_ISA_ref ) {
8988
8989        # Set up the new prefix.
8990        $prepend = $prefix ? $prefix . " -> $name" : $name;
8991
8992        # Crawl up the tree and keep trying to crawl up.
8993        methods_via( $name, $prepend, 1 );
8994    }
8995} ## end sub methods_via
8996
8997=head2 C<setman> - figure out which command to use to show documentation
8998
8999Just checks the contents of C<$^O> and sets the C<$doccmd> global accordingly.
9000
9001=cut
9002
9003sub setman {
9004    $doccmd = $^O !~ /^(?:MSWin32|VMS|os2|amigaos|riscos)\z/s
9005      ? "man"         # O Happy Day!
9006      : "perldoc";    # Alas, poor unfortunates
9007} ## end sub setman
9008
9009=head2 C<runman> - run the appropriate command to show documentation
9010
9011Accepts a man page name; runs the appropriate command to display it (set up
9012during debugger initialization). Uses C<_db_system()> to avoid mucking up the
9013program's STDIN and STDOUT.
9014
9015=cut
9016
9017sub runman {
9018    my $page = shift;
9019    unless ($page) {
9020        _db_system("$doccmd $doccmd");
9021        return;
9022    }
9023
9024    # this way user can override, like with $doccmd="man -Mwhatever"
9025    # or even just "man " to disable the path check.
9026    if ( $doccmd ne 'man' ) {
9027        _db_system("$doccmd $page");
9028        return;
9029    }
9030
9031    $page = 'perl' if lc($page) eq 'help';
9032
9033    require Config;
9034    my $man1dir = $Config::Config{man1direxp};
9035    my $man3dir = $Config::Config{man3direxp};
9036    for ( $man1dir, $man3dir ) { s#/[^/]*\z## if /\S/ }
9037    my $manpath = '';
9038    $manpath .= "$man1dir:" if $man1dir =~ /\S/;
9039    $manpath .= "$man3dir:" if $man3dir =~ /\S/ && $man1dir ne $man3dir;
9040    chop $manpath if $manpath;
9041
9042    # harmless if missing, I figure
9043    local $ENV{MANPATH} = $manpath if $manpath;
9044    my $nopathopt = $^O =~ /dunno what goes here/;
9045    if (
9046        CORE::system(
9047            $doccmd,
9048
9049            # I just *know* there are men without -M
9050            ( ( $manpath && !$nopathopt ) ? ( "-M", $manpath ) : () ),
9051            split ' ', $page
9052        )
9053      )
9054    {
9055        unless ( $page =~ /^perl\w/ ) {
9056            # Previously the debugger contained a list which it slurped in,
9057            # listing the known "perl" manpages. However, it was out of date,
9058            # with errors both of omission and inclusion. This approach is
9059            # considerably less complex. The failure mode on a butchered
9060            # install is simply that the user has to run man or perldoc
9061            # "manually" with the full manpage name.
9062
9063            # There is a list of $^O values in installperl to determine whether
9064            # the directory is 'pods' or 'pod'. However, we can avoid tight
9065            # coupling to that by simply checking the "non-standard" 'pods'
9066            # first.
9067            my $pods = "$Config::Config{privlibexp}/pods";
9068            $pods = "$Config::Config{privlibexp}/pod"
9069                unless -d $pods;
9070            if (-f "$pods/perl$page.pod") {
9071                CORE::system( $doccmd,
9072                    ( ( $manpath && !$nopathopt ) ? ( "-M", $manpath ) : () ),
9073                    "perl$page" );
9074            }
9075        }
9076    } ## end if (CORE::system($doccmd...
9077} ## end sub runman
9078
9079#use Carp;                          # This did break, left for debugging
9080
9081=head1 DEBUGGER INITIALIZATION - THE SECOND BEGIN BLOCK
9082
9083Because of the way the debugger interface to the Perl core is designed, any
9084debugger package globals that C<DB::sub()> requires have to be defined before
9085any subroutines can be called. These are defined in the second C<BEGIN> block.
9086
9087This block sets things up so that (basically) the world is sane
9088before the debugger starts executing. We set up various variables that the
9089debugger has to have set up before the Perl core starts running:
9090
9091=over 4
9092
9093=item *
9094
9095The debugger's own filehandles (copies of STD and STDOUT for now).
9096
9097=item *
9098
9099Characters for shell escapes, the recall command, and the history command.
9100
9101=item *
9102
9103The maximum recursion depth.
9104
9105=item *
9106
9107The size of a C<w> command's window.
9108
9109=item *
9110
9111The before-this-line context to be printed in a C<v> (view a window around this line) command.
9112
9113=item *
9114
9115The fact that we're not in a sub at all right now.
9116
9117=item *
9118
9119The default SIGINT handler for the debugger.
9120
9121=item *
9122
9123The appropriate value of the flag in C<$^D> that says the debugger is running
9124
9125=item *
9126
9127The current debugger recursion level
9128
9129=item *
9130
9131The list of postponed items and the C<$single> stack (XXX define this)
9132
9133=item *
9134
9135That we want no return values and no subroutine entry/exit trace.
9136
9137=back
9138
9139=cut
9140
9141# The following BEGIN is very handy if debugger goes havoc, debugging debugger?
9142
9143use vars qw($db_stop);
9144
9145BEGIN {    # This does not compile, alas. (XXX eh?)
9146    $IN  = \*STDIN;     # For bugs before DB::OUT has been opened
9147    $OUT = \*STDERR;    # For errors before DB::OUT has been opened
9148
9149    # Define characters used by command parsing.
9150    $sh       = '!';      # Shell escape (does not work)
9151    $rc       = ',';      # Recall command (does not work)
9152    @hist     = ('?');    # Show history (does not work)
9153    @truehist = ();       # Can be saved for replay (per session)
9154
9155    # This defines the point at which you get the 'deep recursion'
9156    # warning. It MUST be defined or the debugger will not load.
9157    $deep = 1000;
9158
9159    # Number of lines around the current one that are shown in the
9160    # 'w' command.
9161    $window = 10;
9162
9163    # How much before-the-current-line context the 'v' command should
9164    # use in calculating the start of the window it will display.
9165    $preview = 3;
9166
9167    # We're not in any sub yet, but we need this to be a defined value.
9168    $sub = '';
9169
9170    # Set up the debugger's interrupt handler. It simply sets a flag
9171    # ($signal) that DB::DB() will check before each command is executed.
9172    $SIG{INT} = \&DB::catch;
9173
9174    # The following lines supposedly, if uncommented, allow the debugger to
9175    # debug itself. Perhaps we can try that someday.
9176    # This may be enabled to debug debugger:
9177    #$warnLevel = 1 unless defined $warnLevel;
9178    #$dieLevel = 1 unless defined $dieLevel;
9179    #$signalLevel = 1 unless defined $signalLevel;
9180
9181    # This is the flag that says "a debugger is running, please call
9182    # DB::DB and DB::sub". We will turn it on forcibly before we try to
9183    # execute anything in the user's context, because we always want to
9184    # get control back.
9185    $db_stop = 0;          # Compiler warning ...
9186    $db_stop = 1 << 30;    # ... because this is only used in an eval() later.
9187
9188    # This variable records how many levels we're nested in debugging.
9189    # Used in the debugger prompt, and in determining whether it's all over or
9190    # not.
9191    $level = 0;            # Level of recursive debugging
9192
9193    # "Triggers bug (?) in perl if we postpone this until runtime."
9194    # XXX No details on this yet, or whether we should fix the bug instead
9195    # of work around it. Stay tuned.
9196    @stack = (0);
9197
9198    # Used to track the current stack depth using the auto-stacked-variable
9199    # trick.
9200    $stack_depth = 0;      # Localized repeatedly; simple way to track $#stack
9201
9202    # Don't print return values on exiting a subroutine.
9203    $doret = -2;
9204
9205    # No extry/exit tracing.
9206    $frame = 0;
9207
9208} ## end BEGIN
9209
9210BEGIN { $^W = $ini_warn; }    # Switch warnings back
9211
9212=head1 READLINE SUPPORT - COMPLETION FUNCTION
9213
9214=head2 db_complete
9215
9216C<readline> support - adds command completion to basic C<readline>.
9217
9218Returns a list of possible completions to C<readline> when invoked. C<readline>
9219will print the longest common substring following the text already entered.
9220
9221If there is only a single possible completion, C<readline> will use it in full.
9222
9223This code uses C<map> and C<grep> heavily to create lists of possible
9224completion. Think LISP in this section.
9225
9226=cut
9227
9228sub db_complete {
9229
9230    # Specific code for b c l V m f O, &blah, $blah, @blah, %blah
9231    # $text is the text to be completed.
9232    # $line is the incoming line typed by the user.
9233    # $start is the start of the text to be completed in the incoming line.
9234    my ( $text, $line, $start ) = @_;
9235
9236    # Save the initial text.
9237    # The search pattern is current package, ::, extract the next qualifier
9238    # Prefix and pack are set to undef.
9239    my ( $itext, $search, $prefix, $pack ) =
9240      ( $text, "^\Q${package}::\E([^:]+)\$" );
9241
9242=head3 C<b postpone|compile>
9243
9244=over 4
9245
9246=item *
9247
9248Find all the subroutines that might match in this package
9249
9250=item *
9251
9252Add C<postpone>, C<load>, and C<compile> as possibles (we may be completing the keyword itself)
9253
9254=item *
9255
9256Include all the rest of the subs that are known
9257
9258=item *
9259
9260C<grep> out the ones that match the text we have so far
9261
9262=item *
9263
9264Return this as the list of possible completions
9265
9266=back
9267
9268=cut
9269
9270    return sort grep /^\Q$text/, ( keys %sub ),
9271      qw(postpone load compile),    # subroutines
9272      ( map { /$search/ ? ($1) : () } keys %sub )
9273      if ( substr $line, 0, $start ) =~ /^\|*[blc]\s+((postpone|compile)\s+)?$/;
9274
9275=head3 C<b load>
9276
9277Get all the possible files from C<@INC> as it currently stands and
9278select the ones that match the text so far.
9279
9280=cut
9281
9282    return sort grep /^\Q$text/, values %INC    # files
9283      if ( substr $line, 0, $start ) =~ /^\|*b\s+load\s+$/;
9284
9285=head3  C<V> (list variable) and C<m> (list modules)
9286
9287There are two entry points for these commands:
9288
9289=head4 Unqualified package names
9290
9291Get the top-level packages and grab everything that matches the text
9292so far. For each match, recursively complete the partial packages to
9293get all possible matching packages. Return this sorted list.
9294
9295=cut
9296
9297    return sort map { ( $_, db_complete( $_ . "::", "V ", 2 ) ) }
9298      grep /^\Q$text/, map { /^(.*)::$/ ? ($1) : () } keys %::    # top-packages
9299      if ( substr $line, 0, $start ) =~ /^\|*[Vm]\s+$/ and $text =~ /^\w*$/;
9300
9301=head4 Qualified package names
9302
9303Take a partially-qualified package and find all subpackages for it
9304by getting all the subpackages for the package so far, matching all
9305the subpackages against the text, and discarding all of them which
9306start with 'main::'. Return this list.
9307
9308=cut
9309
9310    return sort map { ( $_, db_complete( $_ . "::", "V ", 2 ) ) }
9311      grep !/^main::/, grep /^\Q$text/,
9312      map { /^(.*)::$/ ? ( $prefix . "::$1" ) : () }
9313      do { no strict 'refs'; keys %{ $prefix . '::' } }
9314      if ( substr $line, 0, $start ) =~ /^\|*[Vm]\s+$/
9315      and $text =~ /^(.*[^:])::?(\w*)$/
9316      and $prefix = $1;
9317
9318=head3 C<f> - switch files
9319
9320Here, we want to get a fully-qualified filename for the C<f> command.
9321Possibilities are:
9322
9323=over 4
9324
9325=item 1. The original source file itself
9326
9327=item 2. A file from C<@INC>
9328
9329=item 3. An C<eval> (the debugger gets a C<(eval N)> fake file for each C<eval>).
9330
9331=back
9332
9333=cut
9334
9335    if ( $line =~ /^\|*f\s+(.*)/ ) {    # Loaded files
9336           # We might possibly want to switch to an eval (which has a "filename"
9337           # like '(eval 9)'), so we may need to clean up the completion text
9338           # before proceeding.
9339        $prefix = length($1) - length($text);
9340        $text   = $1;
9341
9342=pod
9343
9344Under the debugger, source files are represented as C<_E<lt>/fullpath/to/file>
9345(C<eval>s are C<_E<lt>(eval NNN)>) keys in C<%main::>. We pull all of these
9346out of C<%main::>, add the initial source file, and extract the ones that
9347match the completion text so far.
9348
9349=cut
9350
9351        return sort
9352          map { substr $_, 2 + $prefix } grep /^_<\Q$text/, ( keys %main:: ),
9353          $0;
9354    } ## end if ($line =~ /^\|*f\s+(.*)/)
9355
9356=head3 Subroutine name completion
9357
9358We look through all of the defined subs (the keys of C<%sub>) and
9359return both all the possible matches to the subroutine name plus
9360all the matches qualified to the current package.
9361
9362=cut
9363
9364    if ( ( substr $text, 0, 1 ) eq '&' ) {    # subroutines
9365        $text = substr $text, 1;
9366        $prefix = "&";
9367        return sort map "$prefix$_", grep /^\Q$text/, ( keys %sub ),
9368          (
9369            map { /$search/ ? ($1) : () }
9370              keys %sub
9371          );
9372    } ## end if ((substr $text, 0, ...
9373
9374=head3  Scalar, array, and hash completion: partially qualified package
9375
9376Much like the above, except we have to do a little more cleanup:
9377
9378=cut
9379
9380    if ( $text =~ /^[\$@%](.*)::(.*)/ ) {    # symbols in a package
9381
9382=pod
9383
9384=over 4
9385
9386=item *
9387
9388Determine the package that the symbol is in. Put it in C<::> (effectively C<main::>) if no package is specified.
9389
9390=cut
9391
9392        $pack = ( $1 eq 'main' ? '' : $1 ) . '::';
9393
9394=pod
9395
9396=item *
9397
9398Figure out the prefix vs. what needs completing.
9399
9400=cut
9401
9402        $prefix = ( substr $text, 0, 1 ) . $1 . '::';
9403        $text   = $2;
9404
9405=pod
9406
9407=item *
9408
9409Look 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.
9410
9411=cut
9412
9413        my @out = do {
9414            no strict 'refs';
9415            map "$prefix$_", grep /^\Q$text/, grep /^_?[a-zA-Z]/,
9416            keys %$pack;
9417        };
9418
9419=pod
9420
9421=item *
9422
9423If 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.
9424
9425=cut
9426
9427        if ( @out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext ) {
9428            return db_complete( $out[0], $line, $start );
9429        }
9430
9431        # Return the list of possibles.
9432        return sort @out;
9433
9434    } ## end if ($text =~ /^[\$@%](.*)::(.*)/)
9435
9436=pod
9437
9438=back
9439
9440=head3 Symbol completion: current package or package C<main>.
9441
9442=cut
9443
9444    if ( $text =~ /^[\$@%]/ ) {    # symbols (in $package + packages in main)
9445=pod
9446
9447=over 4
9448
9449=item *
9450
9451If it's C<main>, delete main to just get C<::> leading.
9452
9453=cut
9454
9455        $pack = ( $package eq 'main' ? '' : $package ) . '::';
9456
9457=pod
9458
9459=item *
9460
9461We set the prefix to the item's sigil, and trim off the sigil to get the text to be completed.
9462
9463=cut
9464
9465        $prefix = substr $text, 0, 1;
9466        $text   = substr $text, 1;
9467
9468        my @out;
9469
9470=pod
9471
9472=item *
9473
9474We look for the lexical scope above DB::DB and auto-complete lexical variables
9475if PadWalker could be loaded.
9476
9477=cut
9478
9479        if (not $text =~ /::/ and eval {
9480            local @INC = @INC;
9481            pop @INC if $INC[-1] eq '.';
9482            require PadWalker } ) {
9483            my $level = 1;
9484            while (1) {
9485                my @info = caller($level);
9486                $level++;
9487                $level = -1, last
9488                  if not @info;
9489                last if $info[3] eq 'DB::DB';
9490            }
9491            if ($level > 0) {
9492                my $lexicals = PadWalker::peek_my($level);
9493                push @out, grep /^\Q$prefix$text/, keys %$lexicals;
9494            }
9495        }
9496
9497=pod
9498
9499=item *
9500
9501If 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.
9502
9503=cut
9504
9505        push @out, map "$prefix$_", grep /^\Q$text/,
9506          ( grep /^_?[a-zA-Z]/, do { no strict 'refs'; keys %$pack } ),
9507          ( $pack eq '::' ? () : ( grep /::$/, keys %:: ) );
9508
9509=item *
9510
9511If there's only one hit, it's a package qualifier, and it's not equal to the initial text, recomplete using this symbol.
9512
9513=back
9514
9515=cut
9516
9517        if ( @out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext ) {
9518            return db_complete( $out[0], $line, $start );
9519        }
9520
9521        # Return the list of possibles.
9522        return sort @out;
9523    } ## end if ($text =~ /^[\$@%]/)
9524
9525=head3 Options
9526
9527We use C<option_val()> to look up the current value of the option. If there's
9528only a single value, we complete the command in such a way that it is a
9529complete command for setting the option in question. If there are multiple
9530possible values, we generate a command consisting of the option plus a trailing
9531question mark, which, if executed, will list the current value of the option.
9532
9533=cut
9534
9535    if ( ( substr $line, 0, $start ) =~ /^\|*[oO]\b.*\s$/ )
9536    {    # Options after space
9537           # We look for the text to be matched in the list of possible options,
9538           # and fetch the current value.
9539        my @out = grep /^\Q$text/, @options;
9540        my $val = option_val( $out[0], undef );
9541
9542        # Set up a 'query option's value' command.
9543        my $out = '? ';
9544        if ( not defined $val or $val =~ /[\n\r]/ ) {
9545
9546            # There's really nothing else we can do.
9547        }
9548
9549        # We have a value. Create a proper option-setting command.
9550        elsif ( $val =~ /\s/ ) {
9551
9552            # XXX This may be an extraneous variable.
9553            my $found;
9554
9555            # We'll want to quote the string (because of the embedded
9556            # whtespace), but we want to make sure we don't end up with
9557            # mismatched quote characters. We try several possibilities.
9558            foreach my $l ( split //, qq/\"\'\#\|/ ) {
9559
9560                # If we didn't find this quote character in the value,
9561                # quote it using this quote character.
9562                $out = "$l$val$l ", last if ( index $val, $l ) == -1;
9563            }
9564        } ## end elsif ($val =~ /\s/)
9565
9566        # Don't need any quotes.
9567        else {
9568            $out = "=$val ";
9569        }
9570
9571        # If there were multiple possible values, return '? ', which
9572        # makes the command into a query command. If there was just one,
9573        # have readline append that.
9574        $rl_attribs->{completer_terminator_character} =
9575          ( @out == 1 ? $out : '? ' );
9576
9577        # Return list of possibilities.
9578        return sort @out;
9579    } ## end if ((substr $line, 0, ...
9580
9581=head3 Filename completion
9582
9583For entering filenames. We simply call C<readline>'s C<filename_list()>
9584method with the completion text to get the possible completions.
9585
9586=cut
9587
9588    return $term->filename_list($text);    # filenames
9589
9590} ## end sub db_complete
9591
9592=head1 MISCELLANEOUS SUPPORT FUNCTIONS
9593
9594Functions that possibly ought to be somewhere else.
9595
9596=head2 end_report
9597
9598Say we're done.
9599
9600=cut
9601
9602sub end_report {
9603    local $\ = '';
9604    print $OUT "Use 'q' to quit or 'R' to restart.  'h q' for details.\n";
9605}
9606
9607=head2 clean_ENV
9608
9609If we have $ini_pids, save it in the environment; else remove it from the
9610environment. Used by the C<R> (restart) command.
9611
9612=cut
9613
9614sub clean_ENV {
9615    if ( defined($ini_pids) ) {
9616        $ENV{PERLDB_PIDS} = $ini_pids;
9617    }
9618    else {
9619        delete( $ENV{PERLDB_PIDS} );
9620    }
9621} ## end sub clean_ENV
9622
9623# PERLDBf_... flag names from perl.h
9624our ( %DollarCaretP_flags, %DollarCaretP_flags_r );
9625
9626BEGIN {
9627    %DollarCaretP_flags = (
9628        PERLDBf_SUB       => 0x01,     # Debug sub enter/exit
9629        PERLDBf_LINE      => 0x02,     # Keep line #
9630        PERLDBf_NOOPT     => 0x04,     # Switch off optimizations
9631        PERLDBf_INTER     => 0x08,     # Preserve more data
9632        PERLDBf_SUBLINE   => 0x10,     # Keep subr source lines
9633        PERLDBf_SINGLE    => 0x20,     # Start with single-step on
9634        PERLDBf_NONAME    => 0x40,     # For _SUB: no name of the subr
9635        PERLDBf_GOTO      => 0x80,     # Report goto: call DB::goto
9636        PERLDBf_NAMEEVAL  => 0x100,    # Informative names for evals
9637        PERLDBf_NAMEANON  => 0x200,    # Informative names for anon subs
9638        PERLDBf_SAVESRC   => 0x400,    # Save source lines into @{"_<$filename"}
9639        PERLDB_ALL        => 0x33f,    # No _NONAME, _GOTO
9640    );
9641    # PERLDBf_LINE also enables the actions of PERLDBf_SAVESRC, so the debugger
9642    # doesn't need to set it. It's provided for the benefit of profilers and
9643    # other code analysers.
9644
9645    %DollarCaretP_flags_r = reverse %DollarCaretP_flags;
9646}
9647
9648sub parse_DollarCaretP_flags {
9649    my $flags = shift;
9650    $flags =~ s/^\s+//;
9651    $flags =~ s/\s+$//;
9652    my $acu = 0;
9653    foreach my $f ( split /\s*\|\s*/, $flags ) {
9654        my $value;
9655        if ( $f =~ /^0x([[:xdigit:]]+)$/ ) {
9656            $value = hex $1;
9657        }
9658        elsif ( $f =~ /^(\d+)$/ ) {
9659            $value = int $1;
9660        }
9661        elsif ( $f =~ /^DEFAULT$/i ) {
9662            $value = $DollarCaretP_flags{PERLDB_ALL};
9663        }
9664        else {
9665            $f =~ /^(?:PERLDBf_)?(.*)$/i;
9666            $value = $DollarCaretP_flags{ 'PERLDBf_' . uc($1) };
9667            unless ( defined $value ) {
9668                print $OUT (
9669                    "Unrecognized \$^P flag '$f'!\n",
9670                    "Acceptable flags are: "
9671                      . join( ', ', sort keys %DollarCaretP_flags ),
9672                    ", and hexadecimal and decimal numbers.\n"
9673                );
9674                return undef;
9675            }
9676        }
9677        $acu |= $value;
9678    }
9679    $acu;
9680}
9681
9682sub expand_DollarCaretP_flags {
9683    my $DollarCaretP = shift;
9684    my @bits         = (
9685        map {
9686            my $n = ( 1 << $_ );
9687            ( $DollarCaretP & $n )
9688              ? ( $DollarCaretP_flags_r{$n}
9689                  || sprintf( '0x%x', $n ) )
9690              : ()
9691          } 0 .. 31
9692    );
9693    return @bits ? join( '|', @bits ) : 0;
9694}
9695
9696=over 4
9697
9698=item rerun
9699
9700Rerun the current session to:
9701
9702    rerun        current position
9703
9704    rerun 4      command number 4
9705
9706    rerun -4     current command minus 4 (go back 4 steps)
9707
9708Whether this always makes sense, in the current context is unknowable, and is
9709in part left as a useful exercise for the reader.  This sub returns the
9710appropriate arguments to rerun the current session.
9711
9712=cut
9713
9714sub rerun {
9715    my $i = shift;
9716    my @args;
9717    pop(@truehist);                      # strim
9718    unless (defined $truehist[$i]) {
9719        print "Unable to return to non-existent command: $i\n";
9720    } else {
9721        $#truehist = ($i < 0 ? $#truehist + $i : $i > 0 ? $i : $#truehist);
9722        my @temp = @truehist;            # store
9723        push(@DB::typeahead, @truehist); # saved
9724        @truehist = @hist = ();          # flush
9725        @args = restart();              # setup
9726        get_list("PERLDB_HIST");        # clean
9727        set_list("PERLDB_HIST", @temp); # reset
9728    }
9729    return @args;
9730}
9731
9732=item restart
9733
9734Restarting the debugger is a complex operation that occurs in several phases.
9735First, we try to reconstruct the command line that was used to invoke Perl
9736and the debugger.
9737
9738=cut
9739
9740sub restart {
9741    # I may not be able to resurrect you, but here goes ...
9742    print $OUT
9743"Warning: some settings and command-line options may be lost!\n";
9744    my ( @script, @flags, $cl );
9745
9746    # If warn was on before, turn it on again.
9747    push @flags, '-w' if $ini_warn;
9748
9749    # Rebuild the -I flags that were on the initial
9750    # command line.
9751    for (@ini_INC) {
9752        push @flags, '-I', $_;
9753    }
9754
9755    # Turn on taint if it was on before.
9756    push @flags, '-T' if ${^TAINT};
9757
9758    # Arrange for setting the old INC:
9759    # Save the current @init_INC in the environment.
9760    set_list( "PERLDB_INC", @ini_INC );
9761
9762    # If this was a perl one-liner, go to the "file"
9763    # corresponding to the one-liner read all the lines
9764    # out of it (except for the first one, which is going
9765    # to be added back on again when 'perl -d' runs: that's
9766    # the 'require perl5db.pl;' line), and add them back on
9767    # to the command line to be executed.
9768    if ( $0 eq '-e' ) {
9769        my $lines = *{$main::{'_<-e'}}{ARRAY};
9770        for ( 1 .. $#$lines ) {  # The first line is PERL5DB
9771            chomp( $cl = $lines->[$_] );
9772            push @script, '-e', $cl;
9773        }
9774    } ## end if ($0 eq '-e')
9775
9776    # Otherwise we just reuse the original name we had
9777    # before.
9778    else {
9779        @script = $0;
9780    }
9781
9782=pod
9783
9784After the command line  has been reconstructed, the next step is to save
9785the debugger's status in environment variables. The C<DB::set_list> routine
9786is used to save aggregate variables (both hashes and arrays); scalars are
9787just popped into environment variables directly.
9788
9789=cut
9790
9791    # If the terminal supported history, grab it and
9792    # save that in the environment.
9793    set_list( "PERLDB_HIST",
9794          $term->Features->{getHistory}
9795        ? $term->GetHistory
9796        : @hist );
9797
9798    # Find all the files that were visited during this
9799    # session (i.e., the debugger had magic hashes
9800    # corresponding to them) and stick them in the environment.
9801    my @had_breakpoints = keys %had_breakpoints;
9802    set_list( "PERLDB_VISITED", @had_breakpoints );
9803
9804    # Save the debugger options we chose.
9805    set_list( "PERLDB_OPT", %option );
9806    # set_list( "PERLDB_OPT", options2remember() );
9807
9808    # Save the break-on-loads.
9809    set_list( "PERLDB_ON_LOAD", %break_on_load );
9810
9811=pod
9812
9813The most complex part of this is the saving of all of the breakpoints. They
9814can live in an awful lot of places, and we have to go through all of them,
9815find the breakpoints, and then save them in the appropriate environment
9816variable via C<DB::set_list>.
9817
9818=cut
9819
9820    # Go through all the breakpoints and make sure they're
9821    # still valid.
9822    my @hard;
9823    for ( 0 .. $#had_breakpoints ) {
9824
9825        # We were in this file.
9826        my $file = $had_breakpoints[$_];
9827
9828        # Grab that file's magic line hash.
9829        *dbline = $main::{ '_<' . $file };
9830
9831        # Skip out if it doesn't exist, or if the breakpoint
9832        # is in a postponed file (we'll do postponed ones
9833        # later).
9834        next unless %dbline or $postponed_file{$file};
9835
9836        # In an eval. This is a little harder, so we'll
9837        # do more processing on that below.
9838        ( push @hard, $file ), next
9839          if $file =~ /^\(\w*eval/;
9840
9841        # XXX I have no idea what this is doing. Yet.
9842        my @add;
9843        @add = %{ $postponed_file{$file} }
9844          if $postponed_file{$file};
9845
9846        # Save the list of all the breakpoints for this file.
9847        set_list( "PERLDB_FILE_$_", %dbline, @add );
9848
9849        # Serialize the extra data %breakpoints_data hash.
9850        # That's a bug fix.
9851        set_list( "PERLDB_FILE_ENABLED_$_",
9852            map { _is_breakpoint_enabled($file, $_) ? 1 : 0 }
9853            sort { $a <=> $b } keys(%dbline)
9854        )
9855    } ## end for (0 .. $#had_breakpoints)
9856
9857    # The breakpoint was inside an eval. This is a little
9858    # more difficult. XXX and I don't understand it.
9859    foreach my $hard_file (@hard) {
9860        # Get over to the eval in question.
9861        *dbline = $main::{ '_<' . $hard_file };
9862        my $quoted = quotemeta $hard_file;
9863        my %subs;
9864        for my $sub ( keys %sub ) {
9865            if (my ($n1, $n2) = $sub{$sub} =~ /\A$quoted:(\d+)-(\d+)\z/) {
9866                $subs{$sub} = [ $n1, $n2 ];
9867            }
9868        }
9869        unless (%subs) {
9870            print {$OUT}
9871            "No subroutines in $hard_file, ignoring breakpoints.\n";
9872            next;
9873        }
9874        LINES: foreach my $line ( keys %dbline ) {
9875
9876            # One breakpoint per sub only:
9877            my ( $offset, $found );
9878            SUBS: foreach my $sub ( keys %subs ) {
9879                if (
9880                    $subs{$sub}->[1] >= $line    # Not after the subroutine
9881                    and (
9882                        not defined $offset    # Not caught
9883                            or $offset < 0
9884                    )
9885                )
9886                {                              # or badly caught
9887                    $found  = $sub;
9888                    $offset = $line - $subs{$sub}->[0];
9889                    if ($offset >= 0) {
9890                        $offset = "+$offset";
9891                        last SUBS;
9892                    }
9893                } ## end if ($subs{$sub}->[1] >=...
9894            } ## end for $sub (keys %subs)
9895            if ( defined $offset ) {
9896                $postponed{$found} =
9897                "break $offset if $dbline{$line}";
9898            }
9899            else {
9900                print {$OUT}
9901                ("Breakpoint in ${hard_file}:$line ignored:"
9902                . " after all the subroutines.\n");
9903            }
9904        } ## end for $line (keys %dbline)
9905    } ## end for (@hard)
9906
9907    # Save the other things that don't need to be
9908    # processed.
9909    set_list( "PERLDB_POSTPONE",  %postponed );
9910    set_list( "PERLDB_PRETYPE",   @$pretype );
9911    set_list( "PERLDB_PRE",       @$pre );
9912    set_list( "PERLDB_POST",      @$post );
9913    set_list( "PERLDB_TYPEAHEAD", @typeahead );
9914
9915    # We are officially restarting.
9916    $ENV{PERLDB_RESTART} = 1;
9917
9918    # We are junking all child debuggers.
9919    delete $ENV{PERLDB_PIDS};    # Restore ini state
9920
9921    # Set this back to the initial pid.
9922    $ENV{PERLDB_PIDS} = $ini_pids if defined $ini_pids;
9923
9924=pod
9925
9926After all the debugger status has been saved, we take the command we built up
9927and then return it, so we can C<exec()> it. The debugger will spot the
9928C<PERLDB_RESTART> environment variable and realize it needs to reload its state
9929from the environment.
9930
9931=cut
9932
9933    # And run Perl again. Add the "-d" flag, all the
9934    # flags we built up, the script (whether a one-liner
9935    # or a file), add on the -emacs flag for a client editor,
9936    # and then the old arguments.
9937
9938    return ($^X, '-d', @flags, @script, ($client_editor ? '-emacs' : ()), @ARGS);
9939
9940};  # end restart
9941
9942=back
9943
9944=head1 END PROCESSING - THE C<END> BLOCK
9945
9946Come here at the very end of processing. We want to go into a
9947loop where we allow the user to enter commands and interact with the
9948debugger, but we don't want anything else to execute.
9949
9950First we set the C<$finished> variable, so that some commands that
9951shouldn't be run after the end of program quit working.
9952
9953We then figure out whether we're truly done (as in the user entered a C<q>
9954command, or we finished execution while running nonstop). If we aren't,
9955we set C<$single> to 1 (causing the debugger to get control again).
9956
9957We then call C<DB::fake::at_exit()>, which returns the C<Use 'q' to quit ...>
9958message and returns control to the debugger. Repeat.
9959
9960When the user finally enters a C<q> command, C<$fall_off_end> is set to
99611 and the C<END> block simply exits with C<$single> set to 0 (don't
9962break, run to completion.).
9963
9964=cut
9965
9966END {
9967    $finished = 1 if $inhibit_exit;    # So that some commands may be disabled.
9968    $fall_off_end = 1 unless $inhibit_exit;
9969
9970    # Do not stop in at_exit() and destructors on exit:
9971    if ($fall_off_end or $runnonstop) {
9972        save_hist();
9973    } else {
9974        $DB::single = 1;
9975        DB::fake::at_exit();
9976    }
9977} ## end END
9978
9979=head1 PRE-5.8 COMMANDS
9980
9981Some of the commands changed function quite a bit in the 5.8 command
9982realignment, so much so that the old code had to be replaced completely.
9983Because we wanted to retain the option of being able to go back to the
9984former command set, we moved the old code off to this section.
9985
9986There's an awful lot of duplicated code here. We've duplicated the
9987comments to keep things clear.
9988
9989=head2 Null command
9990
9991Does nothing. Used to I<turn off> commands.
9992
9993=cut
9994
9995sub cmd_pre580_null {
9996
9997    # do nothing...
9998}
9999
10000=head2 Old C<a> command.
10001
10002This version added actions if you supplied them, and deleted them
10003if you didn't.
10004
10005=cut
10006
10007sub cmd_pre580_a {
10008    my $xcmd = shift;
10009    my $cmd  = shift;
10010
10011    # Argument supplied. Add the action.
10012    if ( $cmd =~ /^(\d*)\s*(.*)/ ) {
10013
10014        # If the line isn't there, use the current line.
10015        my $i = $1 || $line;
10016        my $j = $2;
10017
10018        # If there is an action ...
10019        if ( length $j ) {
10020
10021            # ... but the line isn't breakable, skip it.
10022            if ( $dbline[$i] == 0 ) {
10023                print $OUT "Line $i may not have an action.\n";
10024            }
10025            else {
10026
10027                # ... and the line is breakable:
10028                # Mark that there's an action in this file.
10029                $had_breakpoints{$filename} |= 2;
10030
10031                # Delete any current action.
10032                $dbline{$i} =~ s/\0[^\0]*//;
10033
10034                # Add the new action, continuing the line as needed.
10035                $dbline{$i} .= "\0" . action($j);
10036            }
10037        } ## end if (length $j)
10038
10039        # No action supplied.
10040        else {
10041
10042            # Delete the action.
10043            $dbline{$i} =~ s/\0[^\0]*//;
10044
10045            # Mark as having no break or action if nothing's left.
10046            delete $dbline{$i} if $dbline{$i} eq '';
10047        }
10048    } ## end if ($cmd =~ /^(\d*)\s*(.*)/)
10049} ## end sub cmd_pre580_a
10050
10051=head2 Old C<b> command
10052
10053Add breakpoints.
10054
10055=cut
10056
10057sub cmd_pre580_b {
10058    my $xcmd   = shift;
10059    my $cmd    = shift;
10060    my $dbline = shift;
10061
10062    # Break on load.
10063    if ( $cmd =~ /^load\b\s*(.*)/ ) {
10064        my $file = $1;
10065        $file =~ s/\s+$//;
10066        cmd_b_load($file);
10067    }
10068
10069    # b compile|postpone <some sub> [<condition>]
10070    # The interpreter actually traps this one for us; we just put the
10071    # necessary condition in the %postponed hash.
10072    elsif ( $cmd =~ /^(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/ ) {
10073
10074        # Capture the condition if there is one. Make it true if none.
10075        my $cond = length $3 ? $3 : '1';
10076
10077        # Save the sub name and set $break to 1 if $1 was 'postpone', 0
10078        # if it was 'compile'.
10079        my ( $subname, $break ) = ( $2, $1 eq 'postpone' );
10080
10081        # De-Perl4-ify the name - ' separators to ::.
10082        $subname =~ s/\'/::/g;
10083
10084        # Qualify it into the current package unless it's already qualified.
10085        $subname = "${package}::" . $subname
10086          unless $subname =~ /::/;
10087
10088        # Add main if it starts with ::.
10089        $subname = "main" . $subname if substr( $subname, 0, 2 ) eq "::";
10090
10091        # Save the break type for this sub.
10092        $postponed{$subname} = $break ? "break +0 if $cond" : "compile";
10093    } ## end elsif ($cmd =~ ...
10094
10095    # b <sub name> [<condition>]
10096    elsif ( $cmd =~ /^([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/ ) {
10097        my $subname = $1;
10098        my $cond = length $2 ? $2 : '1';
10099        cmd_b_sub( $subname, $cond );
10100    }
10101    # b <line> [<condition>].
10102    elsif ( $cmd =~ /^(\d*)\s*(.*)/ ) {
10103        my $i = $1 || $dbline;
10104        my $cond = length $2 ? $2 : '1';
10105        cmd_b_line( $i, $cond );
10106    }
10107} ## end sub cmd_pre580_b
10108
10109=head2 Old C<D> command.
10110
10111Delete all breakpoints unconditionally.
10112
10113=cut
10114
10115sub cmd_pre580_D {
10116    my $xcmd = shift;
10117    my $cmd  = shift;
10118    if ( $cmd =~ /^\s*$/ ) {
10119        print $OUT "Deleting all breakpoints...\n";
10120
10121        # %had_breakpoints lists every file that had at least one
10122        # breakpoint in it.
10123        my $file;
10124        for $file ( keys %had_breakpoints ) {
10125
10126            # Switch to the desired file temporarily.
10127            local *dbline = $main::{ '_<' . $file };
10128
10129            $max = $#dbline;
10130            my $was;
10131
10132            # For all lines in this file ...
10133            for my $i (1 .. $max) {
10134
10135                # If there's a breakpoint or action on this line ...
10136                if ( defined $dbline{$i} ) {
10137
10138                    # ... remove the breakpoint.
10139                    $dbline{$i} =~ s/^[^\0]+//;
10140                    if ( $dbline{$i} =~ s/^\0?$// ) {
10141
10142                        # Remove the entry altogether if no action is there.
10143                        delete $dbline{$i};
10144                    }
10145                } ## end if (defined $dbline{$i...
10146            } ## end for my $i (1 .. $max)
10147
10148            # If, after we turn off the "there were breakpoints in this file"
10149            # bit, the entry in %had_breakpoints for this file is zero,
10150            # we should remove this file from the hash.
10151            if ( not $had_breakpoints{$file} &= ~1 ) {
10152                delete $had_breakpoints{$file};
10153            }
10154        } ## end for $file (keys %had_breakpoints)
10155
10156        # Kill off all the other breakpoints that are waiting for files that
10157        # haven't been loaded yet.
10158        undef %postponed;
10159        undef %postponed_file;
10160        undef %break_on_load;
10161    } ## end if ($cmd =~ /^\s*$/)
10162} ## end sub cmd_pre580_D
10163
10164=head2 Old C<h> command
10165
10166Print help. Defaults to printing the long-form help; the 5.8 version
10167prints the summary by default.
10168
10169=cut
10170
10171sub cmd_pre580_h {
10172    my $xcmd = shift;
10173    my $cmd  = shift;
10174
10175    # Print the *right* help, long format.
10176    if ( $cmd =~ /^\s*$/ ) {
10177        print_help($pre580_help);
10178    }
10179
10180    # 'h h' - explicitly-requested summary.
10181    elsif ( $cmd =~ /^h\s*/ ) {
10182        print_help($pre580_summary);
10183    }
10184
10185    # Find and print a command's help.
10186    elsif ( $cmd =~ /^h\s+(\S.*)$/ ) {
10187        my $asked  = $1;                   # for proper errmsg
10188        my $qasked = quotemeta($asked);    # for searching
10189                                           # XXX: finds CR but not <CR>
10190        if (
10191            $pre580_help =~ /^
10192                              <?           # Optional '<'
10193                              (?:[IB]<)    # Optional markup
10194                              $qasked      # The command name
10195                            /mx
10196          )
10197        {
10198
10199            while (
10200                $pre580_help =~ /^
10201                                  (             # The command help:
10202                                   <?           # Optional '<'
10203                                   (?:[IB]<)    # Optional markup
10204                                   $qasked      # The command name
10205                                   ([\s\S]*?)   # Lines starting with tabs
10206                                   \n           # Final newline
10207                                  )
10208                                  (?!\s)/mgx
10209              )    # Line not starting with space
10210                   # (Next command's help)
10211            {
10212                print_help($1);
10213            }
10214        } ## end if ($pre580_help =~ /^<?(?:[IB]<)$qasked/m)
10215
10216        # Help not found.
10217        else {
10218            print_help("B<$asked> is not a debugger command.\n");
10219        }
10220    } ## end elsif ($cmd =~ /^h\s+(\S.*)$/)
10221} ## end sub cmd_pre580_h
10222
10223=head2 Old C<W> command
10224
10225C<W E<lt>exprE<gt>> adds a watch expression, C<W> deletes them all.
10226
10227=cut
10228
10229sub cmd_pre580_W {
10230    my $xcmd = shift;
10231    my $cmd  = shift;
10232
10233    # Delete all watch expressions.
10234    if ( $cmd =~ /^$/ ) {
10235
10236        # No watching is going on.
10237        $trace &= ~2;
10238
10239        # Kill all the watch expressions and values.
10240        @to_watch = @old_watch = ();
10241    }
10242
10243    # Add a watch expression.
10244    elsif ( $cmd =~ /^(.*)/s ) {
10245
10246        # add it to the list to be watched.
10247        push @to_watch, $1;
10248
10249        # Get the current value of the expression.
10250        # Doesn't handle expressions returning list values!
10251        $evalarg = $1;
10252        # The &-call is here to ascertain the mutability of @_.
10253        my ($val) = &DB::eval;
10254        $val = ( defined $val ) ? "'$val'" : 'undef';
10255
10256        # Save it.
10257        push @old_watch, $val;
10258
10259        # We're watching stuff.
10260        $trace |= 2;
10261
10262    } ## end elsif ($cmd =~ /^(.*)/s)
10263} ## end sub cmd_pre580_W
10264
10265=head1 PRE-AND-POST-PROMPT COMMANDS AND ACTIONS
10266
10267The debugger used to have a bunch of nearly-identical code to handle
10268the pre-and-post-prompt action commands. C<cmd_pre590_prepost> and
10269C<cmd_prepost> unify all this into one set of code to handle the
10270appropriate actions.
10271
10272=head2 C<cmd_pre590_prepost>
10273
10274A small wrapper around C<cmd_prepost>; it makes sure that the default doesn't
10275do something destructive. In pre 5.8 debuggers, the default action was to
10276delete all the actions.
10277
10278=cut
10279
10280sub cmd_pre590_prepost {
10281    my $cmd    = shift;
10282    my $line   = shift || '*';
10283    my $dbline = shift;
10284
10285    return cmd_prepost( $cmd, $line, $dbline );
10286} ## end sub cmd_pre590_prepost
10287
10288=head2 C<cmd_prepost>
10289
10290Actually does all the handling for C<E<lt>>, C<E<gt>>, C<{{>, C<{>, etc.
10291Since the lists of actions are all held in arrays that are pointed to by
10292references anyway, all we have to do is pick the right array reference and
10293then use generic code to all, delete, or list actions.
10294
10295=cut
10296
10297sub cmd_prepost {
10298    my $cmd = shift;
10299
10300    # No action supplied defaults to 'list'.
10301    my $line = shift || '?';
10302
10303    # Figure out what to put in the prompt.
10304    my $which = '';
10305
10306    # Make sure we have some array or another to address later.
10307    # This means that if for some reason the tests fail, we won't be
10308    # trying to stash actions or delete them from the wrong place.
10309    my $aref = [];
10310
10311    # < - Perl code to run before prompt.
10312    if ( $cmd =~ /^\</o ) {
10313        $which = 'pre-perl';
10314        $aref  = $pre;
10315    }
10316
10317    # > - Perl code to run after prompt.
10318    elsif ( $cmd =~ /^\>/o ) {
10319        $which = 'post-perl';
10320        $aref  = $post;
10321    }
10322
10323    # { - first check for properly-balanced braces.
10324    elsif ( $cmd =~ /^\{/o ) {
10325        if ( $cmd =~ /^\{.*\}$/o && unbalanced( substr( $cmd, 1 ) ) ) {
10326            print $OUT
10327"$cmd is now a debugger command\nuse ';$cmd' if you mean Perl code\n";
10328        }
10329
10330        # Properly balanced. Pre-prompt debugger actions.
10331        else {
10332            $which = 'pre-debugger';
10333            $aref  = $pretype;
10334        }
10335    } ## end elsif ( $cmd =~ /^\{/o )
10336
10337    # Did we find something that makes sense?
10338    unless ($which) {
10339        print $OUT "Confused by command: $cmd\n";
10340    }
10341
10342    # Yes.
10343    else {
10344
10345        # List actions.
10346        if ( $line =~ /^\s*\?\s*$/o ) {
10347            unless (@$aref) {
10348
10349                # Nothing there. Complain.
10350                print $OUT "No $which actions.\n";
10351            }
10352            else {
10353
10354                # List the actions in the selected list.
10355                print $OUT "$which commands:\n";
10356                foreach my $action (@$aref) {
10357                    print $OUT "\t$cmd -- $action\n";
10358                }
10359            } ## end else
10360        } ## end if ( $line =~ /^\s*\?\s*$/o)
10361
10362        # Might be a delete.
10363        else {
10364            if ( length($cmd) == 1 ) {
10365                if ( $line =~ /^\s*\*\s*$/o ) {
10366
10367                    # It's a delete. Get rid of the old actions in the
10368                    # selected list..
10369                    @$aref = ();
10370                    print $OUT "All $cmd actions cleared.\n";
10371                }
10372                else {
10373
10374                    # Replace all the actions. (This is a <, >, or {).
10375                    @$aref = action($line);
10376                }
10377            } ## end if ( length($cmd) == 1)
10378            elsif ( length($cmd) == 2 ) {
10379
10380                # Add the action to the line. (This is a <<, >>, or {{).
10381                push @$aref, action($line);
10382            }
10383            else {
10384
10385                # <<<, >>>>, {{{{{{ ... something not a command.
10386                print $OUT
10387                  "Confused by strange length of $which command($cmd)...\n";
10388            }
10389        } ## end else [ if ( $line =~ /^\s*\?\s*$/o)
10390    } ## end else
10391} ## end sub cmd_prepost
10392
10393=head1 C<DB::fake>
10394
10395Contains the C<at_exit> routine that the debugger uses to issue the
10396C<Debugged program terminated ...> message after the program completes. See
10397the L<C<END>|/END PROCESSING - THE END BLOCK> block documentation for more
10398details.
10399
10400=cut
10401
10402package DB::fake;
10403
10404sub at_exit {
10405    "Debugged program terminated.  Use 'q' to quit or 'R' to restart.";
10406}
10407
10408package DB;    # Do not trace this 1; below!
10409
104101;
10411
10412
10413