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