blib/lib/PDLdb.pl untested

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