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