This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Allow more tries for t/op/time.t test 2.
[perl5.git] / lib / perl5db.pl
CommitLineData
e22ea7cc 1
69893cff
RGS
2=head1 NAME
3
4C<perl5db.pl> - the perl debugger
5
6=head1 SYNOPSIS
7
8 perl -d your_Perl_script
9
10=head1 DESCRIPTION
11
12C<perl5db.pl> is the perl debugger. It is loaded automatically by Perl when
13you invoke a script with C<perl -d>. This documentation tries to outline the
14structure and services provided by C<perl5db.pl>, and to describe how you
15can use them.
16
17=head1 GENERAL NOTES
18
19The debugger can look pretty forbidding to many Perl programmers. There are
20a number of reasons for this, many stemming out of the debugger's history.
21
22When the debugger was first written, Perl didn't have a lot of its nicer
23features - no references, no lexical variables, no closures, no object-oriented
24programming. So a lot of the things one would normally have done using such
25features was done using global variables, globs and the C<local()> operator
26in creative ways.
27
28Some of these have survived into the current debugger; a few of the more
29interesting and still-useful idioms are noted in this section, along with notes
30on the comments themselves.
31
32=head2 Why not use more lexicals?
33
34Experienced Perl programmers will note that the debugger code tends to use
35mostly package globals rather than lexically-scoped variables. This is done
36to allow a significant amount of control of the debugger from outside the
37debugger itself.
38
39Unfortunately, though the variables are accessible, they're not well
40documented, so it's generally been a decision that hasn't made a lot of
41difference to most users. Where appropriate, comments have been added to
42make variables more accessible and usable, with the understanding that these
43i<are> debugger internals, and are therefore subject to change. Future
44development should probably attempt to replace the globals with a well-defined
45API, but for now, the variables are what we've got.
46
47=head2 Automated variable stacking via C<local()>
48
49As you may recall from reading C<perlfunc>, the C<local()> operator makes a
50temporary copy of a variable in the current scope. When the scope ends, the
51old copy is restored. This is often used in the debugger to handle the
52automatic stacking of variables during recursive calls:
53
54 sub foo {
55 local $some_global++;
56
57 # Do some stuff, then ...
58 return;
59 }
60
61What happens is that on entry to the subroutine, C<$some_global> is localized,
62then altered. When the subroutine returns, Perl automatically undoes the
63localization, restoring the previous value. Voila, automatic stack management.
64
65The debugger uses this trick a I<lot>. Of particular note is C<DB::eval>,
66which lets the debugger get control inside of C<eval>'ed code. The debugger
67localizes a saved copy of C<$@> inside the subroutine, which allows it to
68keep C<$@> safe until it C<DB::eval> returns, at which point the previous
69value of C<$@> is restored. This makes it simple (well, I<simpler>) to keep
70track of C<$@> inside C<eval>s which C<eval> other C<eval's>.
71
72In any case, watch for this pattern. It occurs fairly often.
73
74=head2 The C<^> trick
75
76This is used to cleverly reverse the sense of a logical test depending on
77the value of an auxiliary variable. For instance, the debugger's C<S>
78(search for subroutines by pattern) allows you to negate the pattern
79like this:
80
81 # Find all non-'foo' subs:
82 S !/foo/
83
84Boolean algebra states that the truth table for XOR looks like this:
85
86=over 4
87
88=item * 0 ^ 0 = 0
89
90(! not present and no match) --> false, don't print
91
92=item * 0 ^ 1 = 1
93
94(! not present and matches) --> true, print
95
96=item * 1 ^ 0 = 1
97
98(! present and no match) --> true, print
99
100=item * 1 ^ 1 = 0
101
102(! present and matches) --> false, don't print
103
104=back
105
106As you can see, the first pair applies when C<!> isn't supplied, and
107the second pair applies when it isn't. The XOR simply allows us to
108compact a more complicated if-then-elseif-else into a more elegant
109(but perhaps overly clever) single test. After all, it needed this
110explanation...
111
112=head2 FLAGS, FLAGS, FLAGS
113
114There is a certain C programming legacy in the debugger. Some variables,
115such as C<$single>, C<$trace>, and C<$frame>, have "magical" values composed
116of 1, 2, 4, etc. (powers of 2) OR'ed together. This allows several pieces
117of state to be stored independently in a single scalar.
118
119A test like
120
121 if ($scalar & 4) ...
122
123is checking to see if the appropriate bit is on. Since each bit can be
124"addressed" independently in this way, C<$scalar> is acting sort of like
125an array of bits. Obviously, since the contents of C<$scalar> are just a
126bit-pattern, we can save and restore it easily (it will just look like
127a number).
128
129The problem, is of course, that this tends to leave magic numbers scattered
130all over your program whenever a bit is set, cleared, or checked. So why do
131it?
132
133=over 4
134
135
136=item * First, doing an arithmetical or bitwise operation on a scalar is
137just about the fastest thing you can do in Perl: C<use constant> actually
138creates a subroutine call, and array hand hash lookups are much slower. Is
139this over-optimization at the expense of readability? Possibly, but the
140debugger accesses these variables a I<lot>. Any rewrite of the code will
141probably have to benchmark alternate implementations and see which is the
142best balance of readability and speed, and then document how it actually
143works.
144
145=item * Second, it's very easy to serialize a scalar number. This is done in
146the restart code; the debugger state variables are saved in C<%ENV> and then
147restored when the debugger is restarted. Having them be just numbers makes
148this trivial.
149
150=item * Third, some of these variables are being shared with the Perl core
151smack in the middle of the interpreter's execution loop. It's much faster for
152a C program (like the interpreter) to check a bit in a scalar than to access
153several different variables (or a Perl array).
154
155=back
156
157=head2 What are those C<XXX> comments for?
158
159Any comment containing C<XXX> means that the comment is either somewhat
160speculative - it's not exactly clear what a given variable or chunk of
161code is doing, or that it is incomplete - the basics may be clear, but the
162subtleties are not completely documented.
163
164Send in a patch if you can clear up, fill out, or clarify an C<XXX>.
165
166=head1 DATA STRUCTURES MAINTAINED BY CORE
167
168There are a number of special data structures provided to the debugger by
169the Perl interpreter.
170
171The array C<@{$main::{'_<'.$filename}}> (aliased locally to C<@dbline> via glob
172assignment) contains the text from C<$filename>, with each element
173corresponding to a single line of C<$filename>.
174
175The hash C<%{'_<'.$filename}> (aliased locally to C<%dbline> via glob
176assignment) contains breakpoints and actions. The keys are line numbers;
177you can set individual values, but not the whole hash. The Perl interpreter
178uses this hash to determine where breakpoints have been set. Any true value is
179considered to be a breakpoint; C<perl5db.pl> uses "$break_condition\0$action".
180Values are magical in numeric context: 1 if the line is breakable, 0 if not.
181
182The scalar ${'_<'.$filename} contains $filename XXX What?
183
184=head1 DEBUGGER STARTUP
185
186When C<perl5db.pl> starts, it reads an rcfile (C<perl5db.ini> for
187non-interactive sessions, C<.perldb> for interactive ones) that can set a number
188of options. In addition, this file may define a subroutine C<&afterinit>
189that will be executed (in the debugger's context) after the debugger has
190initialized itself.
191
192Next, it checks the C<PERLDB_OPTS> environment variable and treats its
193contents as the argument of a debugger <C<o> command.
194
195=head2 STARTUP-ONLY OPTIONS
196
197The following options can only be specified at startup.
198To set them in your rcfile, add a call to
199C<&parse_options("optionName=new_value")>.
200
201=over 4
202
203=item * TTY
204
205the TTY to use for debugging i/o.
206
207=item * noTTY
208
209if set, goes in NonStop mode. On interrupt, if TTY is not set,
210uses the value of noTTY or "/tmp/perldbtty$$" to find TTY using
211Term::Rendezvous. Current variant is to have the name of TTY in this
212file.
213
214=item * ReadLine
215
216If false, a dummy ReadLine is used, so you can debug
217ReadLine applications.
218
219=item * NonStop
220
221if true, no i/o is performed until interrupt.
222
223=item * LineInfo
224
225file or pipe to print line number info to. If it is a
226pipe, a short "emacs like" message is used.
227
228=item * RemotePort
229
230host:port to connect to on remote host for remote debugging.
231
232=back
233
234=head3 SAMPLE RCFILE
235
236 &parse_options("NonStop=1 LineInfo=db.out");
237 sub afterinit { $trace = 1; }
238
239The script will run without human intervention, putting trace
240information into C<db.out>. (If you interrupt it, you had better
241reset C<LineInfo> to something "interactive"!)
242
243=head1 INTERNALS DESCRIPTION
244
245=head2 DEBUGGER INTERFACE VARIABLES
246
247Perl supplies the values for C<%sub>. It effectively inserts
248a C<&DB'DB();> in front of each place that can have a
249breakpoint. At each subroutine call, it calls C<&DB::sub> with
250C<$DB::sub> set to the called subroutine. It also inserts a C<BEGIN
251{require 'perl5db.pl'}> before the first line.
252
253After each C<require>d file is compiled, but before it is executed, a
254call to C<&DB::postponed($main::{'_<'.$filename})> is done. C<$filename>
255is the expanded name of the C<require>d file (as found via C<%INC>).
256
257=head3 IMPORTANT INTERNAL VARIABLES
258
259=head4 C<$CreateTTY>
260
261Used to control when the debugger will attempt to acquire another TTY to be
262used for input.
263
264=over
265
266=item * 1 - on C<fork()>
267
268=item * 2 - debugger is started inside debugger
269
270=item * 4 - on startup
271
272=back
273
274=head4 C<$doret>
275
276The value -2 indicates that no return value should be printed.
277Any other positive value causes C<DB::sub> to print return values.
278
279=head4 C<$evalarg>
280
281The item to be eval'ed by C<DB::eval>. Used to prevent messing with the current
282contents of C<@_> when C<DB::eval> is called.
283
284=head4 C<$frame>
285
286Determines what messages (if any) will get printed when a subroutine (or eval)
287is entered or exited.
288
289=over 4
290
291=item * 0 - No enter/exit messages
292
293=item * 1 - Print "entering" messages on subroutine entry
294
295=item * 2 - Adds exit messages on subroutine exit. If no other flag is on, acts like 1+2.
296
297=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.
298
299=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.
300
301=item * 16 - Adds C<I<context> return from I<subname>: I<value>> messages on subroutine/eval exit. Ignored if C<4> is is not on.
302
303=back
304
305To get everything, use C<$frame=30> (or C<o f-30> as a debugger command).
306The debugger internally juggles the value of C<$frame> during execution to
307protect external modules that the debugger uses from getting traced.
308
309=head4 C<$level>
310
311Tracks current debugger nesting level. Used to figure out how many
312C<E<lt>E<gt>> pairs to surround the line number with when the debugger
313outputs a prompt. Also used to help determine if the program has finished
314during command parsing.
315
316=head4 C<$onetimeDump>
317
318Controls what (if anything) C<DB::eval()> will print after evaluating an
319expression.
320
321=over 4
322
323=item * C<undef> - don't print anything
324
325=item * C<dump> - use C<dumpvar.pl> to display the value returned
326
327=item * C<methods> - print the methods callable on the first item returned
328
329=back
330
331=head4 C<$onetimeDumpDepth>
332
333Controls how far down C<dumpvar.pl> will go before printing '...' while
334dumping a structure. Numeric. If C<undef>, print all levels.
335
336=head4 C<$signal>
337
338Used to track whether or not an C<INT> signal has been detected. C<DB::DB()>,
339which is called before every statement, checks this and puts the user into
340command mode if it finds C<$signal> set to a true value.
341
342=head4 C<$single>
343
344Controls behavior during single-stepping. Stacked in C<@stack> on entry to
345each subroutine; popped again at the end of each subroutine.
346
347=over 4
348
349=item * 0 - run continuously.
350
351=item * 1 - single-step, go into subs. The 's' command.
352
353=item * 2 - single-step, don't go into subs. The 'n' command.
354
355=item * 4 - print current sub depth (turned on to force this when "too much
356recursion" occurs.
357
358=back
359
360=head4 C<$trace>
361
362Controls the output of trace information.
363
364=over 4
365
366=item * 1 - The C<t> command was entered to turn on tracing (every line executed is printed)
367
368=item * 2 - watch expressions are active
369
370=item * 4 - user defined a C<watchfunction()> in C<afterinit()>
371
372=back
373
374=head4 C<$slave_editor>
375
3761 if C<LINEINFO> was directed to a pipe; 0 otherwise.
377
378=head4 C<@cmdfhs>
379
380Stack of filehandles that C<DB::readline()> will read commands from.
381Manipulated by the debugger's C<source> command and C<DB::readline()> itself.
382
383=head4 C<@dbline>
384
385Local alias to the magical line array, C<@{$main::{'_<'.$filename}}> ,
386supplied by the Perl interpreter to the debugger. Contains the source.
387
388=head4 C<@old_watch>
389
390Previous values of watch expressions. First set when the expression is
391entered; reset whenever the watch expression changes.
392
393=head4 C<@saved>
394
395Saves important globals (C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, C<$^W>)
396so that the debugger can substitute safe values while it's running, and
397restore them when it returns control.
398
399=head4 C<@stack>
400
401Saves the current value of C<$single> on entry to a subroutine.
402Manipulated by the C<c> command to turn off tracing in all subs above the
403current one.
404
405=head4 C<@to_watch>
406
407The 'watch' expressions: to be evaluated before each line is executed.
408
409=head4 C<@typeahead>
410
411The typeahead buffer, used by C<DB::readline>.
412
413=head4 C<%alias>
414
415Command aliases. Stored as character strings to be substituted for a command
416entered.
417
418=head4 C<%break_on_load>
419
420Keys are file names, values are 1 (break when this file is loaded) or undef
421(don't break when it is loaded).
422
423=head4 C<%dbline>
424
425Keys are line numbers, values are "condition\0action". If used in numeric
426context, values are 0 if not breakable, 1 if breakable, no matter what is
427in the actual hash entry.
428
429=head4 C<%had_breakpoints>
430
431Keys are file names; values are bitfields:
432
433=over 4
434
435=item * 1 - file has a breakpoint in it.
436
437=item * 2 - file has an action in it.
438
439=back
440
441A zero or undefined value means this file has neither.
442
443=head4 C<%option>
444
445Stores the debugger options. These are character string values.
446
447=head4 C<%postponed>
448
449Saves breakpoints for code that hasn't been compiled yet.
450Keys are subroutine names, values are:
451
452=over 4
453
454=item * 'compile' - break when this sub is compiled
455
456=item * 'break +0 if <condition>' - break (conditionally) at the start of this routine. The condition will be '1' if no condition was specified.
457
458=back
459
460=head4 C<%postponed_file>
461
462This hash keeps track of breakpoints that need to be set for files that have
463not yet been compiled. Keys are filenames; values are references to hashes.
464Each of these hashes is keyed by line number, and its values are breakpoint
465definitions ("condition\0action").
466
467=head1 DEBUGGER INITIALIZATION
468
469The debugger's initialization actually jumps all over the place inside this
470package. This is because there are several BEGIN blocks (which of course
471execute immediately) spread through the code. Why is that?
472
473The debugger needs to be able to change some things and set some things up
474before the debugger code is compiled; most notably, the C<$deep> variable that
475C<DB::sub> uses to tell when a program has recursed deeply. In addition, the
476debugger has to turn off warnings while the debugger code is compiled, but then
477restore them to their original setting before the program being debugged begins
478executing.
479
480The first C<BEGIN> block simply turns off warnings by saving the current
481setting of C<$^W> and then setting it to zero. The second one initializes
482the debugger variables that are needed before the debugger begins executing.
483The third one puts C<$^X> back to its former value.
484
485We'll detail the second C<BEGIN> block later; just remember that if you need
486to initialize something before the debugger starts really executing, that's
487where it has to go.
488
489=cut
490
a687059c
LW
491package DB;
492
9eba6a4e
AV
493use IO::Handle;
494
54d04a52 495# Debugger for Perl 5.00x; perl5db.pl patch level:
2cbb2ee1 496$VERSION = 1.28;
69893cff 497
e22ea7cc 498$header = "perl5db.pl version $VERSION";
d338d6fe 499
69893cff
RGS
500=head1 DEBUGGER ROUTINES
501
502=head2 C<DB::eval()>
503
504This function replaces straight C<eval()> inside the debugger; it simplifies
505the process of evaluating code in the user's context.
506
507The code to be evaluated is passed via the package global variable
508C<$DB::evalarg>; this is done to avoid fiddling with the contents of C<@_>.
509
510We preserve the current settings of X<C<$trace>>, X<C<$single>>, and X<C<$^D>>;
511add the X<C<$usercontext>> (that's the preserved values of C<$@>, C<$!>,
512C<$^E>, C<$,>, C<$/>, C<$\>, and C<$^W>, grabbed when C<DB::DB> got control,
513and the user's current package) and a add a newline before we do the C<eval()>.
514This causes the proper context to be used when the eval is actually done.
515Afterward, we restore C<$trace>, C<$single>, and C<$^D>.
516
517Next we need to handle C<$@> without getting confused. We save C<$@> in a
518local lexical, localize C<$saved[0]> (which is where C<save()> will put
519C<$@>), and then call C<save()> to capture C<$@>, C<$!>, C<$^E>, C<$,>,
520C<$/>, C<$\>, and C<$^W>) and set C<$,>, C<$/>, C<$\>, and C<$^W> to values
521considered sane by the debugger. If there was an C<eval()> error, we print
522it on the debugger's output. If X<C<$onetimedump>> is defined, we call
523X<C<dumpit>> if it's set to 'dump', or X<C<methods>> if it's set to
524'methods'. Setting it to something else causes the debugger to do the eval
525but not print the result - handy if you want to do something else with it
526(the "watch expressions" code does this to get the value of the watch
527expression but not show it unless it matters).
528
529In any case, we then return the list of output from C<eval> to the caller,
530and unwinding restores the former version of C<$@> in C<@saved> as well
531(the localization of C<$saved[0]> goes away at the end of this scope).
532
533=head3 Parameters and variables influencing execution of DB::eval()
534
535C<DB::eval> isn't parameterized in the standard way; this is to keep the
536debugger's calls to C<DB::eval()> from mucking with C<@_>, among other things.
537The variables listed below influence C<DB::eval()>'s execution directly.
538
539=over 4
540
541=item C<$evalarg> - the thing to actually be eval'ed
542
543=item C<$trace> - Current state of execution tracing (see X<$trace>)
544
545=item C<$single> - Current state of single-stepping (see X<$single>)
546
547=item C<$onetimeDump> - what is to be displayed after the evaluation
548
549=item C<$onetimeDumpDepth> - how deep C<dumpit()> should go when dumping results
550
551=back
552
553The following variables are altered by C<DB::eval()> during its execution. They
554are "stacked" via C<local()>, enabling recursive calls to C<DB::eval()>.
555
556=over 4
557
558=item C<@res> - used to capture output from actual C<eval>.
559
560=item C<$otrace> - saved value of C<$trace>.
561
562=item C<$osingle> - saved value of C<$single>.
563
564=item C<$od> - saved value of C<$^D>.
565
566=item C<$saved[0]> - saved value of C<$@>.
567
568=item $\ - for output of C<$@> if there is an evaluation error.
569
570=back
571
572=head3 The problem of lexicals
573
574The context of C<DB::eval()> presents us with some problems. Obviously,
575we want to be 'sandboxed' away from the debugger's internals when we do
576the eval, but we need some way to control how punctuation variables and
577debugger globals are used.
578
579We can't use local, because the code inside C<DB::eval> can see localized
580variables; and we can't use C<my> either for the same reason. The code
581in this routine compromises and uses C<my>.
582
583After this routine is over, we don't have user code executing in the debugger's
584context, so we can use C<my> freely.
585
586=cut
587
588############################################## Begin lexical danger zone
589
590# 'my' variables used here could leak into (that is, be visible in)
591# the context that the code being evaluated is executing in. This means that
592# the code could modify the debugger's variables.
593#
594# Fiddling with the debugger's context could be Bad. We insulate things as
595# much as we can.
596
c1051fcf 597sub eval {
69893cff 598
c1051fcf 599 # 'my' would make it visible from user code
e22ea7cc 600 # but so does local! --tchrist
69893cff 601 # Remember: this localizes @DB::res, not @main::res.
c1051fcf
IZ
602 local @res;
603 {
e22ea7cc
RF
604
605 # Try to keep the user code from messing with us. Save these so that
606 # even if the eval'ed code changes them, we can put them back again.
607 # Needed because the user could refer directly to the debugger's
69893cff
RGS
608 # package globals (and any 'my' variables in this containing scope)
609 # inside the eval(), and we want to try to stay safe.
e22ea7cc 610 local $otrace = $trace;
69893cff
RGS
611 local $osingle = $single;
612 local $od = $^D;
613
614 # Untaint the incoming eval() argument.
615 { ($evalarg) = $evalarg =~ /(.*)/s; }
616
e22ea7cc 617 # $usercontext built in DB::DB near the comment
69893cff
RGS
618 # "set up the context for DB::eval ..."
619 # Evaluate and save any results.
e22ea7cc 620 @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug
69893cff
RGS
621
622 # Restore those old values.
623 $trace = $otrace;
624 $single = $osingle;
625 $^D = $od;
c1051fcf 626 }
69893cff
RGS
627
628 # Save the current value of $@, and preserve it in the debugger's copy
629 # of the saved precious globals.
c1051fcf 630 my $at = $@;
69893cff
RGS
631
632 # Since we're only saving $@, we only have to localize the array element
633 # that it will be stored in.
e22ea7cc 634 local $saved[0]; # Preserve the old value of $@
c1051fcf 635 eval { &DB::save };
69893cff
RGS
636
637 # Now see whether we need to report an error back to the user.
c1051fcf 638 if ($at) {
69893cff
RGS
639 local $\ = '';
640 print $OUT $at;
641 }
642
643 # Display as required by the caller. $onetimeDump and $onetimedumpDepth
644 # are package globals.
645 elsif ($onetimeDump) {
e22ea7cc
RF
646 if ( $onetimeDump eq 'dump' ) {
647 local $option{dumpDepth} = $onetimedumpDepth
648 if defined $onetimedumpDepth;
649 dumpit( $OUT, \@res );
650 }
651 elsif ( $onetimeDump eq 'methods' ) {
652 methods( $res[0] );
653 }
69893cff 654 } ## end elsif ($onetimeDump)
c1051fcf 655 @res;
69893cff
RGS
656} ## end sub eval
657
658############################################## End lexical danger zone
c1051fcf 659
e22ea7cc
RF
660# After this point it is safe to introduce lexicals.
661# The code being debugged will be executing in its own context, and
69893cff 662# can't see the inside of the debugger.
d338d6fe 663#
e22ea7cc 664# However, one should not overdo it: leave as much control from outside as
69893cff
RGS
665# possible. If you make something a lexical, it's not going to be addressable
666# from outside the debugger even if you know its name.
667
d338d6fe
PP
668# This file is automatically included if you do perl -d.
669# It's probably not useful to include this yourself.
670#
e22ea7cc 671# Before venturing further into these twisty passages, it is
2f7e9187
MS
672# wise to read the perldebguts man page or risk the ire of dragons.
673#
69893cff
RGS
674# (It should be noted that perldebguts will tell you a lot about
675# the underlying mechanics of how the debugger interfaces into the
676# Perl interpreter, but not a lot about the debugger itself. The new
677# comments in this code try to address this problem.)
678
d338d6fe 679# Note that no subroutine call is possible until &DB::sub is defined
36477c24 680# (for subroutines defined outside of the package DB). In fact the same is
d338d6fe 681# true if $deep is not defined.
055fd3a9
GS
682
683# Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich)
055fd3a9
GS
684
685# modified Perl debugger, to be run from Emacs in perldb-mode
686# Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990
687# Johan Vromans -- upgrade to 4.0 pl 10
688# Ilya Zakharevich -- patches after 5.001 (and some before ;-)
689
69893cff
RGS
690# (We have made efforts to clarify the comments in the change log
691# in other places; some of them may seem somewhat obscure as they
692# were originally written, and explaining them away from the code
693# in question seems conterproductive.. -JM)
694
695########################################################################
696# Changes: 0.94
697# + A lot of things changed after 0.94. First of all, core now informs
698# debugger about entry into XSUBs, overloaded operators, tied operations,
699# BEGIN and END. Handy with `O f=2'.
700# + This can make debugger a little bit too verbose, please be patient
701# and report your problems promptly.
702# + Now the option frame has 3 values: 0,1,2. XXX Document!
703# + Note that if DESTROY returns a reference to the object (or object),
704# the deletion of data may be postponed until the next function call,
705# due to the need to examine the return value.
706#
707# Changes: 0.95
708# + `v' command shows versions.
709#
e22ea7cc 710# Changes: 0.96
69893cff
RGS
711# + `v' command shows version of readline.
712# primitive completion works (dynamic variables, subs for `b' and `l',
713# options). Can `p %var'
714# + Better help (`h <' now works). New commands <<, >>, {, {{.
715# {dump|print}_trace() coded (to be able to do it from <<cmd).
716# + `c sub' documented.
717# + At last enough magic combined to stop after the end of debuggee.
718# + !! should work now (thanks to Emacs bracket matching an extra
719# `]' in a regexp is caught).
720# + `L', `D' and `A' span files now (as documented).
721# + Breakpoints in `require'd code are possible (used in `R').
722# + Some additional words on internal work of debugger.
723# + `b load filename' implemented.
724# + `b postpone subr' implemented.
725# + now only `q' exits debugger (overwritable on $inhibit_exit).
726# + When restarting debugger breakpoints/actions persist.
e22ea7cc 727# + Buglet: When restarting debugger only one breakpoint/action per
69893cff
RGS
728# autoloaded function persists.
729#
36477c24 730# Changes: 0.97: NonStop will not stop in at_exit().
69893cff
RGS
731# + Option AutoTrace implemented.
732# + Trace printed differently if frames are printed too.
733# + new `inhibitExit' option.
734# + printing of a very long statement interruptible.
1d06cb2d 735# Changes: 0.98: New command `m' for printing possible methods
69893cff
RGS
736# + 'l -' is a synonym for `-'.
737# + Cosmetic bugs in printing stack trace.
738# + `frame' & 8 to print "expanded args" in stack trace.
739# + Can list/break in imported subs.
740# + new `maxTraceLen' option.
741# + frame & 4 and frame & 8 granted.
742# + new command `m'
743# + nonstoppable lines do not have `:' near the line number.
744# + `b compile subname' implemented.
745# + Will not use $` any more.
746# + `-' behaves sane now.
477ea2b1 747# Changes: 0.99: Completion for `f', `m'.
69893cff
RGS
748# + `m' will remove duplicate names instead of duplicate functions.
749# + `b load' strips trailing whitespace.
750# completion ignores leading `|'; takes into account current package
751# when completing a subroutine name (same for `l').
055fd3a9
GS
752# Changes: 1.07: Many fixed by tchrist 13-March-2000
753# BUG FIXES:
04e43a21 754# + Added bare minimal security checks on perldb rc files, plus
055fd3a9
GS
755# comments on what else is needed.
756# + Fixed the ornaments that made "|h" completely unusable.
757# They are not used in print_help if they will hurt. Strip pod
758# if we're paging to less.
759# + Fixed mis-formatting of help messages caused by ornaments
e22ea7cc
RF
760# to restore Larry's original formatting.
761# + Fixed many other formatting errors. The code is still suboptimal,
04e43a21 762# and needs a lot of work at restructuring. It's also misindented
055fd3a9
GS
763# in many places.
764# + Fixed bug where trying to look at an option like your pager
e22ea7cc 765# shows "1".
055fd3a9
GS
766# + Fixed some $? processing. Note: if you use csh or tcsh, you will
767# lose. You should consider shell escapes not using their shell,
768# or else not caring about detailed status. This should really be
769# unified into one place, too.
770# + Fixed bug where invisible trailing whitespace on commands hoses you,
04e43a21 771# tricking Perl into thinking you weren't calling a debugger command!
055fd3a9
GS
772# + Fixed bug where leading whitespace on commands hoses you. (One
773# suggests a leading semicolon or any other irrelevant non-whitespace
774# to indicate literal Perl code.)
775# + Fixed bugs that ate warnings due to wrong selected handle.
776# + Fixed a precedence bug on signal stuff.
777# + Fixed some unseemly wording.
778# + Fixed bug in help command trying to call perl method code.
779# + Fixed to call dumpvar from exception handler. SIGPIPE killed us.
780# ENHANCEMENTS:
781# + Added some comments. This code is still nasty spaghetti.
782# + Added message if you clear your pre/post command stacks which was
783# very easy to do if you just typed a bare >, <, or {. (A command
784# without an argument should *never* be a destructive action; this
785# API is fundamentally screwed up; likewise option setting, which
786# is equally buggered.)
787# + Added command stack dump on argument of "?" for >, <, or {.
788# + Added a semi-built-in doc viewer command that calls man with the
789# proper %Config::Config path (and thus gets caching, man -k, etc),
790# or else perldoc on obstreperous platforms.
791# + Added to and rearranged the help information.
792# + Detected apparent misuse of { ... } to declare a block; this used
793# to work but now is a command, and mysteriously gave no complaint.
04e43a21
DL
794#
795# Changes: 1.08: Apr 25, 2001 Jon Eveland <jweveland@yahoo.com>
796# BUG FIX:
797# + This patch to perl5db.pl cleans up formatting issues on the help
798# summary (h h) screen in the debugger. Mostly columnar alignment
799# issues, plus converted the printed text to use all spaces, since
800# tabs don't seem to help much here.
801#
802# Changes: 1.09: May 19, 2001 Ilya Zakharevich <ilya@math.ohio-state.edu>
69893cff
RGS
803# Minor bugs corrected;
804# + Support for auto-creation of new TTY window on startup, either
805# unconditionally, or if started as a kid of another debugger session;
806# + New `O'ption CreateTTY
807# I<CreateTTY> bits control attempts to create a new TTY on events:
e22ea7cc 808# 1: on fork()
69893cff
RGS
809# 2: debugger is started inside debugger
810# 4: on startup
811# + Code to auto-create a new TTY window on OS/2 (currently one
812# extra window per session - need named pipes to have more...);
813# + Simplified interface for custom createTTY functions (with a backward
814# compatibility hack); now returns the TTY name to use; return of ''
815# means that the function reset the I/O handles itself;
816# + Better message on the semantic of custom createTTY function;
817# + Convert the existing code to create a TTY into a custom createTTY
818# function;
819# + Consistent support for TTY names of the form "TTYin,TTYout";
820# + Switch line-tracing output too to the created TTY window;
821# + make `b fork' DWIM with CORE::GLOBAL::fork;
822# + High-level debugger API cmd_*():
04e43a21
DL
823# cmd_b_load($filenamepart) # b load filenamepart
824# cmd_b_line($lineno [, $cond]) # b lineno [cond]
825# cmd_b_sub($sub [, $cond]) # b sub [cond]
826# cmd_stop() # Control-C
492652be 827# cmd_d($lineno) # d lineno (B)
04e43a21
DL
828# The cmd_*() API returns FALSE on failure; in this case it outputs
829# the error message to the debugging output.
69893cff 830# + Low-level debugger API
04e43a21
DL
831# break_on_load($filename) # b load filename
832# @files = report_break_on_load() # List files with load-breakpoints
833# breakable_line_in_filename($name, $from [, $to])
834# # First breakable line in the
835# # range $from .. $to. $to defaults
e22ea7cc 836# # to $from, and may be less than
69893cff 837# # $to
04e43a21
DL
838# breakable_line($from [, $to]) # Same for the current file
839# break_on_filename_line($name, $lineno [, $cond])
e22ea7cc 840# # Set breakpoint,$cond defaults to
69893cff 841# # 1
04e43a21
DL
842# break_on_filename_line_range($name, $from, $to [, $cond])
843# # As above, on the first
844# # breakable line in range
845# break_on_line($lineno [, $cond]) # As above, in the current file
846# break_subroutine($sub [, $cond]) # break on the first breakable line
847# ($name, $from, $to) = subroutine_filename_lines($sub)
848# # The range of lines of the text
849# The low-level API returns TRUE on success, and die()s on failure.
850#
851# Changes: 1.10: May 23, 2001 Daniel Lewart <d-lewart@uiuc.edu>
852# BUG FIXES:
853# + Fixed warnings generated by "perl -dWe 42"
854# + Corrected spelling errors
855# + Squeezed Help (h) output into 80 columns
600d99fa
DL
856#
857# Changes: 1.11: May 24, 2001 David Dyck <dcd@tc.fluke.com>
858# + Made "x @INC" work like it used to
859#
860# Changes: 1.12: May 24, 2001 Daniel Lewart <d-lewart@uiuc.edu>
861# + Fixed warnings generated by "O" (Show debugger options)
862# + Fixed warnings generated by "p 42" (Print expression)
6f891d7d 863# Changes: 1.13: Jun 19, 2001 Scott.L.Miller@compaq.com
e22ea7cc 864# + Added windowSize option
2f7e9187
MS
865# Changes: 1.14: Oct 9, 2001 multiple
866# + Clean up after itself on VMS (Charles Lane in 12385)
867# + Adding "@ file" syntax (Peter Scott in 12014)
868# + Debug reloading selfloaded stuff (Ilya Zakharevich in 11457)
869# + $^S and other debugger fixes (Ilya Zakharevich in 11120)
870# + Forgot a my() declaration (Ilya Zakharevich in 11085)
871# Changes: 1.15: Nov 6, 2001 Michael G Schwern <schwern@pobox.com>
872# + Updated 1.14 change log
873# + Added *dbline explainatory comments
874# + Mentioning perldebguts man page
492652be 875# Changes: 1.16: Feb 15, 2002 Mark-Jason Dominus <mjd@plover.com>
69893cff 876# + $onetimeDump improvements
492652be
RF
877# Changes: 1.17: Feb 20, 2002 Richard Foley <richard.foley@rfi.net>
878# Moved some code to cmd_[.]()'s for clarity and ease of handling,
e22ea7cc
RF
879# rationalised the following commands and added cmd_wrapper() to
880# enable switching between old and frighteningly consistent new
492652be
RF
881# behaviours for diehards: 'o CommandSet=pre580' (sigh...)
882# a(add), A(del) # action expr (added del by line)
883# + b(add), B(del) # break [line] (was b,D)
e22ea7cc 884# + w(add), W(del) # watch expr (was W,W)
69893cff 885# # added del by expr
492652be
RF
886# + h(summary), h h(long) # help (hh) (was h h,h)
887# + m(methods), M(modules) # ... (was m,v)
888# + o(option) # lc (was O)
889# + v(view code), V(view Variables) # ... (was w,V)
aef14ef9
RF
890# Changes: 1.18: Mar 17, 2002 Richard Foley <richard.foley@rfi.net>
891# + fixed missing cmd_O bug
471505cc 892# Changes: 1.19: Mar 29, 2002 Spider Boardman
893# + Added missing local()s -- DB::DB is called recursively.
35408c4e
RF
894# Changes: 1.20: Feb 17, 2003 Richard Foley <richard.foley@rfi.net>
895# + pre'n'post commands no longer trashed with no args
896# + watch val joined out of eval()
69893cff
RGS
897# Changes: 1.21: Jun 04, 2003 Joe McMahon <mcmahon@ibiblio.org>
898# + Added comments and reformatted source. No bug fixes/enhancements.
899# + Includes cleanup by Robin Barker and Jarkko Hietaniemi.
900# Changes: 1.22 Jun 09, 2003 Alex Vandiver <alexmv@MIT.EDU>
901# + Flush stdout/stderr before the debugger prompt is printed.
902# Changes: 1.23: Dec 21, 2003 Dominique Quatravaux
de5e1a3d 903# + Fix a side-effect of bug #24674 in the perl debugger ("odd taint bug")
e219e2fb
RF
904# Changes: 1.24: Mar 03, 2004 Richard Foley <richard.foley@rfi.net>
905# + Added command to save all debugger commands for sourcing later.
906# + Added command to display parent inheritence tree of given class.
907# + Fixed minor newline in history bug.
e22ea7cc
RF
908# Changes: 1.25: Apr 17, 2004 Richard Foley <richard.foley@rfi.net>
909# + Fixed option bug (setting invalid options + not recognising valid short forms)
910# Changes: 1.26: Apr 22, 2004 Richard Foley <richard.foley@rfi.net>
911# + unfork the 5.8.x and 5.9.x debuggers.
912# + whitespace and assertions call cleanup across versions
913# + H * deletes (resets) history
914# + i now handles Class + blessed objects
7fddc82f
RF
915# Changes: 1.27: May 09, 2004 Richard Foley <richard.foley@rfi.net>
916# + updated pod page references - clunky.
917# + removed windowid restriction for forking into an xterm.
918# + more whitespace again.
919# + wrapped restart and enabled rerun [-n] (go back n steps) command.
2cbb2ee1
RGS
920# Changes: 1.28: Oct 12, 2004 Richard Foley <richard.foley@rfi.net>
921# + Added threads support (inc. e and E commands)
ee971a18 922####################################################################
d338d6fe 923
69893cff
RGS
924=head1 DEBUGGER INITIALIZATION
925
926The debugger starts up in phases.
927
928=head2 BASIC SETUP
929
930First, it initializes the environment it wants to run in: turning off
931warnings during its own compilation, defining variables which it will need
932to avoid warnings later, setting itself up to not exit when the program
933terminates, and defaulting to printing return values for the C<r> command.
934
935=cut
936
eda6e075 937# Needed for the statement after exec():
69893cff
RGS
938#
939# This BEGIN block is simply used to switch off warnings during debugger
940# compiliation. Probably it would be better practice to fix the warnings,
941# but this is how it's done at the moment.
eda6e075 942
e22ea7cc
RF
943BEGIN {
944 $ini_warn = $^W;
945 $^W = 0;
946} # Switch compilation warnings off until another BEGIN.
d12a4851
JH
947
948# test if assertions are supported and actived:
eda6e075 949BEGIN {
e22ea7cc
RF
950 $ini_assertion = eval "sub asserting_test : assertion {1}; 1";
951
d12a4851 952 # $ini_assertion = undef => assertions unsupported,
e22ea7cc 953 # " = 1 => assertions supported
d12a4851
JH
954 # print "\$ini_assertion=$ini_assertion\n";
955}
956
69893cff
RGS
957local ($^W) = 0; # Switch run-time warnings off during init.
958
2cbb2ee1
RGS
959=head2 THREADS SUPPORT
960
961If we are running under a threaded Perl, we require threads and threads::shared
962if the environment variable C<PERL5DB_THREADED> is set, to enable proper
963threaded debugger control. C<-dt> can also be used to set this.
964
965Each new thread will be announced and the debugger prompt will always inform
966you of each new thread created. It will also indicate the thread id in which
967we are currently running within the prompt like this:
968
969 [tid] DB<$i>
970
971Where C<[tid]> is an integer thread id and C<$i> is the familiar debugger
972command prompt. The prompt will show: C<[0]> when running under threads, but
973not actually in a thread. C<[tid]> is consistent with C<gdb> usage.
974
975While running under threads, when you set or delete a breakpoint (etc.), this
976will apply to all threads, not just the currently running one. When you are
977in a currently executing thread, you will stay there until it completes. With
978the current implementation it is not currently possible to hop from one thread
979to another.
980
981The C<e> and C<E> commands are currently fairly minimal - see C<h e> and C<h E>.
982
983Note that threading support was built into the debugger as of Perl version
984C<5.8.6> and debugger version C<1.2.8>.
985
986=cut
987
988BEGIN {
989 # ensure we can share our non-threaded variables or no-op
990 if ($ENV{PERL5DB_THREADED}) {
991 require threads;
992 require threads::shared;
993 import threads::shared qw(share);
994 $DBGR;
995 share(\$DBGR);
996 lock($DBGR);
997 print "Threads support enabled\n";
998 } else {
999 *lock = sub(*) {};
1000 *share = sub(*) {};
1001 }
1002}
1003
69893cff
RGS
1004# This would probably be better done with "use vars", but that wasn't around
1005# when this code was originally written. (Neither was "use strict".) And on
1006# the principle of not fiddling with something that was working, this was
1007# left alone.
1008warn( # Do not ;-)
2cbb2ee1 1009 # These variables control the execution of 'dumpvar.pl'.
69893cff
RGS
1010 $dumpvar::hashDepth,
1011 $dumpvar::arrayDepth,
1012 $dumpvar::dumpDBFiles,
1013 $dumpvar::dumpPackages,
1014 $dumpvar::quoteHighBit,
1015 $dumpvar::printUndef,
1016 $dumpvar::globPrint,
1017 $dumpvar::usageOnly,
1018
1019 # used to save @ARGV and extract any debugger-related flags.
1020 @ARGS,
1021
1022 # used to control die() reporting in diesignal()
1023 $Carp::CarpLevel,
1024
1025 # used to prevent multiple entries to diesignal()
1026 # (if for instance diesignal() itself dies)
1027 $panic,
1028
1029 # used to prevent the debugger from running nonstop
1030 # after a restart
1031 $second_time,
1032 )
1033 if 0;
d338d6fe 1034
2cbb2ee1
RGS
1035foreach my $k (keys (%INC)) {
1036 &share(\$main::{'_<'.$filename});
1037};
1038
54d04a52 1039# Command-line + PERLLIB:
69893cff 1040# Save the contents of @INC before they are modified elsewhere.
54d04a52
IZ
1041@ini_INC = @INC;
1042
69893cff
RGS
1043# This was an attempt to clear out the previous values of various
1044# trapped errors. Apparently it didn't help. XXX More info needed!
d338d6fe
PP
1045# $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?!
1046
69893cff
RGS
1047# We set these variables to safe values. We don't want to blindly turn
1048# off warnings, because other packages may still want them.
e22ea7cc
RF
1049$trace = $signal = $single = 0; # Uninitialized warning suppression
1050 # (local $^W cannot help - other packages!).
69893cff
RGS
1051
1052# Default to not exiting when program finishes; print the return
1053# value when the 'r' command is used to return from a subroutine.
55497cff 1054$inhibit_exit = $option{PrintRet} = 1;
d338d6fe 1055
69893cff
RGS
1056=head1 OPTION PROCESSING
1057
1058The debugger's options are actually spread out over the debugger itself and
1059C<dumpvar.pl>; some of these are variables to be set, while others are
1060subs to be called with a value. To try to make this a little easier to
1061manage, the debugger uses a few data structures to define what options
1062are legal and how they are to be processed.
1063
1064First, the C<@options> array defines the I<names> of all the options that
1065are to be accepted.
1066
1067=cut
1068
1069@options = qw(
e22ea7cc
RF
1070 CommandSet
1071 hashDepth arrayDepth dumpDepth
1072 DumpDBFiles DumpPackages DumpReused
1073 compactDump veryCompact quote
1074 HighBit undefPrint globPrint
1075 PrintRet UsageOnly frame
1076 AutoTrace TTY noTTY
1077 ReadLine NonStop LineInfo
1078 maxTraceLen recallCommand ShellBang
1079 pager tkRunning ornaments
1080 signalLevel warnLevel dieLevel
1081 inhibit_exit ImmediateStop bareStringify
1082 CreateTTY RemotePort windowSize
1083 DollarCaretP OnlyAssertions WarnAssertions
1084);
d12a4851
JH
1085
1086@RememberOnROptions = qw(DollarCaretP OnlyAssertions);
1087
69893cff
RGS
1088=pod
1089
1090Second, C<optionVars> lists the variables that each option uses to save its
1091state.
1092
1093=cut
1094
1095%optionVars = (
e22ea7cc
RF
1096 hashDepth => \$dumpvar::hashDepth,
1097 arrayDepth => \$dumpvar::arrayDepth,
1098 CommandSet => \$CommandSet,
1099 DumpDBFiles => \$dumpvar::dumpDBFiles,
1100 DumpPackages => \$dumpvar::dumpPackages,
1101 DumpReused => \$dumpvar::dumpReused,
1102 HighBit => \$dumpvar::quoteHighBit,
1103 undefPrint => \$dumpvar::printUndef,
1104 globPrint => \$dumpvar::globPrint,
1105 UsageOnly => \$dumpvar::usageOnly,
1106 CreateTTY => \$CreateTTY,
1107 bareStringify => \$dumpvar::bareStringify,
1108 frame => \$frame,
1109 AutoTrace => \$trace,
1110 inhibit_exit => \$inhibit_exit,
1111 maxTraceLen => \$maxtrace,
1112 ImmediateStop => \$ImmediateStop,
1113 RemotePort => \$remoteport,
1114 windowSize => \$window,
1115 WarnAssertions => \$warnassertions,
69893cff
RGS
1116);
1117
1118=pod
1119
1120Third, C<%optionAction> defines the subroutine to be called to process each
1121option.
1122
1123=cut
1124
1125%optionAction = (
1126 compactDump => \&dumpvar::compactDump,
1127 veryCompact => \&dumpvar::veryCompact,
1128 quote => \&dumpvar::quote,
1129 TTY => \&TTY,
1130 noTTY => \&noTTY,
1131 ReadLine => \&ReadLine,
1132 NonStop => \&NonStop,
1133 LineInfo => \&LineInfo,
1134 recallCommand => \&recallCommand,
1135 ShellBang => \&shellBang,
1136 pager => \&pager,
1137 signalLevel => \&signalLevel,
1138 warnLevel => \&warnLevel,
1139 dieLevel => \&dieLevel,
1140 tkRunning => \&tkRunning,
1141 ornaments => \&ornaments,
1142 RemotePort => \&RemotePort,
1143 DollarCaretP => \&DollarCaretP,
1144 OnlyAssertions=> \&OnlyAssertions,
d12a4851
JH
1145);
1146
69893cff
RGS
1147=pod
1148
1149Last, the C<%optionRequire> notes modules that must be C<require>d if an
1150option is used.
1151
1152=cut
d338d6fe 1153
69893cff
RGS
1154# Note that this list is not complete: several options not listed here
1155# actually require that dumpvar.pl be loaded for them to work, but are
1156# not in the table. A subsequent patch will correct this problem; for
1157# the moment, we're just recommenting, and we are NOT going to change
1158# function.
eda6e075 1159%optionRequire = (
69893cff
RGS
1160 compactDump => 'dumpvar.pl',
1161 veryCompact => 'dumpvar.pl',
1162 quote => 'dumpvar.pl',
e22ea7cc 1163);
69893cff
RGS
1164
1165=pod
1166
1167There are a number of initialization-related variables which can be set
1168by putting code to set them in a BEGIN block in the C<PERL5DB> environment
1169variable. These are:
1170
1171=over 4
1172
1173=item C<$rl> - readline control XXX needs more explanation
1174
1175=item C<$warnLevel> - whether or not debugger takes over warning handling
1176
1177=item C<$dieLevel> - whether or not debugger takes over die handling
1178
1179=item C<$signalLevel> - whether or not debugger takes over signal handling
1180
1181=item C<$pre> - preprompt actions (array reference)
1182
1183=item C<$post> - postprompt actions (array reference)
1184
1185=item C<$pretype>
1186
1187=item C<$CreateTTY> - whether or not to create a new TTY for this debugger
1188
1189=item C<$CommandSet> - which command set to use (defaults to new, documented set)
1190
1191=back
1192
1193=cut
d338d6fe
PP
1194
1195# These guys may be defined in $ENV{PERL5DB} :
69893cff
RGS
1196$rl = 1 unless defined $rl;
1197$warnLevel = 1 unless defined $warnLevel;
1198$dieLevel = 1 unless defined $dieLevel;
1199$signalLevel = 1 unless defined $signalLevel;
1200$pre = [] unless defined $pre;
1201$post = [] unless defined $post;
1202$pretype = [] unless defined $pretype;
1203$CreateTTY = 3 unless defined $CreateTTY;
1204$CommandSet = '580' unless defined $CommandSet;
1205
2cbb2ee1
RGS
1206share($rl);
1207share($warnLevel);
1208share($dieLevel);
1209share($signalLevel);
1210share($pre);
1211share($post);
1212share($pretype);
1213share($rl);
1214share($CreateTTY);
1215share($CommandSet);
1216
69893cff
RGS
1217=pod
1218
1219The default C<die>, C<warn>, and C<signal> handlers are set up.
1220
1221=cut
055fd3a9 1222
d338d6fe
PP
1223warnLevel($warnLevel);
1224dieLevel($dieLevel);
1225signalLevel($signalLevel);
055fd3a9 1226
69893cff
RGS
1227=pod
1228
1229The pager to be used is needed next. We try to get it from the
1230environment first. if it's not defined there, we try to find it in
1231the Perl C<Config.pm>. If it's not there, we default to C<more>. We
1232then call the C<pager()> function to save the pager name.
1233
1234=cut
1235
1236# This routine makes sure $pager is set up so that '|' can use it.
4865a36d 1237pager(
e22ea7cc 1238
69893cff 1239 # If PAGER is defined in the environment, use it.
e22ea7cc
RF
1240 defined $ENV{PAGER}
1241 ? $ENV{PAGER}
69893cff
RGS
1242
1243 # If not, see if Config.pm defines it.
e22ea7cc
RF
1244 : eval { require Config }
1245 && defined $Config::Config{pager}
1246 ? $Config::Config{pager}
69893cff
RGS
1247
1248 # If not, fall back to 'more'.
e22ea7cc
RF
1249 : 'more'
1250 )
1251 unless defined $pager;
69893cff
RGS
1252
1253=pod
1254
1255We set up the command to be used to access the man pages, the command
1256recall character ("!" unless otherwise defined) and the shell escape
1257character ("!" unless otherwise defined). Yes, these do conflict, and
1258neither works in the debugger at the moment.
1259
1260=cut
1261
055fd3a9 1262setman();
69893cff
RGS
1263
1264# Set up defaults for command recall and shell escape (note:
1265# these currently don't work in linemode debugging).
d338d6fe 1266&recallCommand("!") unless defined $prc;
69893cff
RGS
1267&shellBang("!") unless defined $psh;
1268
1269=pod
1270
1271We then set up the gigantic string containing the debugger help.
1272We also set the limit on the number of arguments we'll display during a
1273trace.
1274
1275=cut
1276
04e43a21 1277sethelp();
69893cff
RGS
1278
1279# If we didn't get a default for the length of eval/stack trace args,
1280# set it here.
1d06cb2d 1281$maxtrace = 400 unless defined $maxtrace;
69893cff
RGS
1282
1283=head2 SETTING UP THE DEBUGGER GREETING
1284
1285The debugger 'greeting' helps to inform the user how many debuggers are
1286running, and whether the current debugger is the primary or a child.
1287
1288If we are the primary, we just hang onto our pid so we'll have it when
1289or if we start a child debugger. If we are a child, we'll set things up
1290so we'll have a unique greeting and so the parent will give us our own
1291TTY later.
1292
1293We save the current contents of the C<PERLDB_PIDS> environment variable
1294because we mess around with it. We'll also need to hang onto it because
1295we'll need it if we restart.
1296
1297Child debuggers make a label out of the current PID structure recorded in
1298PERLDB_PIDS plus the new PID. They also mark themselves as not having a TTY
1299yet so the parent will give them one later via C<resetterm()>.
1300
1301=cut
1302
e22ea7cc 1303# Save the current contents of the environment; we're about to
69893cff 1304# much with it. We'll need this if we have to restart.
f1583d8f 1305$ini_pids = $ENV{PERLDB_PIDS};
69893cff 1306
e22ea7cc
RF
1307if ( defined $ENV{PERLDB_PIDS} ) {
1308
69893cff 1309 # We're a child. Make us a label out of the current PID structure
e22ea7cc 1310 # recorded in PERLDB_PIDS plus our (new) PID. Mark us as not having
69893cff 1311 # a term yet so the parent will give us one later via resetterm().
e22ea7cc
RF
1312 $pids = "[$ENV{PERLDB_PIDS}]";
1313 $ENV{PERLDB_PIDS} .= "->$$";
1314 $term_pid = -1;
69893cff
RGS
1315} ## end if (defined $ENV{PERLDB_PIDS...
1316else {
e22ea7cc
RF
1317
1318 # We're the parent PID. Initialize PERLDB_PID in case we end up with a
69893cff
RGS
1319 # child debugger, and mark us as the parent, so we'll know to set up
1320 # more TTY's is we have to.
1321 $ENV{PERLDB_PIDS} = "$$";
e22ea7cc
RF
1322 $pids = "{pid=$$}";
1323 $term_pid = $$;
f1583d8f 1324}
69893cff 1325
f1583d8f 1326$pidprompt = '';
69893cff
RGS
1327
1328# Sets up $emacs as a synonym for $slave_editor.
1329*emacs = $slave_editor if $slave_editor; # May be used in afterinit()...
1330
1331=head2 READING THE RC FILE
1332
1333The debugger will read a file of initialization options if supplied. If
1334running interactively, this is C<.perldb>; if not, it's C<perldb.ini>.
1335
1336=cut
1337
1338# As noted, this test really doesn't check accurately that the debugger
1339# is running at a terminal or not.
d338d6fe 1340
e22ea7cc
RF
1341if ( -e "/dev/tty" ) { # this is the wrong metric!
1342 $rcfile = ".perldb";
1343}
69893cff
RGS
1344else {
1345 $rcfile = "perldb.ini";
d338d6fe
PP
1346}
1347
69893cff
RGS
1348=pod
1349
1350The debugger does a safety test of the file to be read. It must be owned
1351either by the current user or root, and must only be writable by the owner.
1352
1353=cut
1354
1355# This wraps a safety test around "do" to read and evaluate the init file.
1356#
055fd3a9
GS
1357# This isn't really safe, because there's a race
1358# between checking and opening. The solution is to
1359# open and fstat the handle, but then you have to read and
1360# eval the contents. But then the silly thing gets
69893cff
RGS
1361# your lexical scope, which is unfortunate at best.
1362sub safe_do {
055fd3a9
GS
1363 my $file = shift;
1364
1365 # Just exactly what part of the word "CORE::" don't you understand?
69893cff
RGS
1366 local $SIG{__WARN__};
1367 local $SIG{__DIE__};
055fd3a9 1368
e22ea7cc 1369 unless ( is_safe_file($file) ) {
69893cff 1370 CORE::warn <<EO_GRIPE;
055fd3a9
GS
1371perldb: Must not source insecure rcfile $file.
1372 You or the superuser must be the owner, and it must not
69893cff 1373 be writable by anyone but its owner.
055fd3a9 1374EO_GRIPE
69893cff
RGS
1375 return;
1376 } ## end unless (is_safe_file($file...
055fd3a9
GS
1377
1378 do $file;
1379 CORE::warn("perldb: couldn't parse $file: $@") if $@;
69893cff 1380} ## end sub safe_do
055fd3a9 1381
69893cff
RGS
1382# This is the safety test itself.
1383#
055fd3a9
GS
1384# Verifies that owner is either real user or superuser and that no
1385# one but owner may write to it. This function is of limited use
1386# when called on a path instead of upon a handle, because there are
1387# no guarantees that filename (by dirent) whose file (by ino) is
e22ea7cc 1388# eventually accessed is the same as the one tested.
055fd3a9
GS
1389# Assumes that the file's existence is not in doubt.
1390sub is_safe_file {
1391 my $path = shift;
69893cff 1392 stat($path) || return; # mysteriously vaporized
e22ea7cc 1393 my ( $dev, $ino, $mode, $nlink, $uid, $gid ) = stat(_);
055fd3a9
GS
1394
1395 return 0 if $uid != 0 && $uid != $<;
1396 return 0 if $mode & 022;
1397 return 1;
69893cff 1398} ## end sub is_safe_file
055fd3a9 1399
69893cff 1400# If the rcfile (whichever one we decided was the right one to read)
e22ea7cc
RF
1401# exists, we safely do it.
1402if ( -f $rcfile ) {
055fd3a9 1403 safe_do("./$rcfile");
69893cff 1404}
e22ea7cc 1405
69893cff 1406# If there isn't one here, try the user's home directory.
e22ea7cc 1407elsif ( defined $ENV{HOME} && -f "$ENV{HOME}/$rcfile" ) {
055fd3a9
GS
1408 safe_do("$ENV{HOME}/$rcfile");
1409}
e22ea7cc 1410
69893cff 1411# Else try the login directory.
e22ea7cc 1412elsif ( defined $ENV{LOGDIR} && -f "$ENV{LOGDIR}/$rcfile" ) {
055fd3a9 1413 safe_do("$ENV{LOGDIR}/$rcfile");
d338d6fe
PP
1414}
1415
69893cff 1416# If the PERLDB_OPTS variable has options in it, parse those out next.
e22ea7cc
RF
1417if ( defined $ENV{PERLDB_OPTS} ) {
1418 parse_options( $ENV{PERLDB_OPTS} );
d338d6fe
PP
1419}
1420
69893cff
RGS
1421=pod
1422
1423The last thing we do during initialization is determine which subroutine is
1424to be used to obtain a new terminal when a new debugger is started. Right now,
1425the debugger only handles X Windows and OS/2.
1426
1427=cut
1428
1429# Set up the get_fork_TTY subroutine to be aliased to the proper routine.
1430# Works if you're running an xterm or xterm-like window, or you're on
1431# OS/2. This may need some expansion: for instance, this doesn't handle
e22ea7cc
RF
1432# OS X Terminal windows.
1433
1434if (
1435 not defined &get_fork_TTY # no routine exists,
1436 and defined $ENV{TERM} # and we know what kind
1437 # of terminal this is,
1438 and $ENV{TERM} eq 'xterm' # and it's an xterm,
7fddc82f
RF
1439# and defined $ENV{WINDOWID} # and we know what window this is, <- wrong metric
1440 and defined $ENV{DISPLAY} # and what display it's on,
1441 )
69893cff 1442{
e22ea7cc 1443 *get_fork_TTY = \&xterm_get_fork_TTY; # use the xterm version
69893cff 1444} ## end if (not defined &get_fork_TTY...
e22ea7cc
RF
1445elsif ( $^O eq 'os2' ) { # If this is OS/2,
1446 *get_fork_TTY = \&os2_get_fork_TTY; # use the OS/2 version
f1583d8f 1447}
e22ea7cc 1448
dbb46cec
DQ
1449# untaint $^O, which may have been tainted by the last statement.
1450# see bug [perl #24674]
e22ea7cc
RF
1451$^O =~ m/^(.*)\z/;
1452$^O = $1;
f1583d8f 1453
d12a4851 1454# Here begin the unreadable code. It needs fixing.
055fd3a9 1455
69893cff
RGS
1456=head2 RESTART PROCESSING
1457
1458This section handles the restart command. When the C<R> command is invoked, it
1459tries to capture all of the state it can into environment variables, and
1460then sets C<PERLDB_RESTART>. When we start executing again, we check to see
1461if C<PERLDB_RESTART> is there; if so, we reload all the information that
1462the R command stuffed into the environment variables.
1463
1464 PERLDB_RESTART - flag only, contains no restart data itself.
1465 PERLDB_HIST - command history, if it's available
1466 PERLDB_ON_LOAD - breakpoints set by the rc file
1467 PERLDB_POSTPONE - subs that have been loaded/not executed, and have actions
1468 PERLDB_VISITED - files that had breakpoints
1469 PERLDB_FILE_... - breakpoints for a file
1470 PERLDB_OPT - active options
1471 PERLDB_INC - the original @INC
1472 PERLDB_PRETYPE - preprompt debugger actions
1473 PERLDB_PRE - preprompt Perl code
1474 PERLDB_POST - post-prompt Perl code
1475 PERLDB_TYPEAHEAD - typeahead captured by readline()
1476
1477We chug through all these variables and plug the values saved in them
1478back into the appropriate spots in the debugger.
1479
1480=cut
1481
e22ea7cc
RF
1482if ( exists $ENV{PERLDB_RESTART} ) {
1483
69893cff 1484 # We're restarting, so we don't need the flag that says to restart anymore.
e22ea7cc
RF
1485 delete $ENV{PERLDB_RESTART};
1486
1487 # $restart = 1;
1488 @hist = get_list('PERLDB_HIST');
1489 %break_on_load = get_list("PERLDB_ON_LOAD");
1490 %postponed = get_list("PERLDB_POSTPONE");
69893cff 1491
2cbb2ee1
RGS
1492 share(@hist);
1493 share(@truehist);
1494 share(%break_on_load);
1495 share(%postponed);
1496
69893cff 1497 # restore breakpoints/actions
e22ea7cc
RF
1498 my @had_breakpoints = get_list("PERLDB_VISITED");
1499 for ( 0 .. $#had_breakpoints ) {
1500 my %pf = get_list("PERLDB_FILE_$_");
1501 $postponed_file{ $had_breakpoints[$_] } = \%pf if %pf;
1502 }
69893cff
RGS
1503
1504 # restore options
e22ea7cc
RF
1505 my %opt = get_list("PERLDB_OPT");
1506 my ( $opt, $val );
1507 while ( ( $opt, $val ) = each %opt ) {
1508 $val =~ s/[\\\']/\\$1/g;
1509 parse_options("$opt'$val'");
1510 }
69893cff
RGS
1511
1512 # restore original @INC
e22ea7cc
RF
1513 @INC = get_list("PERLDB_INC");
1514 @ini_INC = @INC;
1515
1516 # return pre/postprompt actions and typeahead buffer
1517 $pretype = [ get_list("PERLDB_PRETYPE") ];
1518 $pre = [ get_list("PERLDB_PRE") ];
1519 $post = [ get_list("PERLDB_POST") ];
1520 @typeahead = get_list( "PERLDB_TYPEAHEAD", @typeahead );
69893cff
RGS
1521} ## end if (exists $ENV{PERLDB_RESTART...
1522
1523=head2 SETTING UP THE TERMINAL
1524
1525Now, we'll decide how the debugger is going to interact with the user.
1526If there's no TTY, we set the debugger to run non-stop; there's not going
1527to be anyone there to enter commands.
1528
1529=cut
54d04a52 1530
d338d6fe 1531if ($notty) {
69893cff 1532 $runnonstop = 1;
2cbb2ee1 1533 share($runnonstop);
69893cff 1534}
d12a4851 1535
69893cff
RGS
1536=pod
1537
1538If there is a TTY, we have to determine who it belongs to before we can
1539proceed. If this is a slave editor or graphical debugger (denoted by
1540the first command-line switch being '-emacs'), we shift this off and
1541set C<$rl> to 0 (XXX ostensibly to do straight reads).
1542
1543=cut
1544
1545else {
e22ea7cc 1546
69893cff
RGS
1547 # Is Perl being run from a slave editor or graphical debugger?
1548 # If so, don't use readline, and set $slave_editor = 1.
e22ea7cc
RF
1549 $slave_editor =
1550 ( ( defined $main::ARGV[0] ) and ( $main::ARGV[0] eq '-emacs' ) );
1551 $rl = 0, shift(@main::ARGV) if $slave_editor;
1552
1553 #require Term::ReadLine;
d12a4851 1554
69893cff
RGS
1555=pod
1556
1557We then determine what the console should be on various systems:
1558
1559=over 4
1560
1561=item * Cygwin - We use C<stdin> instead of a separate device.
1562
1563=cut
1564
e22ea7cc
RF
1565 if ( $^O eq 'cygwin' ) {
1566
69893cff
RGS
1567 # /dev/tty is binary. use stdin for textmode
1568 undef $console;
1569 }
1570
1571=item * Unix - use C</dev/tty>.
1572
1573=cut
1574
e22ea7cc 1575 elsif ( -e "/dev/tty" ) {
69893cff
RGS
1576 $console = "/dev/tty";
1577 }
1578
1579=item * Windows or MSDOS - use C<con>.
1580
1581=cut
1582
e22ea7cc 1583 elsif ( $^O eq 'dos' or -e "con" or $^O eq 'MSWin32' ) {
69893cff
RGS
1584 $console = "con";
1585 }
1586
1587=item * MacOS - use C<Dev:Console:Perl Debug> if this is the MPW version; C<Dev:
1588Console> if not. (Note that Mac OS X returns 'darwin', not 'MacOS'. Also note that the debugger doesn't do anything special for 'darwin'. Maybe it should.)
1589
1590=cut
1591
e22ea7cc
RF
1592 elsif ( $^O eq 'MacOS' ) {
1593 if ( $MacPerl::Version !~ /MPW/ ) {
1594 $console =
1595 "Dev:Console:Perl Debug"; # Separate window for application
69893cff
RGS
1596 }
1597 else {
1598 $console = "Dev:Console";
1599 }
1600 } ## end elsif ($^O eq 'MacOS')
1601
1602=item * VMS - use C<sys$command>.
1603
1604=cut
1605
1606 else {
e22ea7cc 1607
69893cff
RGS
1608 # everything else is ...
1609 $console = "sys\$command";
d12a4851 1610 }
69893cff
RGS
1611
1612=pod
1613
1614=back
1615
1616Several other systems don't use a specific console. We C<undef $console>
1617for those (Windows using a slave editor/graphical debugger, NetWare, OS/2
1618with a slave editor, Epoc).
1619
1620=cut
d12a4851 1621
e22ea7cc
RF
1622 if ( ( $^O eq 'MSWin32' ) and ( $slave_editor or defined $ENV{EMACS} ) ) {
1623
69893cff 1624 # /dev/tty is binary. use stdin for textmode
e22ea7cc
RF
1625 $console = undef;
1626 }
1627
1628 if ( $^O eq 'NetWare' ) {
d12a4851 1629
69893cff
RGS
1630 # /dev/tty is binary. use stdin for textmode
1631 $console = undef;
1632 }
d12a4851 1633
69893cff
RGS
1634 # In OS/2, we need to use STDIN to get textmode too, even though
1635 # it pretty much looks like Unix otherwise.
e22ea7cc
RF
1636 if ( defined $ENV{OS2_SHELL} and ( $slave_editor or $ENV{WINDOWID} ) )
1637 { # In OS/2
1638 $console = undef;
1639 }
1640
1641 # EPOC also falls into the 'got to use STDIN' camp.
1642 if ( $^O eq 'epoc' ) {
1643 $console = undef;
1644 }
d12a4851 1645
69893cff
RGS
1646=pod
1647
1648If there is a TTY hanging around from a parent, we use that as the console.
1649
1650=cut
1651
e22ea7cc 1652 $console = $tty if defined $tty;
d12a4851 1653
69893cff
RGS
1654=head2 SOCKET HANDLING
1655
1656The debugger is capable of opening a socket and carrying out a debugging
1657session over the socket.
1658
1659If C<RemotePort> was defined in the options, the debugger assumes that it
1660should try to start a debugging session on that port. It builds the socket
1661and then tries to connect the input and output filehandles to it.
1662
1663=cut
1664
1665 # Handle socket stuff.
e22ea7cc
RF
1666
1667 if ( defined $remoteport ) {
1668
69893cff
RGS
1669 # If RemotePort was defined in the options, connect input and output
1670 # to the socket.
e22ea7cc
RF
1671 require IO::Socket;
1672 $OUT = new IO::Socket::INET(
1673 Timeout => '10',
1674 PeerAddr => $remoteport,
1675 Proto => 'tcp',
69893cff 1676 );
e22ea7cc
RF
1677 if ( !$OUT ) { die "Unable to connect to remote host: $remoteport\n"; }
1678 $IN = $OUT;
69893cff
RGS
1679 } ## end if (defined $remoteport)
1680
1681=pod
1682
1683If no C<RemotePort> was defined, and we want to create a TTY on startup,
1684this is probably a situation where multiple debuggers are running (for example,
1685a backticked command that starts up another debugger). We create a new IN and
1686OUT filehandle, and do the necessary mojo to create a new TTY if we know how
1687and if we can.
1688
1689=cut
1690
1691 # Non-socket.
1692 else {
e22ea7cc 1693
69893cff
RGS
1694 # Two debuggers running (probably a system or a backtick that invokes
1695 # the debugger itself under the running one). create a new IN and OUT
e22ea7cc 1696 # filehandle, and do the necessary mojo to create a new tty if we
69893cff 1697 # know how, and we can.
e22ea7cc
RF
1698 create_IN_OUT(4) if $CreateTTY & 4;
1699 if ($console) {
1700
69893cff
RGS
1701 # If we have a console, check to see if there are separate ins and
1702 # outs to open. (They are assumed identiical if not.)
1703
e22ea7cc
RF
1704 my ( $i, $o ) = split /,/, $console;
1705 $o = $i unless defined $o;
69893cff 1706
69893cff 1707 # read/write on in, or just read, or read on STDIN.
e22ea7cc
RF
1708 open( IN, "+<$i" )
1709 || open( IN, "<$i" )
1710 || open( IN, "<&STDIN" );
1711
69893cff
RGS
1712 # read/write/create/clobber out, or write/create/clobber out,
1713 # or merge with STDERR, or merge with STDOUT.
e22ea7cc
RF
1714 open( OUT, "+>$o" )
1715 || open( OUT, ">$o" )
1716 || open( OUT, ">&STDERR" )
1717 || open( OUT, ">&STDOUT" ); # so we don't dongle stdout
1718
1719 } ## end if ($console)
1720 elsif ( not defined $console ) {
1721
1722 # No console. Open STDIN.
1723 open( IN, "<&STDIN" );
1724
1725 # merge with STDERR, or with STDOUT.
1726 open( OUT, ">&STDERR" )
1727 || open( OUT, ">&STDOUT" ); # so we don't dongle stdout
1728 $console = 'STDIN/OUT';
69893cff
RGS
1729 } ## end elsif (not defined $console)
1730
1731 # Keep copies of the filehandles so that when the pager runs, it
1732 # can close standard input without clobbering ours.
e22ea7cc
RF
1733 $IN = \*IN, $OUT = \*OUT if $console or not defined $console;
1734 } ## end elsif (from if(defined $remoteport))
1735
1736 # Unbuffer DB::OUT. We need to see responses right away.
1737 my $previous = select($OUT);
1738 $| = 1; # for DB::OUT
1739 select($previous);
1740
1741 # Line info goes to debugger output unless pointed elsewhere.
1742 # Pointing elsewhere makes it possible for slave editors to
1743 # keep track of file and position. We have both a filehandle
1744 # and a I/O description to keep track of.
1745 $LINEINFO = $OUT unless defined $LINEINFO;
1746 $lineinfo = $console unless defined $lineinfo;
2cbb2ee1
RGS
1747 # share($LINEINFO); # <- unable to share globs
1748 share($lineinfo); #
e22ea7cc 1749
69893cff
RGS
1750=pod
1751
1752To finish initialization, we show the debugger greeting,
1753and then call the C<afterinit()> subroutine if there is one.
1754
1755=cut
d12a4851 1756
e22ea7cc
RF
1757 # Show the debugger greeting.
1758 $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/;
1759 unless ($runnonstop) {
1760 local $\ = '';
1761 local $, = '';
1762 if ( $term_pid eq '-1' ) {
1763 print $OUT "\nDaughter DB session started...\n";
1764 }
1765 else {
1766 print $OUT "\nLoading DB routines from $header\n";
1767 print $OUT (
1768 "Editor support ",
1769 $slave_editor ? "enabled" : "available", ".\n"
1770 );
1771 print $OUT
69893cff
RGS
1772"\nEnter h or `h h' for help, or `$doccmd perldebug' for more help.\n\n";
1773 } ## end else [ if ($term_pid eq '-1')
1774 } ## end unless ($runnonstop)
1775} ## end else [ if ($notty)
1776
1777# XXX This looks like a bug to me.
1778# Why copy to @ARGS and then futz with @args?
d338d6fe
PP
1779@ARGS = @ARGV;
1780for (@args) {
69893cff
RGS
1781 # Make sure backslashes before single quotes are stripped out, and
1782 # keep args unless they are numeric (XXX why?)
e22ea7cc
RF
1783 # s/\'/\\\'/g; # removed while not justified understandably
1784 # s/(.*)/'$1'/ unless /^-?[\d.]+$/; # ditto
d338d6fe
PP
1785}
1786
e22ea7cc 1787# If there was an afterinit() sub defined, call it. It will get
69893cff 1788# executed in our scope, so it can fiddle with debugger globals.
e22ea7cc 1789if ( defined &afterinit ) { # May be defined in $rcfile
69893cff 1790 &afterinit();
d338d6fe 1791}
e22ea7cc 1792
69893cff 1793# Inform us about "Stack dump during die enabled ..." in dieLevel().
43aed9ee
IZ
1794$I_m_init = 1;
1795
d338d6fe
PP
1796############################################################ Subroutines
1797
69893cff
RGS
1798=head1 SUBROUTINES
1799
1800=head2 DB
1801
1802This gigantic subroutine is the heart of the debugger. Called before every
1803statement, its job is to determine if a breakpoint has been reached, and
1804stop if so; read commands from the user, parse them, and execute
1805them, and hen send execution off to the next statement.
1806
1807Note that the order in which the commands are processed is very important;
1808some commands earlier in the loop will actually alter the C<$cmd> variable
1809to create other commands to be executed later. This is all highly "optimized"
1810but can be confusing. Check the comments for each C<$cmd ... && do {}> to
1811see what's happening in any given command.
1812
1813=cut
1814
d338d6fe 1815sub DB {
69893cff 1816
2cbb2ee1
RGS
1817 # lock the debugger and get the thread id for the prompt
1818 lock($DBGR);
1819 my $tid;
1820 if ($ENV{PERL5DB_THREADED}) {
1821 $tid = eval { "[".threads->self->tid."]" };
1822 }
1823
69893cff 1824 # Check for whether we should be running continuously or not.
36477c24 1825 # _After_ the perl program is compiled, $single is set to 1:
e22ea7cc
RF
1826 if ( $single and not $second_time++ ) {
1827
69893cff 1828 # Options say run non-stop. Run until we get an interrupt.
e22ea7cc
RF
1829 if ($runnonstop) { # Disable until signal
1830 # If there's any call stack in place, turn off single
1831 # stepping into subs throughout the stack.
1832 for ( $i = 0 ; $i <= $stack_depth ; ) {
1833 $stack[ $i++ ] &= ~1;
1834 }
1835
69893cff 1836 # And we are now no longer in single-step mode.
e22ea7cc 1837 $single = 0;
69893cff
RGS
1838
1839 # If we simply returned at this point, we wouldn't get
1840 # the trace info. Fall on through.
e22ea7cc 1841 # return;
69893cff
RGS
1842 } ## end if ($runnonstop)
1843
e22ea7cc
RF
1844 elsif ($ImmediateStop) {
1845
1846 # We are supposed to stop here; XXX probably a break.
1847 $ImmediateStop = 0; # We've processed it; turn it off
1848 $signal = 1; # Simulate an interrupt to force
1849 # us into the command loop
69893cff
RGS
1850 }
1851 } ## end if ($single and not $second_time...
1852
1853 # If we're in single-step mode, or an interrupt (real or fake)
1854 # has occurred, turn off non-stop mode.
1855 $runnonstop = 0 if $single or $signal;
1856
1857 # Preserve current values of $@, $!, $^E, $,, $/, $\, $^W.
1858 # The code being debugged may have altered them.
d338d6fe 1859 &save;
69893cff
RGS
1860
1861 # Since DB::DB gets called after every line, we can use caller() to
1862 # figure out where we last were executing. Sneaky, eh? This works because
e22ea7cc 1863 # caller is returning all the extra information when called from the
69893cff 1864 # debugger.
e22ea7cc 1865 local ( $package, $filename, $line ) = caller;
471505cc 1866 local $filename_ini = $filename;
69893cff
RGS
1867
1868 # set up the context for DB::eval, so it can properly execute
1869 # code on behalf of the user. We add the package in so that the
1870 # code is eval'ed in the proper package (not in the debugger!).
1871 local $usercontext =
e22ea7cc 1872 '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' . "package $package;";
69893cff
RGS
1873
1874 # Create an alias to the active file magical array to simplify
1875 # the code here.
e22ea7cc 1876 local (*dbline) = $main::{ '_<' . $filename };
aa057b67
CN
1877
1878 # we need to check for pseudofiles on Mac OS (these are files
1879 # not attached to a filename, but instead stored in Dev:Pseudo)
e22ea7cc
RF
1880 if ( $^O eq 'MacOS' && $#dbline < 0 ) {
1881 $filename_ini = $filename = 'Dev:Pseudo';
1882 *dbline = $main::{ '_<' . $filename };
aa057b67
CN
1883 }
1884
69893cff 1885 # Last line in the program.
471505cc 1886 local $max = $#dbline;
69893cff
RGS
1887
1888 # if we have something here, see if we should break.
e22ea7cc
RF
1889 if ( $dbline{$line}
1890 && ( ( $stop, $action ) = split( /\0/, $dbline{$line} ) ) )
1891 {
1892
69893cff 1893 # Stop if the stop criterion says to just stop.
e22ea7cc 1894 if ( $stop eq '1' ) {
69893cff
RGS
1895 $signal |= 1;
1896 }
e22ea7cc 1897
69893cff
RGS
1898 # It's a conditional stop; eval it in the user's context and
1899 # see if we should stop. If so, remove the one-time sigil.
1900 elsif ($stop) {
e22ea7cc 1901 $evalarg = "\$DB::signal |= 1 if do {$stop}";
69893cff
RGS
1902 &eval;
1903 $dbline{$line} =~ s/;9($|\0)/$1/;
1904 }
1905 } ## end if ($dbline{$line} && ...
1906
1907 # Preserve the current stop-or-not, and see if any of the W
1908 # (watch expressions) has changed.
36477c24 1909 my $was_signal = $signal;
69893cff
RGS
1910
1911 # If we have any watch expressions ...
e22ea7cc
RF
1912 if ( $trace & 2 ) {
1913 for ( my $n = 0 ; $n <= $#to_watch ; $n++ ) {
1914 $evalarg = $to_watch[$n];
1915 local $onetimeDump; # Tell DB::eval() to not output results
69893cff
RGS
1916
1917 # Fix context DB::eval() wants to return an array, but
1918 # we need a scalar here.
e22ea7cc
RF
1919 my ($val) = join( "', '", &eval );
1920 $val = ( ( defined $val ) ? "'$val'" : 'undef' );
69893cff
RGS
1921
1922 # Did it change?
e22ea7cc
RF
1923 if ( $val ne $old_watch[$n] ) {
1924
69893cff 1925 # Yep! Show the difference, and fake an interrupt.
e22ea7cc
RF
1926 $signal = 1;
1927 print $OUT <<EOP;
405ff068 1928Watchpoint $n:\t$to_watch[$n] changed:
69893cff
RGS
1929 old value:\t$old_watch[$n]
1930 new value:\t$val
6027b9a3 1931EOP
e22ea7cc 1932 $old_watch[$n] = $val;
69893cff
RGS
1933 } ## end if ($val ne $old_watch...
1934 } ## end for (my $n = 0 ; $n <= ...
1935 } ## end if ($trace & 2)
1936
1937=head2 C<watchfunction()>
1938
1939C<watchfunction()> is a function that can be defined by the user; it is a
1940function which will be run on each entry to C<DB::DB>; it gets the
1941current package, filename, and line as its parameters.
1942
1943The watchfunction can do anything it likes; it is executing in the
1944debugger's context, so it has access to all of the debugger's internal
1945data structures and functions.
1946
1947C<watchfunction()> can control the debugger's actions. Any of the following
1948will cause the debugger to return control to the user's program after
1949C<watchfunction()> executes:
1950
1951=over 4
1952
1953=item * Returning a false value from the C<watchfunction()> itself.
1954
1955=item * Altering C<$single> to a false value.
1956
1957=item * Altering C<$signal> to a false value.
1958
1959=item * Turning off the '4' bit in C<$trace> (this also disables the
1960check for C<watchfunction()>. This can be done with
1961
1962 $trace &= ~4;
1963
1964=back
1965
1966=cut
1967
e22ea7cc 1968 # If there's a user-defined DB::watchfunction, call it with the
69893cff
RGS
1969 # current package, filename, and line. The function executes in
1970 # the DB:: package.
e22ea7cc
RF
1971 if ( $trace & 4 ) { # User-installed watch
1972 return
1973 if watchfunction( $package, $filename, $line )
1974 and not $single
1975 and not $was_signal
1976 and not( $trace & ~4 );
69893cff
RGS
1977 } ## end if ($trace & 4)
1978
e22ea7cc 1979 # Pick up any alteration to $signal in the watchfunction, and
69893cff 1980 # turn off the signal now.
6027b9a3 1981 $was_signal = $signal;
69893cff
RGS
1982 $signal = 0;
1983
1984=head2 GETTING READY TO EXECUTE COMMANDS
1985
1986The debugger decides to take control if single-step mode is on, the
1987C<t> command was entered, or the user generated a signal. If the program
1988has fallen off the end, we set things up so that entering further commands
1989won't cause trouble, and we say that the program is over.
1990
1991=cut
1992
1993 # Check to see if we should grab control ($single true,
1994 # trace set appropriately, or we got a signal).
e22ea7cc
RF
1995 if ( $single || ( $trace & 1 ) || $was_signal ) {
1996
69893cff 1997 # Yes, grab control.
e22ea7cc
RF
1998 if ($slave_editor) {
1999
69893cff 2000 # Tell the editor to update its position.
e22ea7cc
RF
2001 $position = "\032\032$filename:$line:0\n";
2002 print_lineinfo($position);
2003 }
69893cff
RGS
2004
2005=pod
2006
2007Special check: if we're in package C<DB::fake>, we've gone through the
2008C<END> block at least once. We set up everything so that we can continue
2009to enter commands and have a valid context to be in.
2010
2011=cut
2012
e22ea7cc 2013 elsif ( $package eq 'DB::fake' ) {
69893cff 2014
69893cff 2015 # Fallen off the end already.
e22ea7cc
RF
2016 $term || &setterm;
2017 print_help(<<EOP);
405ff068
IZ
2018Debugged program terminated. Use B<q> to quit or B<R> to restart,
2019 use B<O> I<inhibit_exit> to avoid stopping after program termination,
2020 B<h q>, B<h R> or B<h O> to get additional info.
2021EOP
e22ea7cc 2022
69893cff 2023 # Set the DB::eval context appropriately.
e22ea7cc
RF
2024 $package = 'main';
2025 $usercontext =
2026 '($@, $!, $^E, $,, $/, $\, $^W) = @saved;'
2027 . "package $package;"; # this won't let them modify, alas
69893cff 2028 } ## end elsif ($package eq 'DB::fake')
e219e2fb 2029
69893cff 2030=pod
e219e2fb 2031
69893cff
RGS
2032If the program hasn't finished executing, we scan forward to the
2033next executable line, print that out, build the prompt from the file and line
2034number information, and print that.
e219e2fb 2035
69893cff
RGS
2036=cut
2037
e22ea7cc
RF
2038 else {
2039
69893cff
RGS
2040 # Still somewhere in the midst of execution. Set up the
2041 # debugger prompt.
2042 $sub =~ s/\'/::/; # Swap Perl 4 package separators (') to
e22ea7cc 2043 # Perl 5 ones (sorry, we don't print Klingon
69893cff
RGS
2044 #module names)
2045
e22ea7cc
RF
2046 $prefix = $sub =~ /::/ ? "" : "${'package'}::";
2047 $prefix .= "$sub($filename:";
2048 $after = ( $dbline[$line] =~ /\n$/ ? '' : "\n" );
69893cff
RGS
2049
2050 # Break up the prompt if it's really long.
e22ea7cc
RF
2051 if ( length($prefix) > 30 ) {
2052 $position = "$prefix$line):\n$line:\t$dbline[$line]$after";
2053 $prefix = "";
2054 $infix = ":\t";
2055 }
2056 else {
2057 $infix = "):\t";
2058 $position = "$prefix$line$infix$dbline[$line]$after";
2059 }
69893cff
RGS
2060
2061 # Print current line info, indenting if necessary.
e22ea7cc
RF
2062 if ($frame) {
2063 print_lineinfo( ' ' x $stack_depth,
2064 "$line:\t$dbline[$line]$after" );
2065 }
2066 else {
2067 print_lineinfo($position);
2068 }
69893cff
RGS
2069
2070 # Scan forward, stopping at either the end or the next
2071 # unbreakable line.
e22ea7cc
RF
2072 for ( $i = $line + 1 ; $i <= $max && $dbline[$i] == 0 ; ++$i )
2073 { #{ vi
69893cff
RGS
2074
2075 # Drop out on null statements, block closers, and comments.
2076 last if $dbline[$i] =~ /^\s*[\;\}\#\n]/;
2077
2078 # Drop out if the user interrupted us.
2079 last if $signal;
2080
2081 # Append a newline if the line doesn't have one. Can happen
2082 # in eval'ed text, for instance.
e22ea7cc 2083 $after = ( $dbline[$i] =~ /\n$/ ? '' : "\n" );
69893cff
RGS
2084
2085 # Next executable line.
2086 $incr_pos = "$prefix$i$infix$dbline[$i]$after";
2087 $position .= $incr_pos;
2088 if ($frame) {
e22ea7cc 2089
69893cff 2090 # Print it indented if tracing is on.
e22ea7cc
RF
2091 print_lineinfo( ' ' x $stack_depth,
2092 "$i:\t$dbline[$i]$after" );
69893cff
RGS
2093 }
2094 else {
2095 print_lineinfo($incr_pos);
2096 }
2097 } ## end for ($i = $line + 1 ; $i...
2098 } ## end else [ if ($slave_editor)
2099 } ## end if ($single || ($trace...
2100
2101=pod
2102
2103If there's an action to be executed for the line we stopped at, execute it.
2104If there are any preprompt actions, execute those as well.
e219e2fb
RF
2105
2106=cut
2107
69893cff
RGS
2108 # If there's an action, do it now.
2109 $evalarg = $action, &eval if $action;
e219e2fb 2110
69893cff
RGS
2111 # Are we nested another level (e.g., did we evaluate a function
2112 # that had a breakpoint in it at the debugger prompt)?
e22ea7cc
RF
2113 if ( $single || $was_signal ) {
2114
69893cff 2115 # Yes, go down a level.
e22ea7cc 2116 local $level = $level + 1;
69893cff
RGS
2117
2118 # Do any pre-prompt actions.
e22ea7cc
RF
2119 foreach $evalarg (@$pre) {
2120 &eval;
2121 }
69893cff
RGS
2122
2123 # Complain about too much recursion if we passed the limit.
e22ea7cc 2124 print $OUT $stack_depth . " levels deep in subroutine calls!\n"
69893cff
RGS
2125 if $single & 4;
2126
2127 # The line we're currently on. Set $incr to -1 to stay here
2128 # until we get a command that tells us to advance.
e22ea7cc
RF
2129 $start = $line;
2130 $incr = -1; # for backward motion.
69893cff
RGS
2131
2132 # Tack preprompt debugger actions ahead of any actual input.
e22ea7cc 2133 @typeahead = ( @$pretype, @typeahead );
69893cff
RGS
2134
2135=head2 WHERE ARE WE?
2136
2137XXX Relocate this section?
2138
2139The debugger normally shows the line corresponding to the current line of
2140execution. Sometimes, though, we want to see the next line, or to move elsewhere
2141in the file. This is done via the C<$incr>, C<$start>, and C<$max> variables.
2142
2143C<$incr> controls by how many lines the "current" line should move forward
2144after a command is executed. If set to -1, this indicates that the "current"
2145line shouldn't change.
2146
2147C<$start> is the "current" line. It is used for things like knowing where to
2148move forwards or backwards from when doing an C<L> or C<-> command.
2149
2150C<$max> tells the debugger where the last line of the current file is. It's
2151used to terminate loops most often.
2152
2153=head2 THE COMMAND LOOP
2154
2155Most of C<DB::DB> is actually a command parsing and dispatch loop. It comes
2156in two parts:
2157
2158=over 4
2159
2160=item * The outer part of the loop, starting at the C<CMD> label. This loop
2161reads a command and then executes it.
2162
2163=item * The inner part of the loop, starting at the C<PIPE> label. This part
2164is wholly contained inside the C<CMD> block and only executes a command.
2165Used to handle commands running inside a pager.
2166
2167=back
2168
2169So why have two labels to restart the loop? Because sometimes, it's easier to
2170have a command I<generate> another command and then re-execute the loop to do
2171the new command. This is faster, but perhaps a bit more convoluted.
2172
2173=cut
2174
2175 # The big command dispatch loop. It keeps running until the
2176 # user yields up control again.
2177 #
2178 # If we have a terminal for input, and we get something back
2179 # from readline(), keep on processing.
e22ea7cc
RF
2180 CMD:
2181 while (
2182
69893cff 2183 # We have a terminal, or can get one ...
e22ea7cc
RF
2184 ( $term || &setterm ),
2185
69893cff 2186 # ... and it belogs to this PID or we get one for this PID ...
e22ea7cc
RF
2187 ( $term_pid == $$ or resetterm(1) ),
2188
69893cff 2189 # ... and we got a line of command input ...
e22ea7cc
RF
2190 defined(
2191 $cmd = &readline(
2cbb2ee1 2192 "$pidprompt $tid DB"
e22ea7cc
RF
2193 . ( '<' x $level )
2194 . ( $#hist + 1 )
2195 . ( '>' x $level ) . " "
69893cff
RGS
2196 )
2197 )
2198 )
2199 {
e22ea7cc 2200
2cbb2ee1 2201 share($cmd);
69893cff
RGS
2202 # ... try to execute the input as debugger commands.
2203
2204 # Don't stop running.
2205 $single = 0;
2206
2207 # No signal is active.
2208 $signal = 0;
2209
2210 # Handle continued commands (ending with \):
e22ea7cc
RF
2211 $cmd =~ s/\\$/\n/ && do {
2212 $cmd .= &readline(" cont: ");
2213 redo CMD;
2214 };
69893cff
RGS
2215
2216=head4 The null command
2217
2218A newline entered by itself means "re-execute the last command". We grab the
2219command out of C<$laststep> (where it was recorded previously), and copy it
2220back into C<$cmd> to be executed below. If there wasn't any previous command,
2221we'll do nothing below (no command will match). If there was, we also save it
2222in the command history and fall through to allow the command parsing to pick
2223it up.
2224
2225=cut
2226
2227 # Empty input means repeat the last command.
e22ea7cc
RF
2228 $cmd =~ /^$/ && ( $cmd = $laststep );
2229 chomp($cmd); # get rid of the annoying extra newline
2230 push( @hist, $cmd ) if length($cmd) > 1;
2231 push( @truehist, $cmd );
2cbb2ee1
RGS
2232 share(@hist);
2233 share(@truehist);
e22ea7cc
RF
2234
2235 # This is a restart point for commands that didn't arrive
2236 # via direct user input. It allows us to 'redo PIPE' to
2237 # re-execute command processing without reading a new command.
69893cff 2238 PIPE: {
e22ea7cc
RF
2239 $cmd =~ s/^\s+//s; # trim annoying leading whitespace
2240 $cmd =~ s/\s+$//s; # trim annoying trailing whitespace
2241 ($i) = split( /\s+/, $cmd );
69893cff
RGS
2242
2243=head3 COMMAND ALIASES
2244
2245The debugger can create aliases for commands (these are stored in the
2246C<%alias> hash). Before a command is executed, the command loop looks it up
2247in the alias hash and substitutes the contents of the alias for the command,
2248completely replacing it.
2249
2250=cut
2251
2252 # See if there's an alias for the command, and set it up if so.
e22ea7cc
RF
2253 if ( $alias{$i} ) {
2254
69893cff
RGS
2255 # Squelch signal handling; we want to keep control here
2256 # if something goes loco during the alias eval.
2257 local $SIG{__DIE__};
2258 local $SIG{__WARN__};
2259
2260 # This is a command, so we eval it in the DEBUGGER's
2261 # scope! Otherwise, we can't see the special debugger
2262 # variables, or get to the debugger's subs. (Well, we
2263 # _could_, but why make it even more complicated?)
2264 eval "\$cmd =~ $alias{$i}";
2265 if ($@) {
2266 local $\ = '';
2267 print $OUT "Couldn't evaluate `$i' alias: $@";
2268 next CMD;
2269 }
2270 } ## end if ($alias{$i})
2271
2272=head3 MAIN-LINE COMMANDS
2273
2274All of these commands work up to and after the program being debugged has
2275terminated.
2276
2277=head4 C<q> - quit
2278
2279Quit the debugger. This entails setting the C<$fall_off_end> flag, so we don't
2280try to execute further, cleaning any restart-related stuff out of the
2281environment, and executing with the last value of C<$?>.
2282
2283=cut
2284
2285 $cmd =~ /^q$/ && do {
2286 $fall_off_end = 1;
2287 clean_ENV();
2288 exit $?;
2289 };
2290
2291=head4 C<t> - trace
2292
2293Turn tracing on or off. Inverts the appropriate bit in C<$trace> (q.v.).
2294
2295=cut
2296
e22ea7cc
RF
2297 $cmd =~ /^t$/ && do {
2298 $trace ^= 1;
2299 local $\ = '';
2300 print $OUT "Trace = "
2301 . ( ( $trace & 1 ) ? "on" : "off" ) . "\n";
2302 next CMD;
2303 };
69893cff
RGS
2304
2305=head4 C<S> - list subroutines matching/not matching a pattern
2306
2307Walks through C<%sub>, checking to see whether or not to print the name.
2308
2309=cut
2310
e22ea7cc 2311 $cmd =~ /^S(\s+(!)?(.+))?$/ && do {
69893cff 2312
e22ea7cc 2313 $Srev = defined $2; # Reverse scan?
69893cff
RGS
2314 $Spatt = $3; # The pattern (if any) to use.
2315 $Snocheck = !defined $1; # No args - print all subs.
2316
2317 # Need to make these sane here.
e22ea7cc
RF
2318 local $\ = '';
2319 local $, = '';
69893cff
RGS
2320
2321 # Search through the debugger's magical hash of subs.
2322 # If $nocheck is true, just print the sub name.
2323 # Otherwise, check it against the pattern. We then use
2324 # the XOR trick to reverse the condition as required.
e22ea7cc
RF
2325 foreach $subname ( sort( keys %sub ) ) {
2326 if ( $Snocheck or $Srev ^ ( $subname =~ /$Spatt/ ) ) {
2327 print $OUT $subname, "\n";
2328 }
2329 }
2330 next CMD;
2331 };
69893cff
RGS
2332
2333=head4 C<X> - list variables in current package
2334
2335Since the C<V> command actually processes this, just change this to the
2336appropriate C<V> command and fall through.
2337
2338=cut
2339
e22ea7cc 2340 $cmd =~ s/^X\b/V $package/;
69893cff
RGS
2341
2342=head4 C<V> - list variables
2343
2344Uses C<dumpvar.pl> to dump out the current values for selected variables.
2345
2346=cut
2347
2348 # Bare V commands get the currently-being-debugged package
2349 # added.
e22ea7cc
RF
2350 $cmd =~ /^V$/ && do {
2351 $cmd = "V $package";
2352 };
69893cff
RGS
2353
2354 # V - show variables in package.
2355 $cmd =~ /^V\b\s*(\S+)\s*(.*)/ && do {
e22ea7cc 2356
69893cff
RGS
2357 # Save the currently selected filehandle and
2358 # force output to debugger's filehandle (dumpvar
2359 # just does "print" for output).
e22ea7cc 2360 local ($savout) = select($OUT);
69893cff
RGS
2361
2362 # Grab package name and variables to dump.
e22ea7cc
RF
2363 $packname = $1;
2364 @vars = split( ' ', $2 );
69893cff
RGS
2365
2366 # If main::dumpvar isn't here, get it.
e22ea7cc
RF
2367 do 'dumpvar.pl' unless defined &main::dumpvar;
2368 if ( defined &main::dumpvar ) {
2369
69893cff
RGS
2370 # We got it. Turn off subroutine entry/exit messages
2371 # for the moment, along with return values.
e22ea7cc
RF
2372 local $frame = 0;
2373 local $doret = -2;
69893cff
RGS
2374
2375 # must detect sigpipe failures - not catching
2376 # then will cause the debugger to die.
2377 eval {
2378 &main::dumpvar(
2379 $packname,
2380 defined $option{dumpDepth}
e22ea7cc
RF
2381 ? $option{dumpDepth}
2382 : -1, # assume -1 unless specified
69893cff 2383 @vars
e22ea7cc
RF
2384 );
2385 };
2386
2387 # The die doesn't need to include the $@, because
2388 # it will automatically get propagated for us.
2389 if ($@) {
2390 die unless $@ =~ /dumpvar print failed/;
2391 }
2392 } ## end if (defined &main::dumpvar)
2393 else {
2394
2395 # Couldn't load dumpvar.
2396 print $OUT "dumpvar.pl not available.\n";
2397 }
69893cff 2398
69893cff 2399 # Restore the output filehandle, and go round again.
e22ea7cc
RF
2400 select($savout);
2401 next CMD;
2402 };
69893cff
RGS
2403
2404=head4 C<x> - evaluate and print an expression
2405
2406Hands the expression off to C<DB::eval>, setting it up to print the value
2407via C<dumpvar.pl> instead of just printing it directly.
2408
2409=cut
2410
e22ea7cc
RF
2411 $cmd =~ s/^x\b/ / && do { # Remainder gets done by DB::eval()
2412 $onetimeDump = 'dump'; # main::dumpvar shows the output
69893cff
RGS
2413
2414 # handle special "x 3 blah" syntax XXX propagate
2415 # doc back to special variables.
e22ea7cc
RF
2416 if ( $cmd =~ s/^\s*(\d+)(?=\s)/ / ) {
2417 $onetimedumpDepth = $1;
2418 }
2419 };
69893cff
RGS
2420
2421=head4 C<m> - print methods
2422
2423Just uses C<DB::methods> to determine what methods are available.
2424
2425=cut
2426
e22ea7cc
RF
2427 $cmd =~ s/^m\s+([\w:]+)\s*$/ / && do {
2428 methods($1);
2429 next CMD;
2430 };
69893cff
RGS
2431
2432 # m expr - set up DB::eval to do the work
e22ea7cc
RF
2433 $cmd =~ s/^m\b/ / && do { # Rest gets done by DB::eval()
2434 $onetimeDump = 'methods'; # method output gets used there
2435 };
69893cff
RGS
2436
2437=head4 C<f> - switch files
2438
2439=cut
2440
e22ea7cc
RF
2441 $cmd =~ /^f\b\s*(.*)/ && do {
2442 $file = $1;
2443 $file =~ s/\s+$//;
69893cff
RGS
2444
2445 # help for no arguments (old-style was return from sub).
e22ea7cc
RF
2446 if ( !$file ) {
2447 print $OUT
2448 "The old f command is now the r command.\n"; # hint
2449 print $OUT "The new f command switches filenames.\n";
2450 next CMD;
2451 } ## end if (!$file)
69893cff
RGS
2452
2453 # if not in magic file list, try a close match.
e22ea7cc
RF
2454 if ( !defined $main::{ '_<' . $file } ) {
2455 if ( ($try) = grep( m#^_<.*$file#, keys %main:: ) ) {
2456 {
2457 $try = substr( $try, 2 );
2458 print $OUT "Choosing $try matching `$file':\n";
2459 $file = $try;
2460 }
2461 } ## end if (($try) = grep(m#^_<.*$file#...
2462 } ## end if (!defined $main::{ ...
69893cff
RGS
2463
2464 # If not successfully switched now, we failed.
e22ea7cc
RF
2465 if ( !defined $main::{ '_<' . $file } ) {
2466 print $OUT "No file matching `$file' is loaded.\n";
2467 next CMD;
2468 }
69893cff 2469
e22ea7cc
RF
2470 # We switched, so switch the debugger internals around.
2471 elsif ( $file ne $filename ) {
2472 *dbline = $main::{ '_<' . $file };
2473 $max = $#dbline;
2474 $filename = $file;
2475 $start = 1;
2476 $cmd = "l";
2477 } ## end elsif ($file ne $filename)
2478
2479 # We didn't switch; say we didn't.
2480 else {
2481 print $OUT "Already in $file.\n";
2482 next CMD;
2483 }
2484 };
69893cff
RGS
2485
2486=head4 C<.> - return to last-executed line.
2487
2488We set C<$incr> to -1 to indicate that the debugger shouldn't move ahead,
2489and then we look up the line in the magical C<%dbline> hash.
2490
2491=cut
2492
2493 # . command.
e22ea7cc
RF
2494 $cmd =~ /^\.$/ && do {
2495 $incr = -1; # stay at current line
69893cff
RGS
2496
2497 # Reset everything to the old location.
e22ea7cc
RF
2498 $start = $line;
2499 $filename = $filename_ini;
2500 *dbline = $main::{ '_<' . $filename };
2501 $max = $#dbline;
69893cff
RGS
2502
2503 # Now where are we?
e22ea7cc
RF
2504 print_lineinfo($position);
2505 next CMD;
2506 };
69893cff
RGS
2507
2508=head4 C<-> - back one window
2509
2510We change C<$start> to be one window back; if we go back past the first line,
2511we set it to be the first line. We ser C<$incr> to put us back at the
2512currently-executing line, and then put a C<l $start +> (list one window from
2513C<$start>) in C<$cmd> to be executed later.
2514
2515=cut
2516
2517 # - - back a window.
e22ea7cc
RF
2518 $cmd =~ /^-$/ && do {
2519
69893cff 2520 # back up by a window; go to 1 if back too far.
e22ea7cc
RF
2521 $start -= $incr + $window + 1;
2522 $start = 1 if $start <= 0;
2523 $incr = $window - 1;
69893cff
RGS
2524
2525 # Generate and execute a "l +" command (handled below).
e22ea7cc
RF
2526 $cmd = 'l ' . ($start) . '+';
2527 };
69893cff
RGS
2528
2529=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>, {, {{>
2530
2531In Perl 5.8.0, a realignment of the commands was done to fix up a number of
2532problems, most notably that the default case of several commands destroying
2533the user's work in setting watchpoints, actions, etc. We wanted, however, to
2534retain the old commands for those who were used to using them or who preferred
2535them. At this point, we check for the new commands and call C<cmd_wrapper> to
2536deal with them instead of processing them in-line.
2537
2538=cut
2539
2540 # All of these commands were remapped in perl 5.8.0;
e22ea7cc 2541 # we send them off to the secondary dispatcher (see below).
2cbb2ee1 2542 $cmd =~ /^([aAbBeEhilLMoOPvwW]\b|[<>\{]{1,2})\s*(.*)/so && do {
e22ea7cc
RF
2543 &cmd_wrapper( $1, $2, $line );
2544 next CMD;
2545 };
69893cff
RGS
2546
2547=head4 C<y> - List lexicals in higher scope
2548
2549Uses C<PadWalker> to find the lexicals supplied as arguments in a scope
2550above the current one and then displays then using C<dumpvar.pl>.
2551
2552=cut
2553
2554 $cmd =~ /^y(?:\s+(\d*)\s*(.*))?$/ && do {
2555
2556 # See if we've got the necessary support.
2557 eval { require PadWalker; PadWalker->VERSION(0.08) }
2558 or &warn(
2559 $@ =~ /locate/
2560 ? "PadWalker module not found - please install\n"
2561 : $@
2562 )
2563 and next CMD;
2564
2565 # Load up dumpvar if we don't have it. If we can, that is.
2566 do 'dumpvar.pl' unless defined &main::dumpvar;
2567 defined &main::dumpvar
2568 or print $OUT "dumpvar.pl not available.\n"
2569 and next CMD;
2570
2571 # Got all the modules we need. Find them and print them.
e22ea7cc 2572 my @vars = split( ' ', $2 || '' );
69893cff
RGS
2573
2574 # Find the pad.
e22ea7cc 2575 my $h = eval { PadWalker::peek_my( ( $1 || 0 ) + 1 ) };
69893cff
RGS
2576
2577 # Oops. Can't find it.
2578 $@ and $@ =~ s/ at .*//, &warn($@), next CMD;
2579
2580 # Show the desired vars with dumplex().
2581 my $savout = select($OUT);
2582
2583 # Have dumplex dump the lexicals.
e22ea7cc 2584 dumpvar::dumplex( $_, $h->{$_},
69893cff 2585 defined $option{dumpDepth} ? $option{dumpDepth} : -1,
e22ea7cc
RF
2586 @vars )
2587 for sort keys %$h;
69893cff
RGS
2588 select($savout);
2589 next CMD;
2590 };
2591
2592=head3 COMMANDS NOT WORKING AFTER PROGRAM ENDS
2593
2594All of the commands below this point don't work after the program being
2595debugged has ended. All of them check to see if the program has ended; this
2596allows the commands to be relocated without worrying about a 'line of
2597demarcation' above which commands can be entered anytime, and below which
2598they can't.
2599
2600=head4 C<n> - single step, but don't trace down into subs
2601
2602Done by setting C<$single> to 2, which forces subs to execute straight through
2603when entered (see X<DB::sub>). We also save the C<n> command in C<$laststep>,
2604so a null command knows what to re-execute.
2605
2606=cut
2607
e22ea7cc 2608 # n - next
69893cff
RGS
2609 $cmd =~ /^n$/ && do {
2610 end_report(), next CMD if $finished and $level <= 1;
e22ea7cc 2611
69893cff
RGS
2612 # Single step, but don't enter subs.
2613 $single = 2;
e22ea7cc 2614
69893cff 2615 # Save for empty command (repeat last).
e22ea7cc
RF
2616 $laststep = $cmd;
2617 last CMD;
2618 };
69893cff
RGS
2619
2620=head4 C<s> - single-step, entering subs
2621
2622Sets C<$single> to 1, which causes X<DB::sub> to continue tracing inside
2623subs. Also saves C<s> as C<$lastcmd>.
2624
2625=cut
2626
2627 # s - single step.
2628 $cmd =~ /^s$/ && do {
e22ea7cc 2629
69893cff
RGS
2630 # Get out and restart the command loop if program
2631 # has finished.
e22ea7cc
RF
2632 end_report(), next CMD if $finished and $level <= 1;
2633
69893cff 2634 # Single step should enter subs.
e22ea7cc
RF
2635 $single = 1;
2636
69893cff 2637 # Save for empty command (repeat last).
e22ea7cc
RF
2638 $laststep = $cmd;
2639 last CMD;
2640 };
69893cff
RGS
2641
2642=head4 C<c> - run continuously, setting an optional breakpoint
2643
2644Most of the code for this command is taken up with locating the optional
2645breakpoint, which is either a subroutine name or a line number. We set
2646the appropriate one-time-break in C<@dbline> and then turn off single-stepping
2647in this and all call levels above this one.
2648
2649=cut
2650
2651 # c - start continuous execution.
2652 $cmd =~ /^c\b\s*([\w:]*)\s*$/ && do {
e22ea7cc 2653
69893cff
RGS
2654 # Hey, show's over. The debugged program finished
2655 # executing already.
2656 end_report(), next CMD if $finished and $level <= 1;
2657
2658 # Capture the place to put a one-time break.
2659 $subname = $i = $1;
2660
e22ea7cc
RF
2661 # Probably not needed, since we finish an interactive
2662 # sub-session anyway...
2663 # local $filename = $filename;
2664 # local *dbline = *dbline; # XXX Would this work?!
69893cff
RGS
2665 #
2666 # The above question wonders if localizing the alias
2667 # to the magic array works or not. Since it's commented
2668 # out, we'll just leave that to speculation for now.
2669
2670 # If the "subname" isn't all digits, we'll assume it
2671 # is a subroutine name, and try to find it.
e22ea7cc
RF
2672 if ( $subname =~ /\D/ ) { # subroutine name
2673 # Qualify it to the current package unless it's
2674 # already qualified.
69893cff
RGS
2675 $subname = $package . "::" . $subname
2676 unless $subname =~ /::/;
e22ea7cc 2677
69893cff
RGS
2678 # find_sub will return "file:line_number" corresponding
2679 # to where the subroutine is defined; we call find_sub,
e22ea7cc 2680 # break up the return value, and assign it in one
69893cff 2681 # operation.
e22ea7cc 2682 ( $file, $i ) = ( find_sub($subname) =~ /^(.*):(.*)$/ );
69893cff
RGS
2683
2684 # Force the line number to be numeric.
e22ea7cc 2685 $i += 0;
69893cff
RGS
2686
2687 # If we got a line number, we found the sub.
e22ea7cc
RF
2688 if ($i) {
2689
69893cff
RGS
2690 # Switch all the debugger's internals around so
2691 # we're actually working with that file.
e22ea7cc
RF
2692 $filename = $file;
2693 *dbline = $main::{ '_<' . $filename };
2694
69893cff 2695 # Mark that there's a breakpoint in this file.
e22ea7cc
RF
2696 $had_breakpoints{$filename} |= 1;
2697
69893cff
RGS
2698 # Scan forward to the first executable line
2699 # after the 'sub whatever' line.
e22ea7cc
RF
2700 $max = $#dbline;
2701 ++$i while $dbline[$i] == 0 && $i < $max;
2702 } ## end if ($i)
69893cff
RGS
2703
2704 # We didn't find a sub by that name.
e22ea7cc
RF
2705 else {
2706 print $OUT "Subroutine $subname not found.\n";
2707 next CMD;
2708 }
2709 } ## end if ($subname =~ /\D/)
69893cff
RGS
2710
2711 # At this point, either the subname was all digits (an
2712 # absolute line-break request) or we've scanned through
2713 # the code following the definition of the sub, looking
2714 # for an executable, which we may or may not have found.
2715 #
2716 # If $i (which we set $subname from) is non-zero, we
e22ea7cc
RF
2717 # got a request to break at some line somewhere. On
2718 # one hand, if there wasn't any real subroutine name
2719 # involved, this will be a request to break in the current
2720 # file at the specified line, so we have to check to make
69893cff
RGS
2721 # sure that the line specified really is breakable.
2722 #
2723 # On the other hand, if there was a subname supplied, the
2724 # preceeding block has moved us to the proper file and
2725 # location within that file, and then scanned forward
2726 # looking for the next executable line. We have to make
2727 # sure that one was found.
2728 #
2729 # On the gripping hand, we can't do anything unless the
2730 # current value of $i points to a valid breakable line.
2731 # Check that.
e22ea7cc
RF
2732 if ($i) {
2733
69893cff 2734 # Breakable?
e22ea7cc
RF
2735 if ( $dbline[$i] == 0 ) {
2736 print $OUT "Line $i not breakable.\n";
2737 next CMD;
2738 }
2739
69893cff 2740 # Yes. Set up the one-time-break sigil.
e22ea7cc
RF
2741 $dbline{$i} =~ s/($|\0)/;9$1/; # add one-time-only b.p.
2742 } ## end if ($i)
69893cff
RGS
2743
2744 # Turn off stack tracing from here up.
e22ea7cc
RF
2745 for ( $i = 0 ; $i <= $stack_depth ; ) {
2746 $stack[ $i++ ] &= ~1;
2747 }
2748 last CMD;
2749 };
69893cff
RGS
2750
2751=head4 C<r> - return from a subroutine
2752
2753For C<r> to work properly, the debugger has to stop execution again
2754immediately after the return is executed. This is done by forcing
2755single-stepping to be on in the call level above the current one. If
2756we are printing return values when a C<r> is executed, set C<$doret>
2757appropriately, and force us out of the command loop.
2758
2759=cut
2760
2761 # r - return from the current subroutine.
e22ea7cc
RF
2762 $cmd =~ /^r$/ && do {
2763
69893cff 2764 # Can't do anythign if the program's over.
e22ea7cc
RF
2765 end_report(), next CMD if $finished and $level <= 1;
2766
69893cff 2767 # Turn on stack trace.
e22ea7cc
RF
2768 $stack[$stack_depth] |= 1;
2769
69893cff 2770 # Print return value unless the stack is empty.
e22ea7cc
RF
2771 $doret = $option{PrintRet} ? $stack_depth - 1 : -2;
2772 last CMD;
2773 };
69893cff 2774
69893cff
RGS
2775=head4 C<T> - stack trace
2776
2777Just calls C<DB::print_trace>.
2778
2779=cut
2780
e22ea7cc
RF
2781 $cmd =~ /^T$/ && do {
2782 print_trace( $OUT, 1 ); # skip DB
2783 next CMD;
2784 };
69893cff
RGS
2785
2786=head4 C<w> - List window around current line.
2787
2788Just calls C<DB::cmd_w>.
2789
2790=cut
2791
e22ea7cc 2792 $cmd =~ /^w\b\s*(.*)/s && do { &cmd_w( 'w', $1 ); next CMD; };
69893cff
RGS
2793
2794=head4 C<W> - watch-expression processing.
2795
2796Just calls C<DB::cmd_W>.
2797
2798=cut
2799
e22ea7cc 2800 $cmd =~ /^W\b\s*(.*)/s && do { &cmd_W( 'W', $1 ); next CMD; };
69893cff
RGS
2801
2802=head4 C</> - search forward for a string in the source
2803
2804We take the argument and treat it as a pattern. If it turns out to be a
2805bad one, we return the error we got from trying to C<eval> it and exit.
2806If not, we create some code to do the search and C<eval> it so it can't
2807mess us up.
2808
2809=cut
2810
e22ea7cc 2811 $cmd =~ /^\/(.*)$/ && do {
69893cff
RGS
2812
2813 # The pattern as a string.
e22ea7cc 2814 $inpat = $1;
69893cff
RGS
2815
2816 # Remove the final slash.
e22ea7cc 2817 $inpat =~ s:([^\\])/$:$1:;
69893cff
RGS
2818
2819 # If the pattern isn't null ...
e22ea7cc 2820 if ( $inpat ne "" ) {
69893cff
RGS
2821
2822 # Turn of warn and die procesing for a bit.
e22ea7cc
RF
2823 local $SIG{__DIE__};
2824 local $SIG{__WARN__};
69893cff
RGS
2825
2826 # Create the pattern.
e22ea7cc
RF
2827 eval '$inpat =~ m' . "\a$inpat\a";
2828 if ( $@ ne "" ) {
2829
69893cff 2830 # Oops. Bad pattern. No biscuit.
e22ea7cc 2831 # Print the eval error and go back for more
69893cff 2832 # commands.
e22ea7cc
RF
2833 print $OUT "$@";
2834 next CMD;
2835 }
2836 $pat = $inpat;
2837 } ## end if ($inpat ne "")
69893cff
RGS
2838
2839 # Set up to stop on wrap-around.
e22ea7cc 2840 $end = $start;
69893cff
RGS
2841
2842 # Don't move off the current line.
e22ea7cc 2843 $incr = -1;
69893cff
RGS
2844
2845 # Done in eval so nothing breaks if the pattern
2846 # does something weird.
e22ea7cc
RF
2847 eval '
2848 for (;;) {
69893cff 2849 # Move ahead one line.
e22ea7cc 2850 ++$start;
69893cff
RGS
2851
2852 # Wrap if we pass the last line.
e22ea7cc 2853 $start = 1 if ($start > $max);
69893cff
RGS
2854
2855 # Stop if we have gotten back to this line again,
e22ea7cc 2856 last if ($start == $end);
69893cff
RGS
2857
2858 # A hit! (Note, though, that we are doing
2859 # case-insensitive matching. Maybe a qr//
2860 # expression would be better, so the user could
2861 # do case-sensitive matching if desired.
e22ea7cc
RF
2862 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
2863 if ($slave_editor) {
69893cff 2864 # Handle proper escaping in the slave.
e22ea7cc
RF
2865 print $OUT "\032\032$filename:$start:0\n";
2866 }
2867 else {
69893cff 2868 # Just print the line normally.
e22ea7cc
RF
2869 print $OUT "$start:\t",$dbline[$start],"\n";
2870 }
69893cff 2871 # And quit since we found something.
e22ea7cc
RF
2872 last;
2873 }
2874 } ';
2875
69893cff 2876 # If we wrapped, there never was a match.
e22ea7cc
RF
2877 print $OUT "/$pat/: not found\n" if ( $start == $end );
2878 next CMD;
2879 };
69893cff
RGS
2880
2881=head4 C<?> - search backward for a string in the source
2882
2883Same as for C</>, except the loop runs backwards.
2884
2885=cut
2886
2887 # ? - backward pattern search.
e22ea7cc 2888 $cmd =~ /^\?(.*)$/ && do {
69893cff
RGS
2889
2890 # Get the pattern, remove trailing question mark.
e22ea7cc
RF
2891 $inpat = $1;
2892 $inpat =~ s:([^\\])\?$:$1:;
69893cff
RGS
2893
2894 # If we've got one ...
e22ea7cc 2895 if ( $inpat ne "" ) {
69893cff
RGS
2896
2897 # Turn off die & warn handlers.
e22ea7cc
RF
2898 local $SIG{__DIE__};
2899 local $SIG{__WARN__};
2900 eval '$inpat =~ m' . "\a$inpat\a";
2901
2902 if ( $@ ne "" ) {
2903
69893cff 2904 # Ouch. Not good. Print the error.
e22ea7cc
RF
2905 print $OUT $@;
2906 next CMD;
2907 }
2908 $pat = $inpat;
69893cff 2909 } ## end if ($inpat ne "")
e22ea7cc 2910
69893cff 2911 # Where we are now is where to stop after wraparound.
e22ea7cc 2912 $end = $start;
69893cff
RGS
2913
2914 # Don't move away from this line.
e22ea7cc 2915 $incr = -1;
69893cff
RGS
2916
2917 # Search inside the eval to prevent pattern badness
2918 # from killing us.
e22ea7cc
RF
2919 eval '
2920 for (;;) {
69893cff 2921 # Back up a line.
e22ea7cc 2922 --$start;
69893cff
RGS
2923
2924 # Wrap if we pass the first line.
e22ea7cc
RF
2925
2926 $start = $max if ($start <= 0);
69893cff
RGS
2927
2928 # Quit if we get back where we started,
e22ea7cc 2929 last if ($start == $end);
69893cff
RGS
2930
2931 # Match?
e22ea7cc
RF
2932 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
2933 if ($slave_editor) {
69893cff 2934 # Yep, follow slave editor requirements.
e22ea7cc
RF
2935 print $OUT "\032\032$filename:$start:0\n";
2936 }
2937 else {
69893cff 2938 # Yep, just print normally.
e22ea7cc
RF
2939 print $OUT "$start:\t",$dbline[$start],"\n";
2940 }
69893cff
RGS
2941
2942 # Found, so done.
e22ea7cc
RF
2943 last;
2944 }
2945 } ';
2946
2947 # Say we failed if the loop never found anything,
2948 print $OUT "?$pat?: not found\n" if ( $start == $end );
2949 next CMD;
2950 };
69893cff
RGS
2951
2952=head4 C<$rc> - Recall command
2953
2954Manages the commands in C<@hist> (which is created if C<Term::ReadLine> reports
2955that the terminal supports history). It find the the command required, puts it
2956into C<$cmd>, and redoes the loop to execute it.
2957
2958=cut
2959
e22ea7cc
RF
2960 # $rc - recall command.
2961 $cmd =~ /^$rc+\s*(-)?(\d+)?$/ && do {
69893cff
RGS
2962
2963 # No arguments, take one thing off history.
e22ea7cc 2964 pop(@hist) if length($cmd) > 1;
69893cff 2965
e22ea7cc 2966 # Relative (- found)?
69893cff 2967 # Y - index back from most recent (by 1 if bare minus)
e22ea7cc 2968 # N - go to that particular command slot or the last
69893cff 2969 # thing if nothing following.
e22ea7cc 2970 $i = $1 ? ( $#hist - ( $2 || 1 ) ) : ( $2 || $#hist );
69893cff
RGS
2971
2972 # Pick out the command desired.
e22ea7cc 2973 $cmd = $hist[$i];
69893cff
RGS
2974
2975 # Print the command to be executed and restart the loop
2976 # with that command in the buffer.
e22ea7cc
RF
2977 print $OUT $cmd, "\n";
2978 redo CMD;
2979 };
69893cff
RGS
2980
2981=head4 C<$sh$sh> - C<system()> command
2982
2983Calls the C<DB::system()> to handle the command. This keeps the C<STDIN> and
2984C<STDOUT> from getting messed up.
2985
2986=cut
2987
2988 # $sh$sh - run a shell command (if it's all ASCII).
2989 # Can't run shell commands with Unicode in the debugger, hmm.
e22ea7cc
RF
2990 $cmd =~ /^$sh$sh\s*([\x00-\xff]*)/ && do {
2991
69893cff 2992 # System it.
e22ea7cc
RF
2993 &system($1);
2994 next CMD;
2995 };
69893cff
RGS
2996
2997=head4 C<$rc I<pattern> $rc> - Search command history
2998
2999Another command to manipulate C<@hist>: this one searches it with a pattern.
3000If a command is found, it is placed in C<$cmd> and executed via <redo>.
3001
3002=cut
3003
e22ea7cc
RF
3004 # $rc pattern $rc - find a command in the history.
3005 $cmd =~ /^$rc([^$rc].*)$/ && do {
3006
69893cff 3007 # Create the pattern to use.
e22ea7cc 3008 $pat = "^$1";
69893cff
RGS
3009
3010 # Toss off last entry if length is >1 (and it always is).
e22ea7cc 3011 pop(@hist) if length($cmd) > 1;
69893cff
RGS
3012
3013 # Look backward through the history.
e22ea7cc
RF
3014 for ( $i = $#hist ; $i ; --$i ) {
3015
69893cff 3016 # Stop if we find it.
e22ea7cc
RF
3017 last if $hist[$i] =~ /$pat/;
3018 }
3019
3020 if ( !$i ) {
69893cff 3021
69893cff 3022 # Never found it.
e22ea7cc
RF
3023 print $OUT "No such command!\n\n";
3024 next CMD;
3025 }
69893cff
RGS
3026
3027 # Found it. Put it in the buffer, print it, and process it.
e22ea7cc
RF
3028 $cmd = $hist[$i];
3029 print $OUT $cmd, "\n";
3030 redo CMD;
3031 };
69893cff
RGS
3032
3033=head4 C<$sh> - Invoke a shell
3034
3035Uses C<DB::system> to invoke a shell.
3036
3037=cut
3038
3039 # $sh - start a shell.
e22ea7cc
RF
3040 $cmd =~ /^$sh$/ && do {
3041
69893cff
RGS
3042 # Run the user's shell. If none defined, run Bourne.
3043 # We resume execution when the shell terminates.
e22ea7cc
RF
3044 &system( $ENV{SHELL} || "/bin/sh" );
3045 next CMD;
3046 };
69893cff
RGS
3047
3048=head4 C<$sh I<command>> - Force execution of a command in a shell
3049
3050Like the above, but the command is passed to the shell. Again, we use
3051C<DB::system> to avoid problems with C<STDIN> and C<STDOUT>.
3052
3053=cut
3054
3055 # $sh command - start a shell and run a command in it.
e22ea7cc
RF
3056 $cmd =~ /^$sh\s*([\x00-\xff]*)/ && do {
3057
3058 # XXX: using csh or tcsh destroys sigint retvals!
3059 #&system($1); # use this instead
69893cff
RGS
3060
3061 # use the user's shell, or Bourne if none defined.
e22ea7cc
RF
3062 &system( $ENV{SHELL} || "/bin/sh", "-c", $1 );
3063 next CMD;
3064 };
69893cff
RGS
3065
3066=head4 C<H> - display commands in history
3067
3068Prints the contents of C<@hist> (if any).
3069
3070=cut
3071
7fddc82f
RF
3072 $cmd =~ /^H\b\s*\*/ && do {
3073 @hist = @truehist = ();
3074 print $OUT "History cleansed\n";
3075 next CMD;
3076 };
e22ea7cc
RF
3077
3078 $cmd =~ /^H\b\s*(-(\d+))?/ && do {
3079
3080 # Anything other than negative numbers is ignored by
69893cff 3081 # the (incorrect) pattern, so this test does nothing.
e22ea7cc 3082 $end = $2 ? ( $#hist - $2 ) : 0;
69893cff
RGS
3083
3084 # Set to the minimum if less than zero.
e22ea7cc 3085 $hist = 0 if $hist < 0;
69893cff 3086
e22ea7cc 3087 # Start at the end of the array.
69893cff
RGS
3088 # Stay in while we're still above the ending value.
3089 # Tick back by one each time around the loop.
e22ea7cc 3090 for ( $i = $#hist ; $i > $end ; $i-- ) {
69893cff
RGS
3091
3092 # Print the command unless it has no arguments.
e22ea7cc
RF
3093 print $OUT "$i: ", $hist[$i], "\n"
3094 unless $hist[$i] =~ /^.?$/;
3095 }
3096 next CMD;
3097 };
69893cff
RGS
3098
3099=head4 C<man, doc, perldoc> - look up documentation
3100
3101Just calls C<runman()> to print the appropriate document.
3102
3103=cut
3104
e22ea7cc
RF
3105 # man, perldoc, doc - show manual pages.
3106 $cmd =~ /^(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?$/ && do {
3107 runman($1);
3108 next CMD;
3109 };
69893cff
RGS
3110
3111=head4 C<p> - print
3112
3113Builds a C<print EXPR> expression in the C<$cmd>; this will get executed at
3114the bottom of the loop.
3115
3116=cut
3117
3118 # p - print (no args): print $_.
e22ea7cc 3119 $cmd =~ s/^p$/print {\$DB::OUT} \$_/;
69893cff
RGS
3120
3121 # p - print the given expression.
e22ea7cc 3122 $cmd =~ s/^p\b/print {\$DB::OUT} /;
69893cff
RGS
3123
3124=head4 C<=> - define command alias
3125
3126Manipulates C<%alias> to add or list command aliases.
3127
3128=cut
3129
e22ea7cc
RF
3130 # = - set up a command alias.
3131 $cmd =~ s/^=\s*// && do {
3132 my @keys;
3133 if ( length $cmd == 0 ) {
3134
69893cff 3135 # No args, get current aliases.
e22ea7cc
RF
3136 @keys = sort keys %alias;
3137 }
3138 elsif ( my ( $k, $v ) = ( $cmd =~ /^(\S+)\s+(\S.*)/ ) ) {
3139
69893cff
RGS
3140 # Creating a new alias. $k is alias name, $v is
3141 # alias value.
3142
e22ea7cc
RF
3143 # can't use $_ or kill //g state
3144 for my $x ( $k, $v ) {
3145
3146 # Escape "alarm" characters.
3147 $x =~ s/\a/\\a/g;
3148 }
69893cff
RGS
3149
3150 # Substitute key for value, using alarm chars
e22ea7cc 3151 # as separators (which is why we escaped them in
69893cff 3152 # the command).
e22ea7cc 3153 $alias{$k} = "s\a$k\a$v\a";
69893cff
RGS
3154
3155 # Turn off standard warn and die behavior.
e22ea7cc
RF
3156 local $SIG{__DIE__};
3157 local $SIG{__WARN__};
69893cff
RGS
3158
3159 # Is it valid Perl?
e22ea7cc
RF
3160 unless ( eval "sub { s\a$k\a$v\a }; 1" ) {
3161
69893cff 3162 # Nope. Bad alias. Say so and get out.
e22ea7cc
RF
3163 print $OUT "Can't alias $k to $v: $@\n";
3164 delete $alias{$k};
3165 next CMD;
3166 }
3167
69893cff 3168 # We'll only list the new one.
e22ea7cc 3169 @keys = ($k);
69893cff
RGS
3170 } ## end elsif (my ($k, $v) = ($cmd...
3171
3172 # The argument is the alias to list.
e22ea7cc
RF
3173 else {
3174 @keys = ($cmd);
3175 }
69893cff
RGS
3176
3177 # List aliases.
e22ea7cc
RF
3178 for my $k (@keys) {
3179
69893cff
RGS
3180 # Messy metaquoting: Trim the substiution code off.
3181 # We use control-G as the delimiter because it's not
3182 # likely to appear in the alias.
e22ea7cc
RF
3183 if ( ( my $v = $alias{$k} ) =~ s\as\a$k\a(.*)\a$\a1\a ) {
3184
69893cff 3185 # Print the alias.
e22ea7cc
RF
3186 print $OUT "$k\t= $1\n";
3187 }
3188 elsif ( defined $alias{$k} ) {
3189
69893cff 3190 # Couldn't trim it off; just print the alias code.
e22ea7cc
RF
3191 print $OUT "$k\t$alias{$k}\n";
3192 }
3193 else {
3194
69893cff 3195 # No such, dude.
e22ea7cc
RF
3196 print "No alias for $k\n";
3197 }
69893cff 3198 } ## end for my $k (@keys)
e22ea7cc
RF
3199 next CMD;
3200 };
69893cff
RGS
3201
3202=head4 C<source> - read commands from a file.
3203
3204Opens a lexical filehandle and stacks it on C<@cmdfhs>; C<DB::readline> will
3205pick it up.
3206
3207=cut
3208
e22ea7cc
RF
3209 # source - read commands from a file (or pipe!) and execute.
3210 $cmd =~ /^source\s+(.*\S)/ && do {
3211 if ( open my $fh, $1 ) {
3212
69893cff 3213 # Opened OK; stick it in the list of file handles.
e22ea7cc
RF
3214 push @cmdfhs, $fh;
3215 }
3216 else {
3217
3218 # Couldn't open it.
3219 &warn("Can't execute `$1': $!\n");
3220 }
3221 next CMD;
3222 };
69893cff
RGS
3223
3224=head4 C<save> - send current history to a file
3225
3226Takes the complete history, (not the shrunken version you see with C<H>),
3227and saves it to the given filename, so it can be replayed using C<source>.
3228
3229Note that all C<^(save|source)>'s are commented out with a view to minimise recursion.
3230
3231=cut
3232
3233 # save source - write commands to a file for later use
3234 $cmd =~ /^save\s*(.*)$/ && do {
e22ea7cc
RF
3235 my $file = $1 || '.perl5dbrc'; # default?
3236 if ( open my $fh, "> $file" ) {
3237
3238 # chomp to remove extraneous newlines from source'd files
3239 chomp( my @truelist =
3240 map { m/^\s*(save|source)/ ? "#$_" : $_ }
3241 @truehist );
3242 print $fh join( "\n", @truelist );
69893cff 3243 print "commands saved in $file\n";
e22ea7cc
RF
3244 }
3245 else {
69893cff
RGS
3246 &warn("Can't save debugger commands in '$1': $!\n");
3247 }
3248 next CMD;
3249 };
3250
7fddc82f
RF
3251=head4 C<R> - restart
3252
3253Restart the debugger session.
3254
3255=head4 C<rerun> - rerun the current session
3256
3257Return to any given position in the B<true>-history list
3258
3259=cut
3260
3261 # R - restart execution.
3262 # rerun - controlled restart execution.
3263 $cmd =~ /^(R|rerun\s*(.*))$/ && do {
3264 my @args = ($1 eq 'R' ? restart() : rerun($2));
3265
ca28b541
AP
3266 # Close all non-system fds for a clean restart. A more
3267 # correct method would be to close all fds that were not
3268 # open when the process started, but this seems to be
3269 # hard. See "debugger 'R'estart and open database
3270 # connections" on p5p.
3271
47d3bbda 3272 my $max_fd = 1024; # default if POSIX can't be loaded
ca28b541
AP
3273 if (eval { require POSIX }) {
3274 $max_fd = POSIX::sysconf(POSIX::_SC_OPEN_MAX());
3275 }
3276
3277 if (defined $max_fd) {
3278 foreach ($^F+1 .. $max_fd-1) {
3279 next unless open FD_TO_CLOSE, "<&=$_";
3280 close(FD_TO_CLOSE);
3281 }
3282 }
3283
7fddc82f
RF
3284 # And run Perl again. We use exec() to keep the
3285 # PID stable (and that way $ini_pids is still valid).
3286 exec(@args) || print $OUT "exec failed: $!\n";
3287
3288 last CMD;
3289 };
3290
69893cff
RGS
3291=head4 C<|, ||> - pipe output through the pager.
3292
3293FOR C<|>, we save C<OUT> (the debugger's output filehandle) and C<STDOUT>
3294(the program's standard output). For C<||>, we only save C<OUT>. We open a
3295pipe to the pager (restoring the output filehandles if this fails). If this
3296is the C<|> command, we also set up a C<SIGPIPE> handler which will simply
3297set C<$signal>, sending us back into the debugger.
3298
3299We then trim off the pipe symbols and C<redo> the command loop at the
3300C<PIPE> label, causing us to evaluate the command in C<$cmd> without
3301reading another.
3302
3303=cut
3304
3305 # || - run command in the pager, with output to DB::OUT.
e22ea7cc
RF
3306 $cmd =~ /^\|\|?\s*[^|]/ && do {
3307 if ( $pager =~ /^\|/ ) {
3308
69893cff 3309 # Default pager is into a pipe. Redirect I/O.
e22ea7cc
RF
3310 open( SAVEOUT, ">&STDOUT" )
3311 || &warn("Can't save STDOUT");
3312 open( STDOUT, ">&OUT" )
3313 || &warn("Can't redirect STDOUT");
69893cff 3314 } ## end if ($pager =~ /^\|/)
e22ea7cc
RF
3315 else {
3316
69893cff 3317 # Not into a pipe. STDOUT is safe.
e22ea7cc
RF
3318 open( SAVEOUT, ">&OUT" ) || &warn("Can't save DB::OUT");
3319 }
69893cff
RGS
3320
3321 # Fix up environment to record we have less if so.
e22ea7cc
RF
3322 fix_less();
3323
3324 unless ( $piped = open( OUT, $pager ) ) {
69893cff 3325
69893cff 3326 # Couldn't open pipe to pager.
e22ea7cc
RF
3327 &warn("Can't pipe output to `$pager'");
3328 if ( $pager =~ /^\|/ ) {
3329
69893cff 3330 # Redirect I/O back again.
e22ea7cc
RF
3331 open( OUT, ">&STDOUT" ) # XXX: lost message
3332 || &warn("Can't restore DB::OUT");
3333 open( STDOUT, ">&SAVEOUT" )
3334 || &warn("Can't restore STDOUT");
3335 close(SAVEOUT);
69893cff 3336 } ## end if ($pager =~ /^\|/)
e22ea7cc
RF
3337 else {
3338
69893cff 3339 # Redirect I/O. STDOUT already safe.
e22ea7cc
RF
3340 open( OUT, ">&STDOUT" ) # XXX: lost message
3341 || &warn("Can't restore DB::OUT");
3342 }
3343 next CMD;
69893cff
RGS
3344 } ## end unless ($piped = open(OUT,...
3345
3346 # Set up broken-pipe handler if necessary.
e22ea7cc
RF
3347 $SIG{PIPE} = \&DB::catch
3348 if $pager =~ /^\|/
3349 && ( "" eq $SIG{PIPE} || "DEFAULT" eq $SIG{PIPE} );
69893cff
RGS
3350
3351 # Save current filehandle, unbuffer out, and put it back.
e22ea7cc
RF
3352 $selected = select(OUT);
3353 $| = 1;
69893cff
RGS
3354
3355 # Don't put it back if pager was a pipe.
e22ea7cc 3356 select($selected), $selected = "" unless $cmd =~ /^\|\|/;
69893cff
RGS
3357
3358 # Trim off the pipe symbols and run the command now.
e22ea7cc
RF
3359 $cmd =~ s/^\|+\s*//;
3360 redo PIPE;
3361 };
69893cff
RGS
3362
3363=head3 END OF COMMAND PARSING
3364
3365Anything left in C<$cmd> at this point is a Perl expression that we want to
3366evaluate. We'll always evaluate in the user's context, and fully qualify
3367any variables we might want to address in the C<DB> package.
3368
3369=cut
3370
3371 # t - turn trace on.
e22ea7cc 3372 $cmd =~ s/^t\s/\$DB::trace |= 1;\n/;
69893cff
RGS
3373
3374 # s - single-step. Remember the last command was 's'.
e22ea7cc 3375 $cmd =~ s/^s\s/\$DB::single = 1;\n/ && do { $laststep = 's' };
69893cff
RGS
3376
3377 # n - single-step, but not into subs. Remember last command
e22ea7cc
RF
3378 # was 'n'.
3379 $cmd =~ s/^n\s/\$DB::single = 2;\n/ && do { $laststep = 'n' };
69893cff 3380
e22ea7cc 3381 } # PIPE:
69893cff 3382
e22ea7cc 3383 # Make sure the flag that says "the debugger's running" is
69893cff 3384 # still on, to make sure we get control again.
e22ea7cc 3385 $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd";
69893cff
RGS
3386
3387 # Run *our* eval that executes in the caller's context.
e22ea7cc 3388 &eval;
69893cff
RGS
3389
3390 # Turn off the one-time-dump stuff now.
e22ea7cc
RF
3391 if ($onetimeDump) {
3392 $onetimeDump = undef;
69893cff 3393 $onetimedumpDepth = undef;
e22ea7cc
RF
3394 }
3395 elsif ( $term_pid == $$ ) {
3396 STDOUT->flush();
3397 STDERR->flush();
3398
69893cff 3399 # XXX If this is the master pid, print a newline.
e22ea7cc
RF
3400 print $OUT "\n";
3401 }
3402 } ## end while (($term || &setterm...
69893cff
RGS
3403
3404=head3 POST-COMMAND PROCESSING
3405
3406After each command, we check to see if the command output was piped anywhere.
3407If so, we go through the necessary code to unhook the pipe and go back to
3408our standard filehandles for input and output.
3409
3410=cut
3411
e22ea7cc 3412 continue { # CMD:
69893cff
RGS
3413
3414 # At the end of every command:
e22ea7cc
RF
3415 if ($piped) {
3416
69893cff 3417 # Unhook the pipe mechanism now.
e22ea7cc
RF
3418 if ( $pager =~ /^\|/ ) {
3419
69893cff 3420 # No error from the child.
e22ea7cc 3421 $? = 0;
69893cff 3422
e22ea7cc
RF
3423 # we cannot warn here: the handle is missing --tchrist
3424 close(OUT) || print SAVEOUT "\nCan't close DB::OUT\n";
69893cff 3425
e22ea7cc 3426 # most of the $? crud was coping with broken cshisms
69893cff 3427 # $? is explicitly set to 0, so this never runs.
e22ea7cc
RF
3428 if ($?) {
3429 print SAVEOUT "Pager `$pager' failed: ";
3430 if ( $? == -1 ) {
3431 print SAVEOUT "shell returned -1\n";
3432 }
3433 elsif ( $? >> 8 ) {
3434 print SAVEOUT ( $? & 127 )
3435 ? " (SIG#" . ( $? & 127 ) . ")"
3436 : "", ( $? & 128 ) ? " -- core dumped" : "", "\n";
3437 }
3438 else {
3439 print SAVEOUT "status ", ( $? >> 8 ), "\n";
3440 }
69893cff
RGS
3441 } ## end if ($?)
3442
e22ea7cc 3443 # Reopen filehandle for our output (if we can) and
69893cff 3444 # restore STDOUT (if we can).
e22ea7cc
RF
3445 open( OUT, ">&STDOUT" ) || &warn("Can't restore DB::OUT");
3446 open( STDOUT, ">&SAVEOUT" )
3447 || &warn("Can't restore STDOUT");
69893cff
RGS
3448
3449 # Turn off pipe exception handler if necessary.
e22ea7cc 3450 $SIG{PIPE} = "DEFAULT" if $SIG{PIPE} eq \&DB::catch;
69893cff 3451
e22ea7cc
RF
3452 # Will stop ignoring SIGPIPE if done like nohup(1)
3453 # does SIGINT but Perl doesn't give us a choice.
69893cff 3454 } ## end if ($pager =~ /^\|/)
e22ea7cc
RF
3455 else {
3456
69893cff 3457 # Non-piped "pager". Just restore STDOUT.
e22ea7cc
RF
3458 open( OUT, ">&SAVEOUT" ) || &warn("Can't restore DB::OUT");
3459 }
69893cff
RGS
3460
3461 # Close filehandle pager was using, restore the normal one
3462 # if necessary,
3463 close(SAVEOUT);
e22ea7cc 3464 select($selected), $selected = "" unless $selected eq "";
69893cff
RGS
3465
3466 # No pipes now.
e22ea7cc 3467 $piped = "";
69893cff 3468 } ## end if ($piped)
e22ea7cc 3469 } # CMD:
69893cff
RGS
3470
3471=head3 COMMAND LOOP TERMINATION
3472
3473When commands have finished executing, we come here. If the user closed the
3474input filehandle, we turn on C<$fall_off_end> to emulate a C<q> command. We
3475evaluate any post-prompt items. We restore C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>,
3476C<$\>, and C<$^W>, and return a null list as expected by the Perl interpreter.
3477The interpreter will then execute the next line and then return control to us
3478again.
3479
3480=cut
3481
3482 # No more commands? Quit.
e22ea7cc 3483 $fall_off_end = 1 unless defined $cmd; # Emulate `q' on EOF
69893cff
RGS
3484
3485 # Evaluate post-prompt commands.
e22ea7cc
RF
3486 foreach $evalarg (@$post) {
3487 &eval;
3488 }
3489 } # if ($single || $signal)
69893cff
RGS
3490
3491 # Put the user's globals back where you found them.
e22ea7cc 3492 ( $@, $!, $^E, $,, $/, $\, $^W ) = @saved;
69893cff
RGS
3493 ();
3494} ## end sub DB
3495
3496# The following code may be executed now:
3497# BEGIN {warn 4}
3498
3499=head2 sub
3500
3501C<sub> is called whenever a subroutine call happens in the program being
3502debugged. The variable C<$DB::sub> contains the name of the subroutine
3503being called.
3504
3505The core function of this subroutine is to actually call the sub in the proper
3506context, capturing its output. This of course causes C<DB::DB> to get called
3507again, repeating until the subroutine ends and returns control to C<DB::sub>
3508again. Once control returns, C<DB::sub> figures out whether or not to dump the
3509return value, and returns its captured copy of the return value as its own
3510return value. The value then feeds back into the program being debugged as if
3511C<DB::sub> hadn't been there at all.
3512
3513C<sub> does all the work of printing the subroutine entry and exit messages
3514enabled by setting C<$frame>. It notes what sub the autoloader got called for,
3515and also prints the return value if needed (for the C<r> command and if
3516the 16 bit is set in C<$frame>).
3517
3518It also tracks the subroutine call depth by saving the current setting of
3519C<$single> in the C<@stack> package global; if this exceeds the value in
3520C<$deep>, C<sub> automatically turns on printing of the current depth by
3521setting the 4 bit in C<$single>. In any case, it keeps the current setting
3522of stop/don't stop on entry to subs set as it currently is set.
3523
3524=head3 C<caller()> support
3525
3526If C<caller()> is called from the package C<DB>, it provides some
3527additional data, in the following order:
3528
3529=over 4
3530
3531=item * C<$package>
3532
3533The package name the sub was in
3534
3535=item * C<$filename>
3536
3537The filename it was defined in
3538
3539=item * C<$line>
3540
3541The line number it was defined on
3542
3543=item * C<$subroutine>
3544
3545The subroutine name; C<'(eval)'> if an C<eval>().
3546
3547=item * C<$hasargs>
3548
35491 if it has arguments, 0 if not
3550
3551=item * C<$wantarray>
3552
35531 if array context, 0 if scalar context
3554
3555=item * C<$evaltext>
3556
3557The C<eval>() text, if any (undefined for C<eval BLOCK>)
3558
3559=item * C<$is_require>
3560
3561frame was created by a C<use> or C<require> statement
3562
3563=item * C<$hints>
3564
3565pragma information; subject to change between versions
3566
3567=item * C<$bitmask>
3568
3569pragma information: subject to change between versions
3570
3571=item * C<@DB::args>
3572
3573arguments with which the subroutine was invoked
3574
3575=back
3576
3577=cut
d338d6fe 3578
d12a4851 3579sub sub {
69893cff 3580
2cbb2ee1
RGS
3581 # lock ourselves under threads
3582 lock($DBGR);
3583
69893cff
RGS
3584 # Whether or not the autoloader was running, a scalar to put the
3585 # sub's return value in (if needed), and an array to put the sub's
3586 # return value in (if needed).
e22ea7cc 3587 my ( $al, $ret, @ret ) = "";
2cbb2ee1
RGS
3588 if ($sub =~ /^threads::new$/ && $ENV{PERL5DB_THREADED}) {
3589 print "creating new thread\n";
3590 }
69893cff
RGS
3591
3592 # If the last ten characters are C'::AUTOLOAD', note we've traced
3593 # into AUTOLOAD for $sub.
e22ea7cc
RF
3594 if ( length($sub) > 10 && substr( $sub, -10, 10 ) eq '::AUTOLOAD' ) {
3595 $al = " for $$sub";
d12a4851 3596 }
69893cff
RGS
3597
3598 # We stack the stack pointer and then increment it to protect us
3599 # from a situation that might unwind a whole bunch of call frames
3600 # at once. Localizing the stack pointer means that it will automatically
3601 # unwind the same amount when multiple stack frames are unwound.
e22ea7cc 3602 local $stack_depth = $stack_depth + 1; # Protect from non-local exits
69893cff
RGS
3603
3604 # Expand @stack.
d12a4851 3605 $#stack = $stack_depth;
69893cff
RGS
3606
3607 # Save current single-step setting.
d12a4851 3608 $stack[-1] = $single;
69893cff 3609
e22ea7cc 3610 # Turn off all flags except single-stepping.
d12a4851 3611 $single &= 1;
69893cff
RGS
3612
3613 # If we've gotten really deeply recursed, turn on the flag that will
3614 # make us stop with the 'deep recursion' message.
d12a4851 3615 $single |= 4 if $stack_depth == $deep;
69893cff
RGS
3616
3617 # If frame messages are on ...
3618 (
3619 $frame & 4 # Extended frame entry message
e22ea7cc
RF
3620 ? (
3621 print_lineinfo( ' ' x ( $stack_depth - 1 ), "in " ),
69893cff 3622
e22ea7cc 3623 # Why -1? But it works! :-(
69893cff
RGS
3624 # Because print_trace will call add 1 to it and then call
3625 # dump_trace; this results in our skipping -1+1 = 0 stack frames
3626 # in dump_trace.
e22ea7cc
RF
3627 print_trace( $LINEINFO, -1, 1, 1, "$sub$al" )
3628 )
3629 : print_lineinfo( ' ' x ( $stack_depth - 1 ), "entering $sub$al\n" )
3630
69893cff 3631 # standard frame entry message
e22ea7cc
RF
3632 )
3633 if $frame;
69893cff
RGS
3634
3635 # Determine the sub's return type,and capture approppriately.
d12a4851 3636 if (wantarray) {
e22ea7cc 3637
69893cff
RGS
3638 # Called in array context. call sub and capture output.
3639 # DB::DB will recursively get control again if appropriate; we'll come
3640 # back here when the sub is finished.
d12a4851 3641 if ($assertion) {
e22ea7cc
RF
3642 $assertion = 0;
3643 eval { @ret = &$sub; };
3644 if ($@) {
3645 print $OUT $@;
3646 $signal = 1 unless $warnassertions;
3647 }
3648 }
3649 else {
69893cff 3650 @ret = &$sub;
69893cff 3651 }
69893cff
RGS
3652
3653 # Pop the single-step value back off the stack.
e22ea7cc 3654 $single |= $stack[ $stack_depth-- ];
69893cff
RGS
3655
3656 # Check for exit trace messages...
e22ea7cc
RF
3657 (
3658 $frame & 4 # Extended exit message
3659 ? (
3660 print_lineinfo( ' ' x $stack_depth, "out " ),
3661 print_trace( $LINEINFO, -1, 1, 1, "$sub$al" )
3662 )
3663 : print_lineinfo( ' ' x $stack_depth, "exited $sub$al\n" )
3664
69893cff 3665 # Standard exit message
e22ea7cc
RF
3666 )
3667 if $frame & 2;
69893cff
RGS
3668
3669 # Print the return info if we need to.
e22ea7cc
RF
3670 if ( $doret eq $stack_depth or $frame & 16 ) {
3671
69893cff 3672 # Turn off output record separator.
e22ea7cc
RF
3673 local $\ = '';
3674 my $fh = ( $doret eq $stack_depth ? $OUT : $LINEINFO );
69893cff
RGS
3675
3676 # Indent if we're printing because of $frame tracing.
e22ea7cc 3677 print $fh ' ' x $stack_depth if $frame & 16;
69893cff
RGS
3678
3679 # Print the return value.
e22ea7cc
RF
3680 print $fh "list context return from $sub:\n";
3681 dumpit( $fh, \@ret );
69893cff
RGS
3682
3683 # And don't print it again.
e22ea7cc 3684 $doret = -2;
69893cff 3685 } ## end if ($doret eq $stack_depth...
e22ea7cc
RF
3686 # And we have to return the return value now.
3687 @ret;
69893cff
RGS
3688 } ## end if (wantarray)
3689
3690 # Scalar context.
3691 else {
d12a4851 3692 if ($assertion) {
e22ea7cc
RF
3693 $assertion = 0;
3694 eval {
3695
3696 # Save the value if it's wanted at all.
3697 $ret = &$sub;
3698 };
3699 if ($@) {
3700 print $OUT $@;
3701 $signal = 1 unless $warnassertions;
3702 }
3703 $ret = undef unless defined wantarray;
69893cff 3704 }
69893cff 3705 else {
e22ea7cc
RF
3706 if ( defined wantarray ) {
3707
3708 # Save the value if it's wanted at all.
3709 $ret = &$sub;
3710 }
3711 else {
3712
3713 # Void return, explicitly.
3714 &$sub;
3715 undef $ret;
3716 }
3717 } # if assertion
69893cff
RGS
3718
3719 # Pop the single-step value off the stack.
e22ea7cc 3720 $single |= $stack[ $stack_depth-- ];
69893cff
RGS
3721
3722 # If we're doing exit messages...
e22ea7cc
RF
3723 (
3724 $frame & 4 # Extended messsages
3725 ? (
3726 print_lineinfo( ' ' x $stack_depth, "out " ),
3727 print_trace( $LINEINFO, -1, 1, 1, "$sub$al" )
3728 )
3729 : print_lineinfo( ' ' x $stack_depth, "exited $sub$al\n" )
3730
3731 # Standard messages
3732 )
3733 if $frame & 2;
69893cff
RGS
3734
3735 # If we are supposed to show the return value... same as before.
e22ea7cc
RF
3736 if ( $doret eq $stack_depth or $frame & 16 and defined wantarray ) {
3737 local $\ = '';
3738 my $fh = ( $doret eq $stack_depth ? $OUT : $LINEINFO );
3739 print $fh ( ' ' x $stack_depth ) if $frame & 16;
3740 print $fh (
3741 defined wantarray
3742 ? "scalar context return from $sub: "
3743 : "void context return from $sub\n"
3744 );
3745 dumpit( $fh, $ret ) if defined wantarray;
3746 $doret = -2;
69893cff
RGS
3747 } ## end if ($doret eq $stack_depth...
3748
3749 # Return the appropriate scalar value.
e22ea7cc 3750 $ret;
69893cff
RGS
3751 } ## end else [ if (wantarray)
3752} ## end sub sub
3753
3754=head1 EXTENDED COMMAND HANDLING AND THE COMMAND API
3755
3756In Perl 5.8.0, there was a major realignment of the commands and what they did,
3757Most of the changes were to systematize the command structure and to eliminate
3758commands that threw away user input without checking.
3759
3760The following sections describe the code added to make it easy to support
3761multiple command sets with conflicting command names. This section is a start
3762at unifying all command processing to make it simpler to develop commands.
3763
3764Note that all the cmd_[a-zA-Z] subroutines require the command name, a line
3765number, and C<$dbline> (the current line) as arguments.
3766
3767Support functions in this section which have multiple modes of failure C<die>
3768on error; the rest simply return a false value.
3769
3770The user-interface functions (all of the C<cmd_*> functions) just output
3771error messages.
3772
3773=head2 C<%set>
3774
3775</