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