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