nd C<$frame>, have I values composed of 1, 2, 4, etc. (powers of 2) OR'ed together. This allows several pieces of state to be stored independently in a single scalar. A test like if ($scalar & 4) ... is checking to see if the appropriate bit is on. Since each bit can be "addressed" independently in this way, C<$scalar> is acting sort of like an array of bits. Obviously, since the contents of C<$scalar> are just a bit-pattern, we can save and restore it easily (it will just look like a number). The problem, is of course, that this tends to leave magic numbers scattered all over your program whenever a bit is set, cleared, or checked. So why do it? =over 4 =item * First, doing an arithmetical or bitwise operation on a scalar is just about the fastest thing you can do in Perl: S> actually creates a subroutine call, and array and hash lookups are much slower. Is this over-optimization at the expense of readability? Possibly, but the debugger accesses these variables a I. Any rewrite of the code will probably have to benchmark alternate implementations and see which is the best balance of readability and speed, and then document how it actually works. =item * Second, it's very easy to serialize a scalar number. This is done in the restart code; the debugger state variables are saved in C<%ENV> and then restored when the debugger is restarted. Having them be just numbers makes this trivial. =item * Third, some of these variables are being shared with the Perl core smack in the middle of the interpreter's execution loop. It's much faster for a C program (like the interpreter) to check a bit in a scalar than to access several different variables (or a Perl array). =back =head2 What are those C comments for? Any comment containing C means that the comment is either somewhat speculative - it's not exactly clear what a given variable or chunk of code is doing, or that it is incomplete - the basics may be clear, but the subtleties are not completely documented. Send in a patch if you can clear up, fill out, or clarify an C. =head1 DATA STRUCTURES MAINTAINED BY CORE There are a number of special data structures provided to the debugger by the Perl interpreter. The array C<@{$main::{'_<'.$filename}}> (aliased locally to C<@dbline> via glob assignment) contains the text from C<$filename>, with each element corresponding to a single line of C<$filename>. Additionally, breakable lines will be dualvars with the numeric component being the memory address of a COP node. Non-breakable lines are dualvar to 0. The hash C<%{'_<'.$filename}> (aliased locally to C<%dbline> via glob assignment) contains breakpoints and actions. The keys are line numbers; you can set individual values, but not the whole hash. The Perl interpreter uses this hash to determine where breakpoints have been set. Any true value is considered to be a breakpoint; C uses C<$break_condition\0$action>. Values are magical in numeric context: 1 if the line is breakable, 0 if not. The scalar C<${"_<$filename"}> simply contains the string C<$filename>. This is also the case for evaluated strings that contain subroutines, or which are currently being executed. The $filename for Ced strings looks like S>. =head1 DEBUGGER STARTUP When C starts, it reads an rcfile (C for non-interactive sessions, C<.perldb> for interactive ones) that can set a number of options. In addition, this file may define a subroutine C<&afterinit> that will be executed (in the debugger's context) after the debugger has initialized itself. Next, it checks the C environment variable and treats its contents as the argument of a C command in the debugger. =head2 STARTUP-ONLY OPTIONS The following options can only be specified at startup. To set them in your rcfile, add a call to C<&parse_options("optionName=new_value")>. =over 4 =item * TTY the TTY to use for debugging i/o. =item * noTTY if set, goes in NonStop mode. On interrupt, if TTY is not set, uses the value of noTTY or F<$HOME/.perldbtty$$> to find TTY using Term::Rendezvous. Current variant is to have the name of TTY in this file. =item * ReadLine if false, a dummy ReadLine is used, so you can debug ReadLine applications. =item * NonStop if true, no i/o is performed until interrupt. =item * LineInfo file or pipe to print line number info to. If it is a pipe, a short "emacs like" message is used. =item * RemotePort host:port to connect to on remote host for remote debugging. =item * HistFile file to store session history to. There is no default and so no history file is written unless this variable is explicitly set. =item * HistSize number of commands to store to the file specified in C. Default is 100. =back =head3 SAMPLE RCFILE &parse_options("NonStop=1 LineInfo=db.out"); sub afterinit { $trace = 1; } The script will run without human intervention, putting trace information into C. (If you interrupt it, you had better reset C to something I!) =head1 INTERNALS DESCRIPTION =head2 DEBUGGER INTERFACE VARIABLES Perl supplies the values for C<%sub>. It effectively inserts a C<&DB::DB();> in front of each place that can have a breakpoint. At each subroutine call, it calls C<&DB::sub> with C<$DB::sub> set to the called subroutine. It also inserts a C before the first line. After each Cd file is compiled, but before it is executed, a call to C<&DB::postponed($main::{'_<'.$filename})> is done. C<$filename> is the expanded name of the Cd file (as found via C<%INC>). =head3 IMPORTANT INTERNAL VARIABLES =head4 C<$CreateTTY> Used to control when the debugger will attempt to acquire another TTY to be used for input. =over =item * 1 - on C =item * 2 - debugger is started inside debugger =item * 4 - on startup =back =head4 C<$doret> The value -2 indicates that no return value should be printed. Any other positive value causes C to print return values. =head4 C<$evalarg> The item to be eval'ed by C. Used to prevent messing with the current contents of C<@_> when C is called. =head4 C<$frame> Determines what messages (if any) will get printed when a subroutine (or eval) is entered or exited. =over 4 =item * 0 - No enter/exit messages =item * 1 - Print I messages on subroutine entry =item * 2 - Adds exit messages on subroutine exit. If no other flag is on, acts like 1+2. =item * 4 - Extended messages: C<< I=I from I:I >>. If no other flag is on, acts like 1+4. =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. =item * 16 - Adds C return from I: I> messages on subroutine/eval exit. Ignored if C<4> is not on. =back To get everything, use C<$frame=30> (or S> as a debugger command). The debugger internally juggles the value of C<$frame> during execution to protect external modules that the debugger uses from getting traced. =head4 C<$level> Tracks current debugger nesting level. Used to figure out how many CE> pairs to surround the line number with when the debugger outputs a prompt. Also used to help determine if the program has finished during command parsing. =head4 C<$onetimeDump> Controls what (if anything) C will print after evaluating an expression. =over 4 =item * C - don't print anything =item * C - use C to display the value returned =item * C - print the methods callable on the first item returned =back =head4 C<$onetimeDumpDepth> Controls how far down C will go before printing C<...> while dumping a structure. Numeric. If C, print all levels. =head4 C<$signal> Used to track whether or not an C signal has been detected. C, which is called before every statement, checks this and puts the user into command mode if it finds C<$signal> set to a true value. =head4 C<$single> Controls behavior during single-stepping. Stacked in C<@stack> on entry to each subroutine; popped again at the end of each subroutine. =over 4 =item * 0 - run continuously. =item * 1 - single-step, go into subs. The C command. =item * 2 - single-step, don't go into subs. The C command. =item * 4 - print current sub depth (turned on to force this when C occurs. =back =head4 C<$trace> Controls the output of trace information. =over 4 =item * 1 - The C command was entered to turn on tracing (every line executed is printed) =item * 2 - watch expressions are active =item * 4 - user defined a C in C =back =head4 C<$client_editor> 1 if C was directed to a pipe; 0 otherwise. (The term C<$slave_editor> was formerly used here.) =head4 C<@cmdfhs> Stack of filehandles that C will read commands from. Manipulated by the debugger's C command and C itself. =head4 C<@dbline> Local alias to the magical line array, C<@{$main::{'_<'.$filename}}> , supplied by the Perl interpreter to the debugger. Contains the source. =head4 C<@old_watch> Previous values of watch expressions. First set when the expression is entered; reset whenever the watch expression changes. =head4 C<@saved> Saves important globals (C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, C<$^W>) so that the debugger can substitute safe values while it's running, and restore them when it returns control. =head4 C<@stack> Saves the current value of C<$single> on entry to a subroutine. Manipulated by the C command to turn off tracing in all subs above the current one. =head4 C<@to_watch> The 'watch' expressions: to be evaluated before each line is executed. =head4 C<@typeahead> The typeahead buffer, used by C. =head4 C<%alias> Command aliases. Stored as character strings to be substituted for a command entered. =head4 C<%break_on_load> Keys are file names, values are 1 (break when this file is loaded) or undef (don't break when it is loaded). =head4 C<%dbline> Keys are line numbers, values are C. If used in numeric context, values are 0 if not breakable, 1 if breakable, no matter what is in the actual hash entry. =head4 C<%had_breakpoints> Keys are file names; values are bitfields: =over 4 =item * 1 - file has a breakpoint in it. =item * 2 - file has an action in it. =back A zero or undefined value means this file has neither. =head4 C<%option> Stores the debugger options. These are character string values. =head4 C<%postponed> Saves breakpoints for code that hasn't been compiled yet. Keys are subroutine names, values are: =over 4 =item * C - break when this sub is compiled =item * C<< break +0 if >> - break (conditionally) at the start of this routine. The condition will be '1' if no condition was specified. =back =head4 C<%postponed_file> This hash keeps track of breakpoints that need to be set for files that have not yet been compiled. Keys are filenames; values are references to hashes. Each of these hashes is keyed by line number, and its values are breakpoint definitions (C). =head1 DEBUGGER INITIALIZATION The debugger's initialization actually jumps all over the place inside this package. This is because there are several BEGIN blocks (which of course execute immediately) spread through the code. Why is that? The debugger needs to be able to change some things and set some things up before the debugger code is compiled; most notably, the C<$deep> variable that C uses to tell when a program has recursed deeply. In addition, the debugger has to turn off warnings while the debugger code is compiled, but then restore them to their original setting before the program being debugged begins executing. The first C block simply turns off warnings by saving the current setting of C<$^W> and then setting it to zero. The second one initializes the debugger variables that are needed before the debugger begins executing. The third one puts C<$^X> back to its former value. We'll detail the second C block later; just remember that if you need to initialize something before the debugger starts really executing, that's where it has to go. =cut package DB; use strict; use Cwd (); my $_initial_cwd; BEGIN {eval 'use IO::Handle'}; # Needed for flush only? breaks under miniperl BEGIN { require feature; $^V =~ /^v(\d+\.\d+)/; feature->import(":$1"); $_initial_cwd = Cwd::getcwd(); } # Debugger for Perl 5.00x; perl5db.pl patch level: use vars qw($VERSION $header); # bump to X.XX in blead, only use X.XX_XX in maint $VERSION = '1.80'; $header = "perl5db.pl version $VERSION"; =head1 DEBUGGER ROUTINES =head2 C This function replaces straight C inside the debugger; it simplifies the process of evaluating code in the user's context. The code to be evaluated is passed via the package global variable C<$DB::evalarg>; this is done to avoid fiddling with the contents of C<@_>. Before we do the C, we preserve the current settings of C<$trace>, C<$single>, C<$^D> and C<$usercontext>. The latter contains the preserved values of C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, C<$^W> and the user's current package, grabbed when C got control. This causes the proper context to be used when the eval is actually done. Afterward, we restore C<$trace>, C<$single>, and C<$^D>. Next we need to handle C<$@> without getting confused. We save C<$@> in a local lexical, localize C<$saved[0]> (which is where C will put C<$@>), and then call C to capture C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, and C<$^W>) and set C<$,>, C<$/>, C<$\>, and C<$^W> to values considered sane by the debugger. If there was an C error, we print it on the debugger's output. If C<$onetimedump> is defined, we call C if it's set to 'dump', or C if it's set to 'methods'. Setting it to something else causes the debugger to do the eval but not print the result - handy if you want to do something else with it (the "watch expressions" code does this to get the value of the watch expression but not show it unless it matters). In any case, we then return the list of output from C to the caller, and unwinding restores the former version of C<$@> in C<@saved> as well (the localization of C<$saved[0]> goes away at the end of this scope). =head3 Parameters and variables influencing execution of DB::eval() C isn't parameterized in the standard way; this is to keep the debugger's calls to C from mucking with C<@_>, among other things. The variables listed below influence C's execution directly. =over 4 =item C<$evalarg> - the thing to actually be eval'ed =item C<$trace> - Current state of execution tracing =item C<$single> - Current state of single-stepping =item C<$onetimeDump> - what is to be displayed after the evaluation =item C<$onetimeDumpDepth> - how deep C should go when dumping results =back The following variables are altered by C during its execution. They are "stacked" via C, enabling recursive calls to C. =over 4 =item C<@res> - used to capture output from actual C. =item C<$otrace> - saved value of C<$trace>. =item C<$osingle> - saved value of C<$single>. =item C<$od> - saved value of C<$^D>. =item C<$saved[0]> - saved value of C<$@>. =item $\ - for output of C<$@> if there is an evaluation error. =back =head3 The problem of lexicals The context of C presents us with some problems. Obviously, we want to be 'sandboxed' away from the debugger's internals when we do the eval, but we need some way to control how punctuation variables and debugger globals are used. We can't use local, because the code inside C can see localized variables; and we can't use C either for the same reason. The code in this routine compromises and uses C. After this routine is over, we don't have user code executing in the debugger's context, so we can use C freely. =cut ############################################## Begin lexical danger zone # 'my' variables used here could leak into (that is, be visible in) # the context that the code being evaluated is executing in. This means that # the code could modify the debugger's variables. # # Fiddling with the debugger's context could be Bad. We insulate things as # much as we can. use vars qw( @args %break_on_load $CommandSet $CreateTTY $DBGR @dbline $dbline %dbline $dieLevel $filename $histfile $histsize $histitemminlength $IN $inhibit_exit @ini_INC $ini_warn $maxtrace $od @options $osingle $otrace $pager $post %postponed $prc $pre $pretype $psh @RememberOnROptions $remoteport @res $rl @saved $signalLevel $sub $term $usercontext $warnLevel ); our ( @cmdfhs, $evalarg, $frame, $hist, $ImmediateStop, $line, $onetimeDump, $onetimedumpDepth, %option, $OUT, $packname, $signal, $single, $start, %sub, $subname, $trace, $window, ); # Used to save @ARGV and extract any debugger-related flags. use vars qw(@ARGS); # Used to prevent multiple entries to diesignal() # (if for instance diesignal() itself dies) use vars qw($panic); # Used to prevent the debugger from running nonstop # after a restart our ($second_time); sub _calc_usercontext { my ($package) = @_; # Cancel strict completely for the evaluated code, so the code # the user evaluates won't be affected by it. (Shlomi Fish) return 'no strict; ($@, $!, $^E, $,, $/, $\, $^W) = @DB::saved;' . "package $package;"; # this won't let them modify, alas } sub eval { # 'my' would make it visible from user code # but so does local! --tchrist # Remember: this localizes @DB::res, not @main::res. local @res; { # Try to keep the user code from messing with us. Save these so that # even if the eval'ed code changes them, we can put them back again. # Needed because the user could refer directly to the debugger's # package globals (and any 'my' variables in this containing scope) # inside the eval(), and we want to try to stay safe. local $otrace = $trace; local $osingle = $single; local $od = $^D; # Untaint the incoming eval() argument. { ($evalarg) = $evalarg =~ /(.*)/s; } # $usercontext built in DB::DB near the comment # "set up the context for DB::eval ..." # Evaluate and save any results. @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug # Restore those old values. $trace = $otrace; $single = $osingle; $^D = $od; } # Save the current value of $@, and preserve it in the debugger's copy # of the saved precious globals. my $at = $@; # Since we're only saving $@, we only have to localize the array element # that it will be stored in. local $saved[0]; # Preserve the old value of $@ eval { &DB::save }; # Now see whether we need to report an error back to the user. if ($at) { local $\ = ''; print $OUT $at; } # Display as required by the caller. $onetimeDump and $onetimedumpDepth # are package globals. elsif ($onetimeDump) { if ( $onetimeDump eq 'dump' ) { local $option{dumpDepth} = $onetimedumpDepth if defined $onetimedumpDepth; dumpit( $OUT, \@res ); } elsif ( $onetimeDump eq 'methods' ) { methods( $res[0] ); } } ## end elsif ($onetimeDump) @res; } ## end sub eval ############################################## End lexical danger zone # After this point it is safe to introduce lexicals. # The code being debugged will be executing in its own context, and # can't see the inside of the debugger. # # However, one should not overdo it: leave as much control from outside as # possible. If you make something a lexical, it's not going to be addressable # from outside the debugger even if you know its name. # This file is automatically included if you do perl -d. # It's probably not useful to include this yourself. # # Before venturing further into these twisty passages, it is # wise to read the perldebguts man page or risk the ire of dragons. # # (It should be noted that perldebguts will tell you a lot about # the underlying mechanics of how the debugger interfaces into the # Perl interpreter, but not a lot about the debugger itself. The new # comments in this code try to address this problem.) # Note that no subroutine call is possible until &DB::sub is defined # (for subroutines defined outside of the package DB). In fact the same is # true if $deep is not defined. # Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich) # modified Perl debugger, to be run from Emacs in perldb-mode # Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990 # Johan Vromans -- upgrade to 4.0 pl 10 # Ilya Zakharevich -- patches after 5.001 (and some before ;-) ######################################################################## =head1 DEBUGGER INITIALIZATION The debugger starts up in phases. =head2 BASIC SETUP First, it initializes the environment it wants to run in: turning off warnings during its own compilation, defining variables which it will need to avoid warnings later, setting itself up to not exit when the program terminates, and defaulting to printing return values for the C command. =cut # Needed for the statement after exec(): # # This BEGIN block is simply used to switch off warnings during debugger # compilation. Probably it would be better practice to fix the warnings, # but this is how it's done at the moment. BEGIN { $ini_warn = $^W; $^W = 0; } # Switch compilation warnings off until another BEGIN. local ($^W) = 0; # Switch run-time warnings off during init. =head2 THREADS SUPPORT If we are running under a threaded Perl, we require threads and threads::shared if the environment variable C is set, to enable proper threaded debugger control. C<-dt> can also be used to set this. Each new thread will be announced and the debugger prompt will always inform you of each new thread created. It will also indicate the thread id in which we are currently running within the prompt like this: [tid] DB<$i> Where C<[tid]> is an integer thread id and C<$i> is the familiar debugger command prompt. The prompt will show: C<[0]> when running under threads, but not actually in a thread. C<[tid]> is consistent with C usage. While running under threads, when you set or delete a breakpoint (etc.), this will apply to all threads, not just the currently running one. When you are in a currently executing thread, you will stay there until it completes. With the current implementation it is not currently possible to hop from one thread to another. The C and C commands are currently fairly minimal - see S> and S>. Note that threading support was built into the debugger as of Perl version C<5.8.6> and debugger version C<1.2.8>. =cut BEGIN { # ensure we can share our non-threaded variables or no-op if ($ENV{PERL5DB_THREADED}) { require threads; require threads::shared; threads::shared->import('share'); $DBGR; share(\$DBGR); lock($DBGR); print "Threads support enabled\n"; } else { *lock = sub :prototype(*) {}; *share = sub :prototype(\[$@%]) {}; } } # These variables control the execution of 'dumpvar.pl'. { package dumpvar; use vars qw( $hashDepth $arrayDepth $dumpDBFiles $dumpPackages $quoteHighBit $printUndef $globPrint $usageOnly ); } # used to control die() reporting in diesignal() { package Carp; use vars qw($CarpLevel); } # without threads, $filename is not defined until DB::DB is called share($main::{'_<'.$filename}) if defined $filename; # Command-line + PERLLIB: # Save the contents of @INC before they are modified elsewhere. @ini_INC = @INC; # This was an attempt to clear out the previous values of various # trapped errors. Apparently it didn't help. XXX More info needed! # $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?! # We set these variables to safe values. We don't want to blindly turn # off warnings, because other packages may still want them. $trace = $signal = $single = 0; # Uninitialized warning suppression # (local $^W cannot help - other packages!). # Default to not exiting when program finishes; print the return # value when the 'r' command is used to return from a subroutine. $inhibit_exit = $option{PrintRet} = 1; use vars qw($trace_to_depth); # Default to 1E9 so it won't be limited to a certain recursion depth. $trace_to_depth = 1E9; =head1 OPTION PROCESSING The debugger's options are actually spread out over the debugger itself and C; some of these are variables to be set, while others are subs to be called with a value. To try to make this a little easier to manage, the debugger uses a few data structures to define what options are legal and how they are to be processed. First, the C<@options> array defines the I of all the options that are to be accepted. =cut @options = qw( CommandSet HistFile HistSize HistItemMinLength hashDepth arrayDepth dumpDepth DumpDBFiles DumpPackages DumpReused compactDump veryCompact quote HighBit undefPrint globPrint PrintRet UsageOnly frame AutoTrace TTY noTTY ReadLine NonStop LineInfo maxTraceLen recallCommand ShellBang pager tkRunning ornaments signalLevel warnLevel dieLevel inhibit_exit ImmediateStop bareStringify CreateTTY RemotePort windowSize DollarCaretP ); @RememberOnROptions = qw(DollarCaretP); =pod Second, C lists the variables that each option uses to save its state. =cut use vars qw(%optionVars); %optionVars = ( hashDepth => \$dumpvar::hashDepth, arrayDepth => \$dumpvar::arrayDepth, CommandSet => \$CommandSet, DumpDBFiles => \$dumpvar::dumpDBFiles, DumpPackages => \$dumpvar::dumpPackages, DumpReused => \$dumpvar::dumpReused, HighBit => \$dumpvar::quoteHighBit, undefPrint => \$dumpvar::printUndef, globPrint => \$dumpvar::globPrint, UsageOnly => \$dumpvar::usageOnly, CreateTTY => \$CreateTTY, bareStringify => \$dumpvar::bareStringify, frame => \$frame, AutoTrace => \$trace, inhibit_exit => \$inhibit_exit, maxTraceLen => \$maxtrace, ImmediateStop => \$ImmediateStop, RemotePort => \$remoteport, windowSize => \$window, HistFile => \$histfile, HistSize => \$histsize, HistItemMinLength => \$histitemminlength ); =pod Third, C<%optionAction> defines the subroutine to be called to process each option. =cut use vars qw(%optionAction); %optionAction = ( compactDump => \&dumpvar::compactDump, veryCompact => \&dumpvar::veryCompact, quote => \&dumpvar::quote, TTY => \&TTY, noTTY => \&noTTY, ReadLine => \&ReadLine, NonStop => \&NonStop, LineInfo => \&LineInfo, recallCommand => \&recallCommand, ShellBang => \&shellBang, pager => \&pager, signalLevel => \&signalLevel, warnLevel => \&warnLevel, dieLevel => \&dieLevel, tkRunning => \&tkRunning, ornaments => \&ornaments, RemotePort => \&RemotePort, DollarCaretP => \&DollarCaretP, ); =pod Last, the C<%optionRequire> notes modules that must be Cd if an option is used. =cut # Note that this list is not complete: several options not listed here # actually require that dumpvar.pl be loaded for them to work, but are # not in the table. A subsequent patch will correct this problem; for # the moment, we're just recommenting, and we are NOT going to change # function. use vars qw(%optionRequire); %optionRequire = ( compactDump => 'dumpvar.pl', veryCompact => 'dumpvar.pl', quote => 'dumpvar.pl', ); =pod There are a number of initialization-related variables which can be set by putting code to set them in a BEGIN block in the C environment variable. These are: =over 4 =item C<$rl> - readline control XXX needs more explanation =item C<$warnLevel> - whether or not debugger takes over warning handling =item C<$dieLevel> - whether or not debugger takes over die handling =item C<$signalLevel> - whether or not debugger takes over signal handling =item C<$pre> - preprompt actions (array reference) =item C<$post> - postprompt actions (array reference) =item C<$pretype> =item C<$CreateTTY> - whether or not to create a new TTY for this debugger =item C<$CommandSet> - which command set to use (defaults to new, documented set) =back =cut # These guys may be defined in $ENV{PERL5DB} : $rl = 1 unless defined $rl; $warnLevel = 1 unless defined $warnLevel; $dieLevel = 1 unless defined $dieLevel; $signalLevel = 1 unless defined $signalLevel; $pre = [] unless defined $pre; $post = [] unless defined $post; $pretype = [] unless defined $pretype; $CreateTTY = 3 unless defined $CreateTTY; $CommandSet = '580' unless defined $CommandSet; share($rl); share($warnLevel); share($dieLevel); share($signalLevel); share($pre); share($post); share($pretype); share($CreateTTY); share($CommandSet); =pod The default C, C, and C handlers are set up. =cut warnLevel($warnLevel); dieLevel($dieLevel); signalLevel($signalLevel); =pod The pager to be used is needed next. We try to get it from the environment first. If it's not defined there, we try to find it in the Perl C. If it's not there, we default to C. We then call the C function to save the pager name. =cut # This routine makes sure $pager is set up so that '|' can use it. pager( # If PAGER is defined in the environment, use it. defined $ENV{PAGER} ? $ENV{PAGER} # If not, see if Config.pm defines it. : eval { require Config } && defined $Config::Config{pager} ? $Config::Config{pager} # If not, fall back to 'more'. : 'more' ) unless defined $pager; =pod We set up the command to be used to access the man pages, the command recall character (C unless otherwise defined) and the shell escape character (C unless otherwise defined). Yes, these do conflict, and neither works in the debugger at the moment. =cut setman(); # Set up defaults for command recall and shell escape (note: # these currently don't work in linemode debugging). recallCommand("!") unless defined $prc; shellBang("!") unless defined $psh; =pod We then set up the gigantic string containing the debugger help. We also set the limit on the number of arguments we'll display during a trace. =cut sethelp(); # If we didn't get a default for the length of eval/stack trace args, # set it here. $maxtrace = 400 unless defined $maxtrace; =head2 SETTING UP THE DEBUGGER GREETING The debugger I helps to inform the user how many debuggers are running, and whether the current debugger is the primary or a child. If we are the primary, we just hang onto our pid so we'll have it when or if we start a child debugger. If we are a child, we'll set things up so we'll have a unique greeting and so the parent will give us our own TTY later. We save the current contents of the C environment variable because we mess around with it. We'll also need to hang onto it because we'll need it if we restart. Child debuggers make a label out of the current PID structure recorded in PERLDB_PIDS plus the new PID. They also mark themselves as not having a TTY yet so the parent will give them one later via C. =cut # Save the current contents of the environment; we're about to # much with it. We'll need this if we have to restart. use vars qw($ini_pids); $ini_pids = $ENV{PERLDB_PIDS}; use vars qw ($pids $term_pid); if ( defined $ENV{PERLDB_PIDS} ) { # We're a child. Make us a label out of the current PID structure # recorded in PERLDB_PIDS plus our (new) PID. Mark us as not having # a term yet so the parent will give us one later via resetterm(). my $env_pids = $ENV{PERLDB_PIDS}; $pids = "[$env_pids]"; # Unless we are on OpenVMS, all programs under the DCL shell run under # the same PID. if (($^O eq 'VMS') && ($env_pids =~ /\b$$\b/)) { $term_pid = $$; } else { $ENV{PERLDB_PIDS} .= "->$$"; $term_pid = -1; } } ## end if (defined $ENV{PERLDB_PIDS... else { # We're the parent PID. Initialize PERLDB_PID in case we end up with a # child debugger, and mark us as the parent, so we'll know to set up # more TTY's is we have to. $ENV{PERLDB_PIDS} = "$$"; $pids = "[pid=$$]"; $term_pid = $$; } use vars qw($pidprompt); $pidprompt = ''; # Sets up $emacs as a synonym for $client_editor. our ($client_editor); *emacs = $client_editor if $client_editor; # May be used in afterinit()... =head2 READING THE RC FILE The debugger will read a file of initialization options if supplied. If running interactively, this is C<.perldb>; if not, it's C. =cut # As noted, this test really doesn't check accurately that the debugger # is running at a terminal or not. use vars qw($rcfile); { my $dev_tty = (($^O eq 'VMS') ? 'TT:' : '/dev/tty'); # this is the wrong metric! $rcfile = ((-e $dev_tty) ? ".perldb" : "perldb.ini"); } =pod The debugger does a safety test of the file to be read. It must be owned either by the current user or root, and must only be writable by the owner. =cut # This wraps a safety test around "do" to read and evaluate the init file. # # This isn't really safe, because there's a race # between checking and opening. The solution is to # open and fstat the handle, but then you have to read and # eval the contents. But then the silly thing gets # your lexical scope, which is unfortunate at best. sub safe_do { my $file = shift; # Just exactly what part of the word "CORE::" don't you understand? local $SIG{__WARN__}; local $SIG{__DIE__}; unless ( is_safe_file($file) ) { CORE::warn < command is invoked, it tries to capture all of the state it can into environment variables, and then sets C. When we start executing again, we check to see if C is there; if so, we reload all the information that the R command stuffed into the environment variables. PERLDB_RESTART - flag only, contains no restart data itself. PERLDB_HIST - command history, if it's available PERLDB_ON_LOAD - breakpoints set by the rc file PERLDB_POSTPONE - subs that have been loaded/not executed, and have actions PERLDB_VISITED - files that had breakpoints PERLDB_FILE_... - breakpoints for a file PERLDB_OPT - active options PERLDB_INC - the original @INC PERLDB_PRETYPE - preprompt debugger actions PERLDB_PRE - preprompt Perl code PERLDB_POST - post-prompt Perl code PERLDB_TYPEAHEAD - typeahead captured by readline() We chug through all these variables and plug the values saved in them back into the appropriate spots in the debugger. =cut use vars qw(%postponed_file @typeahead); our (@hist, @truehist); sub _restore_shared_globals_after_restart { @hist = get_list('PERLDB_HIST'); %break_on_load = get_list("PERLDB_ON_LOAD"); %postponed = get_list("PERLDB_POSTPONE"); share(@hist); share(@truehist); share(%break_on_load); share(%postponed); } sub _restore_breakpoints_and_actions { my @had_breakpoints = get_list("PERLDB_VISITED"); for my $file_idx ( 0 .. $#had_breakpoints ) { my $filename = $had_breakpoints[$file_idx]; my %pf = get_list("PERLDB_FILE_$file_idx"); $postponed_file{ $filename } = \%pf if %pf; my @lines = sort {$a <=> $b} keys(%pf); my @enabled_statuses = get_list("PERLDB_FILE_ENABLED_$file_idx"); for my $line_idx (0 .. $#lines) { _set_breakpoint_enabled_status( $filename, $lines[$line_idx], ($enabled_statuses[$line_idx] ? 1 : ''), ); } } return; } sub _restore_options_after_restart { my %options_map = get_list("PERLDB_OPT"); while ( my ( $opt, $val ) = each %options_map ) { $val =~ s/[\\\']/\\$1/g; parse_options("$opt'$val'"); } return; } sub _restore_globals_after_restart { # restore original @INC @INC = get_list("PERLDB_INC"); @ini_INC = @INC; # return pre/postprompt actions and typeahead buffer $pretype = [ get_list("PERLDB_PRETYPE") ]; $pre = [ get_list("PERLDB_PRE") ]; $post = [ get_list("PERLDB_POST") ]; @typeahead = get_list( "PERLDB_TYPEAHEAD", @typeahead ); return; } if ( exists $ENV{PERLDB_RESTART} ) { # We're restarting, so we don't need the flag that says to restart anymore. delete $ENV{PERLDB_RESTART}; # $restart = 1; _restore_shared_globals_after_restart(); _restore_breakpoints_and_actions(); # restore options _restore_options_after_restart(); _restore_globals_after_restart(); } ## end if (exists $ENV{PERLDB_RESTART... =head2 SETTING UP THE TERMINAL Now, we'll decide how the debugger is going to interact with the user. If there's no TTY, we set the debugger to run non-stop; there's not going to be anyone there to enter commands. =cut use vars qw($notty $console $tty $LINEINFO); use vars qw($lineinfo $doccmd); our ($runnonstop); # Local autoflush to avoid rt#116769, # as calling IO::File methods causes an unresolvable loop # that results in debugger failure. sub _autoflush { my $o = select($_[0]); $|++; select($o); } if ($notty) { $runnonstop = 1; share($runnonstop); } =pod If there is a TTY, we have to determine who it belongs to before we can proceed. If this is a client editor or graphical debugger (denoted by the first command-line switch being '-emacs'), we shift this off and set C<$rl> to 0 (XXX ostensibly to do straight reads). =cut else { # Is Perl being run from a client editor or graphical debugger? # If so, don't use readline, and set $client_editor = 1. if ($client_editor = ( @main::ARGV && ( $main::ARGV[0] eq '-emacs' ) )) { $rl = 0; shift(@main::ARGV); } #require Term::ReadLine; =pod We then determine what the console should be on various systems: =over 4 =item * Cygwin - We use C instead of a separate device. =cut if ( $^O eq 'cygwin' ) { # /dev/tty is binary. use stdin for textmode undef $console; } =item * Windows - use C. =cut elsif ( $^O eq 'MSWin32' and -e "con" ) { $console = "con"; } =item * AmigaOS - use C. =cut elsif ( $^O eq 'amigaos' ) { $console = "CONSOLE:"; } =item * VMS - use C. =cut elsif ($^O eq 'VMS') { $console = 'sys$command'; } # Keep this penultimate, on the grounds that it satisfies a wide variety of # Unix-like systems that would otherwise need to be identified individually. =item * Unix - use F. =cut elsif ( -e "/dev/tty" ) { $console = "/dev/tty"; } # Keep this last. else { _db_warn("Can't figure out your console, using stdin"); undef $console; } =pod =back Several other systems don't use a specific console. We S> for those (Windows using a client editor/graphical debugger, OS/2 with a client editor). =cut if ( ( $^O eq 'MSWin32' ) and ( $client_editor or defined $ENV{EMACS} ) ) { # /dev/tty is binary. use stdin for textmode $console = undef; } # In OS/2, we need to use STDIN to get textmode too, even though # it pretty much looks like Unix otherwise. if ( defined $ENV{OS2_SHELL} and ( $client_editor or $ENV{WINDOWID} ) ) { # In OS/2 $console = undef; } =pod If there is a TTY hanging around from a parent, we use that as the console. =cut $console = $tty if defined $tty; =head2 SOCKET HANDLING The debugger is capable of opening a socket and carrying out a debugging session over the socket. If C was defined in the options, the debugger assumes that it should try to start a debugging session on that port. It builds the socket and then tries to connect the input and output filehandles to it. =cut # Handle socket stuff. if ( defined $remoteport ) { # If RemotePort was defined in the options, connect input and output # to the socket. $IN = $OUT = connect_remoteport(); } ## end if (defined $remoteport) =pod If no C was defined, and we want to create a TTY on startup, this is probably a situation where multiple debuggers are running (for example, a backticked command that starts up another debugger). We create a new IN and OUT filehandle, and do the necessary mojo to create a new TTY if we know how and if we can. =cut # Non-socket. else { # Two debuggers running (probably a system or a backtick that invokes # the debugger itself under the running one). create a new IN and OUT # filehandle, and do the necessary mojo to create a new tty if we # know how, and we can. create_IN_OUT(4) if $CreateTTY & 4; if ($console) { # If we have a console, check to see if there are separate ins and # outs to open. (They are assumed identical if not.) my ( $i, $o ) = split /,/, $console; $o = $i unless defined $o; # read/write on in, or just read, or read on STDIN. open( IN, '+<', $i ) || open( IN, '<', $i ) || open( IN, "<&STDIN" ); # read/write/create/clobber out, or write/create/clobber out, # or merge with STDERR, or merge with STDOUT. open( OUT, '+>', $o ) || open( OUT, '>', $o ) || open( OUT, ">&STDERR" ) || open( OUT, ">&STDOUT" ); # so we don't dongle stdout } ## end if ($console) elsif ( not defined $console ) { # No console. Open STDIN. open( IN, "<&STDIN" ); # merge with STDERR, or with STDOUT. open( OUT, ">&STDERR" ) || open( OUT, ">&STDOUT" ); # so we don't dongle stdout $console = 'STDIN/OUT'; } ## end elsif (not defined $console) # Keep copies of the filehandles so that when the pager runs, it # can close standard input without clobbering ours. if ($console or (not defined($console))) { $IN = \*IN; $OUT = \*OUT; } } ## end elsif (from if(defined $remoteport)) # Unbuffer DB::OUT. We need to see responses right away. _autoflush($OUT); # Line info goes to debugger output unless pointed elsewhere. # Pointing elsewhere makes it possible for client editors to # keep track of file and position. We have both a filehandle # and a I/O description to keep track of. $LINEINFO = $OUT unless defined $LINEINFO; $lineinfo = $console unless defined $lineinfo; # share($LINEINFO); # <- unable to share globs share($lineinfo); # =pod To finish initialization, we show the debugger greeting, and then call the C subroutine if there is one. =cut # Show the debugger greeting. $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/; unless ($runnonstop) { local $\ = ''; local $, = ''; if ( $term_pid eq '-1' ) { print $OUT "\nDaughter DB session started...\n"; } else { print $OUT "\nLoading DB routines from $header\n"; print $OUT ( "Editor support ", $client_editor ? "enabled" : "available", ".\n" ); print $OUT "\nEnter h or 'h h' for help, or '$doccmd perldebug' for more help.\n\n"; } ## end else [ if ($term_pid eq '-1') } ## end unless ($runnonstop) } ## end else [ if ($notty) # XXX This looks like a bug to me. # Why copy to @ARGS and then futz with @args? @ARGS = @ARGV; # for (@args) { # Make sure backslashes before single quotes are stripped out, and # keep args unless they are numeric (XXX why?) # s/\'/\\\'/g; # removed while not justified understandably # s/(.*)/'$1'/ unless /^-?[\d.]+$/; # ditto # } # If there was an afterinit() sub defined, call it. It will get # executed in our scope, so it can fiddle with debugger globals. if ( defined &afterinit ) { # May be defined in $rcfile afterinit(); } # Inform us about "Stack dump during die enabled ..." in dieLevel(). use vars qw($I_m_init); $I_m_init = 1; ############################################################ Subroutines =head1 SUBROUTINES =head2 DB This gigantic subroutine is the heart of the debugger. Called before every statement, its job is to determine if a breakpoint has been reached, and stop if so; read commands from the user, parse them, and execute them, and then send execution off to the next statement. Note that the order in which the commands are processed is very important; some commands earlier in the loop will actually alter the C<$cmd> variable to create other commands to be executed later. This is all highly I but can be confusing. Check the comments for each C<$cmd ... && do {}> to see what's happening in any given command. =cut # $cmd cannot be an our() variable unfortunately (possible perl bug?). use vars qw( $action $cmd $file $filename_ini $finished %had_breakpoints $level $max $package $try ); our ( %alias, $doret, $end, $fall_off_end, $incr, $laststep, $rc, $sh, $stack_depth, @stack, @to_watch, @old_watch, ); sub _DB__determine_if_we_should_break { # if we have something here, see if we should break. # $stop is lexical and local to this block - $action on the other hand # is global. my $stop; if ( $dbline{$line} && _is_breakpoint_enabled($filename, $line) && (( $stop, $action ) = split( /\0/, $dbline{$line} ) ) ) { # Stop if the stop criterion says to just stop. if ( $stop eq '1' ) { $signal |= 1; } # It's a conditional stop; eval it in the user's context and # see if we should stop. If so, remove the one-time sigil. elsif ($stop) { $evalarg = "\$DB::signal |= 1 if do {$stop}"; # The &-call is here to ascertain the mutability of @_. &DB::eval; # If the breakpoint is temporary, then delete its enabled status. if ($dbline{$line} =~ s/;9($|\0)/$1/) { _cancel_breakpoint_temp_enabled_status($filename, $line); } } } ## end if ($dbline{$line} && ... } sub _DB__is_finished { if ($finished and $level <= 1) { end_report(); return 1; } else { return; } } sub _DB__read_next_cmd { my ($tid) = @_; # We have a terminal, or can get one ... if (!$term) { setterm(); } # ... and it belongs to this PID or we get one for this PID ... if ($term_pid != $$) { resetterm(1); } # ... and we got a line of command input ... $cmd = DB::readline( "$pidprompt $tid DB" . ( '<' x $level ) . ( $#hist + 1 ) . ( '>' x $level ) . " " ); return defined($cmd); } sub _DB__trim_command_and_return_first_component { my ($obj) = @_; $cmd =~ s/\A\s+//s; # trim annoying leading whitespace $cmd =~ s/\s+\z//s; # trim annoying trailing whitespace # A single-character debugger command can be immediately followed by its # argument if they aren't both alphanumeric; otherwise require space # between commands and arguments: my ($verb, $args) = $cmd =~ m{\A([^\.-]\b|\S*)\s*(.*)}s; $obj->cmd_verb($verb); $obj->cmd_args($args); return; } sub _DB__handle_f_command { my ($obj) = @_; if ($file = $obj->cmd_args) { # help for no arguments (old-style was return from sub). if ( !$file ) { print $OUT "The old f command is now the r command.\n"; # hint print $OUT "The new f command switches filenames.\n"; next CMD; } ## end if (!$file) # if not in magic file list, try a close match. if ( !defined $main::{ '_<' . $file } ) { if ( ($try) = grep( m#^_<.*$file#, keys %main:: ) ) { { $try = substr( $try, 2 ); print $OUT "Choosing $try matching '$file':\n"; $file = $try; } } ## end if (($try) = grep(m#^_<.*$file#... } ## end if (!defined $main::{ ... # If not successfully switched now, we failed. if ( !defined $main::{ '_<' . $file } ) { print $OUT "No file matching '$file' is loaded.\n"; next CMD; } # We switched, so switch the debugger internals around. elsif ( $file ne $filename ) { *dbline = $main::{ '_<' . $file }; $max = $#dbline; $filename = $file; $start = 1; $cmd = "l"; } ## end elsif ($file ne $filename) # We didn't switch; say we didn't. else { print $OUT "Already in $file.\n"; next CMD; } } return; } sub _DB__handle_dot_command { my ($obj) = @_; # . command. if ($obj->_is_full('.')) { $incr = -1; # stay at current line # Reset everything to the old location. $start = $line; $filename = $filename_ini; *dbline = $main::{ '_<' . $filename }; $max = $#dbline; # Now where are we? print_lineinfo($obj->position()); next CMD; } return; } sub _DB__handle_y_command { my ($obj) = @_; if (my ($match_level, $match_vars) = $obj->cmd_args =~ /\A(?:(\d*)\s*(.*))?\z/) { # See if we've got the necessary support. if (!eval { local @INC = @INC; pop @INC if $INC[-1] eq '.'; require PadWalker; PadWalker->VERSION(0.08) }) { my $Err = $@; _db_warn( $Err =~ /locate/ ? "PadWalker module not found - please install\n" : $Err ); next CMD; } # Load up dumpvar if we don't have it. If we can, that is. do 'dumpvar.pl' || die $@ unless defined &main::dumpvar; defined &main::dumpvar or print $OUT "dumpvar.pl not available.\n" and next CMD; # Got all the modules we need. Find them and print them. my @vars = split( ' ', $match_vars || '' ); # Find the pad. my $h = eval { PadWalker::peek_my( ( $match_level || 0 ) + 2 ) }; # Oops. Can't find it. if (my $Err = $@) { $Err =~ s/ at .*//; _db_warn($Err); next CMD; } # Show the desired vars with dumplex(). my $savout = select($OUT); # Have dumplex dump the lexicals. foreach my $key (sort keys %$h) { dumpvar::dumplex( $key, $h->{$key}, defined $option{dumpDepth} ? $option{dumpDepth} : -1, @vars ); } select($savout); next CMD; } } sub _DB__handle_c_command { my ($obj) = @_; my $i = $obj->cmd_args; if ($i =~ m#\A[\w:]*\z#) { # Hey, show's over. The debugged program finished # executing already. next CMD if _DB__is_finished(); # Capture the place to put a one-time break. $subname = $i; # Probably not needed, since we finish an interactive # sub-session anyway... # local $filename = $filename; # local *dbline = *dbline; # XXX Would this work?! # # The above question wonders if localizing the alias # to the magic array works or not. Since it's commented # out, we'll just leave that to speculation for now. # If the "subname" isn't all digits, we'll assume it # is a subroutine name, and try to find it. if ( $subname =~ /\D/ ) { # subroutine name # Qualify it to the current package unless it's # already qualified. $subname = $package . "::" . $subname unless $subname =~ /::/; # find_sub will return "file:line_number" corresponding # to where the subroutine is defined; we call find_sub, # break up the return value, and assign it in one # operation. ( $file, $i ) = ( find_sub($subname) =~ /^(.*):(.*)$/ ); # Force the line number to be numeric. $i = $i + 0; # If we got a line number, we found the sub. if ($i) { # Switch all the debugger's internals around so # we're actually working with that file. $filename = $file; *dbline = $main::{ '_<' . $filename }; # Mark that there's a breakpoint in this file. $had_breakpoints{$filename} |= 1; # Scan forward to the first executable line # after the 'sub whatever' line. $max = $#dbline; my $_line_num = $i; while ($dbline[$_line_num] == 0 && $_line_num< $max) { $_line_num++; } $i = $_line_num; } ## end if ($i) # We didn't find a sub by that name. else { print $OUT "Subroutine $subname not found.\n"; next CMD; } } ## end if ($subname =~ /\D/) # At this point, either the subname was all digits (an # absolute line-break request) or we've scanned through # the code following the definition of the sub, looking # for an executable, which we may or may not have found. # # If $i (which we set $subname from) is non-zero, we # got a request to break at some line somewhere. On # one hand, if there wasn't any real subroutine name # involved, this will be a request to break in the current # file at the specified line, so we have to check to make # sure that the line specified really is breakable. # # On the other hand, if there was a subname supplied, the # preceding block has moved us to the proper file and # location within that file, and then scanned forward # looking for the next executable line. We have to make # sure that one was found. # # On the gripping hand, we can't do anything unless the # current value of $i points to a valid breakable line. # Check that. if ($i) { # Breakable? if ( $dbline[$i] == 0 ) { print $OUT "Line $i not breakable.\n"; next CMD; } # Yes. Set up the one-time-break sigil. $dbline{$i} =~ s/($|\0)/;9$1/; # add one-time-only b.p. _enable_breakpoint_temp_enabled_status($filename, $i); } ## end if ($i) # Turn off stack tracing from here up. for my $j (0 .. $stack_depth) { $stack[ $j ] &= ~1; } last CMD; } return; } my $sub_twice = chr utf8::unicode_to_native(032); $sub_twice = $sub_twice x 2; sub _DB__handle_forward_slash_command { my ($obj) = @_; # The pattern as a string. use vars qw($inpat); if (($inpat) = $cmd =~ m#\A/(.*)\z#) { # Remove the final slash. $inpat =~ s:([^\\])/$:$1:; # If the pattern isn't null ... if ( $inpat ne "" ) { # Turn off warn and die processing for a bit. local $SIG{__DIE__}; local $SIG{__WARN__}; # Create the pattern. eval 'no strict q/vars/; $inpat =~ m' . "\a$inpat\a"; if ( $@ ne "" ) { # Oops. Bad pattern. No biscuit. # Print the eval error and go back for more # commands. print {$OUT} "$@"; next CMD; } $obj->pat($inpat); } ## end if ($inpat ne "") # Set up to stop on wrap-around. $end = $start; # Don't move off the current line. $incr = -1; my $pat = $obj->pat; # Done in eval so nothing breaks if the pattern # does something weird. eval { no strict q/vars/; for (;;) { # Move ahead one line. ++$start; # Wrap if we pass the last line. if ($start > $max) { $start = 1; } # Stop if we have gotten back to this line again, last if ($start == $end); # A hit! (Note, though, that we are doing # case-insensitive matching. Maybe a qr// # expression would be better, so the user could # do case-sensitive matching if desired. if ($dbline[$start] =~ m/$pat/i) { if ($client_editor) { # Handle proper escaping in the client. print {$OUT} "$sub_twice$filename:$start:0\n"; } else { # Just print the line normally. print {$OUT} "$start:\t",$dbline[$start],"\n"; } # And quit since we found something. last; } } }; if ($@) { warn $@; } # If we wrapped, there never was a match. if ( $start == $end ) { print {$OUT} "/$pat/: not found\n"; } next CMD; } return; } sub _DB__handle_question_mark_command { my ($obj) = @_; # ? - backward pattern search. if (my ($inpat) = $cmd =~ m#\A\?(.*)\z#) { # Get the pattern, remove trailing question mark. $inpat =~ s:([^\\])\?$:$1:; # If we've got one ... if ( $inpat ne "" ) { # Turn off die & warn handlers. local $SIG{__DIE__}; local $SIG{__WARN__}; eval '$inpat =~ m' . "\a$inpat\a"; if ( $@ ne "" ) { # Ouch. Not good. Print the error. print $OUT $@; next CMD; } $obj->pat($inpat); } ## end if ($inpat ne "") # Where we are now is where to stop after wraparound. $end = $start; # Don't move away from this line. $incr = -1; my $pat = $obj->pat; # Search inside the eval to prevent pattern badness # from killing us. eval { no strict q/vars/; for (;;) { # Back up a line. --$start; # Wrap if we pass the first line. $start = $max if ($start <= 0); # Quit if we get back where we started, last if ($start == $end); # Match? if ($dbline[$start] =~ m/$pat/i) { if ($client_editor) { # Yep, follow client editor requirements. print $OUT "$sub_twice$filename:$start:0\n"; } else { # Yep, just print normally. print $OUT "$start:\t",$dbline[$start],"\n"; } # Found, so done. last; } } }; # Say we failed if the loop never found anything, if ( $start == $end ) { print {$OUT} "?$pat?: not found\n"; } next CMD; } return; } sub _DB__handle_restart_and_rerun_commands { my ($obj) = @_; my $cmd_cmd = $obj->cmd_verb; my $cmd_params = $obj->cmd_args; # R - restart execution. # rerun - controlled restart execution. if ($cmd_cmd eq 'rerun' or $cmd_params eq '') { # Change directory to the initial current working directory on # the script startup, so if the debugged program changed the # directory, then we will still be able to find the path to the # program. (perl 5 RT #121509 ). chdir ($_initial_cwd); my @args = ($cmd_cmd eq 'R' ? restart() : rerun($cmd_params)); # Close all non-system fds for a clean restart. A more # correct method would be to close all fds that were not # open when the process started, but this seems to be # hard. See "debugger 'R'estart and open database # connections" on p5p. my $max_fd = 1024; # default if POSIX can't be loaded if (eval { require POSIX }) { eval { $max_fd = POSIX::sysconf(POSIX::_SC_OPEN_MAX()) }; } if (defined $max_fd) { foreach ($^F+1 .. $max_fd-1) { next unless open FD_TO_CLOSE, "<&=$_"; close(FD_TO_CLOSE); } } # And run Perl again. We use exec() to keep the # PID stable (and that way $ini_pids is still valid). exec(@args) or print {$OUT} "exec failed: $!\n"; last CMD; } return; } sub _DB__handle_run_command_in_pager_command { my ($obj) = @_; if ($cmd =~ m#\A\|\|?\s*[^|]#) { if ( $pager =~ /^\|/ ) { # Default pager is into a pipe. Redirect I/O. open( SAVEOUT, ">&STDOUT" ) || _db_warn("Can't save STDOUT"); open( STDOUT, ">&OUT" ) || _db_warn("Can't redirect STDOUT"); } ## end if ($pager =~ /^\|/) else { # Not into a pipe. STDOUT is safe. open( SAVEOUT, ">&OUT" ) || _db_warn("Can't save DB::OUT"); } # Fix up environment to record we have less if so. fix_less(); unless ( $obj->piped(scalar ( open( OUT, $pager ) ) ) ) { # Couldn't open pipe to pager. _db_warn("Can't pipe output to '$pager'"); if ( $pager =~ /^\|/ ) { # Redirect I/O back again. open( OUT, ">&STDOUT" ) # XXX: lost message || _db_warn("Can't restore DB::OUT"); open( STDOUT, ">&SAVEOUT" ) || _db_warn("Can't restore STDOUT"); close(SAVEOUT); } ## end if ($pager =~ /^\|/) else { # Redirect I/O. STDOUT already safe. open( OUT, ">&STDOUT" ) # XXX: lost message || _db_warn("Can't restore DB::OUT"); } next CMD; } ## end unless ($piped = open(OUT,... # Set up broken-pipe handler if necessary. $SIG{PIPE} = \&DB::catch if $pager =~ /^\|/ && ( "" eq $SIG{PIPE} || "DEFAULT" eq $SIG{PIPE} ); _autoflush(\*OUT); # Save current filehandle, and put it back. $obj->selected(scalar( select(OUT) )); # Don't put it back if pager was a pipe. if ($cmd !~ /\A\|\|/) { select($obj->selected()); $obj->selected(""); } # Trim off the pipe symbols and run the command now. $cmd =~ s#\A\|+\s*##; redo PIPE; } return; } sub _DB__handle_m_command { my ($obj) = @_; if ($cmd =~ s#\Am\s+([\w:]+)\s*\z# #) { methods($1); next CMD; } # m expr - set up DB::eval to do the work if ($cmd =~ s#\Am\b# #) { # Rest gets done by DB::eval() $onetimeDump = 'methods'; # method output gets used there } return; } sub _DB__at_end_of_every_command { my ($obj) = @_; # At the end of every command: if ($obj->piped) { # Unhook the pipe mechanism now. if ( $pager =~ /^\|/ ) { # No error from the child. $? = 0; # we cannot warn here: the handle is missing --tchrist close(OUT) || print SAVEOUT "\nCan't close DB::OUT\n"; # most of the $? crud was coping with broken cshisms # $? is explicitly set to 0, so this never runs. if ($?) { print SAVEOUT "Pager '$pager' failed: "; if ( $? == -1 ) { print SAVEOUT "shell returned -1\n"; } elsif ( $? >> 8 ) { print SAVEOUT ( $? & 127 ) ? " (SIG#" . ( $? & 127 ) . ")" : "", ( $? & 128 ) ? " -- core dumped" : "", "\n"; } else { print SAVEOUT "status ", ( $? >> 8 ), "\n"; } } ## end if ($?) # Reopen filehandle for our output (if we can) and # restore STDOUT (if we can). open( OUT, ">&STDOUT" ) || _db_warn("Can't restore DB::OUT"); open( STDOUT, ">&SAVEOUT" ) || _db_warn("Can't restore STDOUT"); # Turn off pipe exception handler if necessary. $SIG{PIPE} = "DEFAULT" if $SIG{PIPE} eq \&DB::catch; # Will stop ignoring SIGPIPE if done like nohup(1) # does SIGINT but Perl doesn't give us a choice. } ## end if ($pager =~ /^\|/) else { # Non-piped "pager". Just restore STDOUT. open( OUT, ">&SAVEOUT" ) || _db_warn("Can't restore DB::OUT"); } # Let Readline know about the new filehandles. reset_IN_OUT( \*IN, \*OUT ); # Close filehandle pager was using, restore the normal one # if necessary, close(SAVEOUT); if ($obj->selected() ne "") { select($obj->selected); $obj->selected(""); } # No pipes now. $obj->piped(""); } ## end if ($piped) return; } sub _DB__handle_watch_expressions { my $self = shift; if ( $DB::trace & 2 ) { for my $n (0 .. $#DB::to_watch) { $DB::evalarg = $DB::to_watch[$n]; local $DB::onetimeDump; # Tell DB::eval() to not output results # Fix context DB::eval() wants to return an array, but # we need a scalar here. my ($val) = join( "', '", DB::eval(@_) ); $val = ( ( defined $val ) ? "'$val'" : 'undef' ); # Did it change? if ( $val ne $DB::old_watch[$n] ) { # Yep! Show the difference, and fake an interrupt. $DB::signal = 1; print {$DB::OUT} < - inheritance display Display the (nested) parentage of the module or object given. =cut sub _DB__handle_i_command { my $self = shift; my $line = $self->cmd_args; require mro; foreach my $isa ( split( /\s+/, $line ) ) { $evalarg = "$isa"; # The &-call is here to ascertain the mutability of @_. ($isa) = &DB::eval; no strict 'refs'; print join( ', ', map { "$_" . ( defined( ${"$_\::VERSION"} ) ? ' ' . ${"$_\::VERSION"} : undef ) } @{mro::get_linear_isa(ref($isa) || $isa)} ); print "\n"; } next CMD; } =head3 C<_cmd_l_main> - list lines (command) Most of the command is taken up with transforming all the different line specification syntaxes into 'start-stop'. After that is done, the command runs a loop over C<@dbline> for the specified range of lines. It handles the printing of each line and any markers (C<==E> for current line, C for break on this line, C for action on this line, C<:> for this line breakable). We save the last line listed in the C<$start> global for further listing later. =cut sub _min { my $min = shift; foreach my $v (@_) { if ($min > $v) { $min = $v; } } return $min; } sub _max { my $max = shift; foreach my $v (@_) { if ($max < $v) { $max = $v; } } return $max; } sub _minify_to_max { my $ref = shift; $$ref = _min($$ref, $max); return; } sub _cmd_l_handle_var_name { my $var_name = shift; $evalarg = $var_name; my ($s) = DB::eval(); # Ooops. Bad scalar. if ($@) { print {$OUT} "Error: $@\n"; next CMD; } # Good scalar. If it's a reference, find what it points to. $s = CvGV_name($s); print {$OUT} "Interpreted as: $1 $s\n"; $line = "$1 $s"; # Call self recursively to really do the command. return _cmd_l_main( $s ); } sub _cmd_l_handle_subname { my $s = my $subname = shift; # De-Perl4. $subname =~ s/\'/::/; # Put it in this package unless it starts with ::. $subname = $package . "::" . $subname unless $subname =~ /::/; # Put it in CORE::GLOBAL if t doesn't start with :: and # it doesn't live in this package and it lives in CORE::GLOBAL. $subname = "CORE::GLOBAL::$s" if not defined &$subname and $s !~ /::/ and defined &{"CORE::GLOBAL::$s"}; # Put leading '::' names into 'main::'. $subname = "main" . $subname if substr( $subname, 0, 2 ) eq "::"; # Get name:start-stop from find_sub, and break this up at # colons. my @pieces = split( /:/, find_sub($subname) || $sub{$subname} ); # Pull off start-stop. my $subrange = pop @pieces; # If the name contained colons, the split broke it up. # Put it back together. $file = join( ':', @pieces ); # If we're not in that file, switch over to it. if ( $file ne $filename ) { if (! $client_editor) { print {$OUT} "Switching to file '$file'.\n"; } # Switch debugger's magic structures. *dbline = $main::{ '_<' . $file }; $max = $#dbline; $filename = $file; } ## end if ($file ne $filename) # Subrange is 'start-stop'. If this is less than a window full, # swap it to 'start+', which will list a window from the start point. if ($subrange) { if ( eval($subrange) < -$window ) { $subrange =~ s/-.*/+/; } # Call self recursively to list the range. return _cmd_l_main( $subrange ); } ## end if ($subrange) # Couldn't find it. else { print {$OUT} "Subroutine $subname not found.\n"; return; } } sub _cmd_l_empty { # Compute new range to list. $incr = $window - 1; # Recurse to do it. return _cmd_l_main( $start . '-' . ( $start + $incr ) ); } sub _cmd_l_plus { my ($new_start, $new_incr) = @_; # Don't reset start for 'l +nnn'. $start = $new_start if $new_start; # Increment for list. Use window size if not specified. # (Allows 'l +' to work.) $incr = $new_incr || ($window - 1); # Create a line range we'll understand, and recurse to do it. return _cmd_l_main( $start . '-' . ( $start + $incr ) ); } sub _cmd_l_calc_initial_end_and_i { my ($current_line, $start_match, $end_match) = @_; my $end = $end_match // $start_match // $max; # Clean up the end spec if needed. $end = $current_line if $end eq '.'; _minify_to_max(\$end); # Determine the loop start point. my $i = $start_match // 1; $i = $current_line if $i eq '.'; return ($end, $i); } sub _cmd_l_range { my ($current_line, $start_match, $end_match) = @_; my ($end, $i) = _cmd_l_calc_initial_end_and_i($current_line, $start_match, $end_match); # If we're running under a client editor, force it to show the lines. if ($client_editor) { print {$OUT} "$sub_twice$filename:$i:0\n"; $i = $end; } # We're doing it ourselves. We want to show the line and special # markers for: # - the current line in execution # - whether a line is breakable or not # - whether a line has a break or not # - whether a line has an action or not else { I_TO_END: for ( ; $i <= $end ; $i++ ) { # Check for breakpoints and actions. my ( $stop, $action ); if ($dbline{$i}) { ( $stop, $action ) = split( /\0/, $dbline{$i} ); } # ==> if this is the current line in execution, # : if it's breakable. my $arrow = ( $i == $current_line and $filename eq $filename_ini ) ? '==>' : ( $dbline[$i] + 0 ? ':' : ' ' ); # Add break and action indicators. $arrow .= 'b' if $stop; $arrow .= 'a' if $action; # Print the line. print {$OUT} "$i$arrow\t", $dbline[$i]; # Move on to the next line. Drop out on an interrupt. if ($signal) { $i++; last I_TO_END; } } ## end for (; $i <= $end ; $i++) # Line the prompt up; print a newline if the last line listed # didn't have a newline. if ($dbline[ $i - 1 ] !~ /\n\z/) { print {$OUT} "\n"; } } ## end else [ if ($client_editor) # Save the point we last listed to in case another relative 'l' # command is desired. Don't let it run off the end. $start = $i; _minify_to_max(\$start); return; } sub _cmd_l_main { my $spec = shift; # If the line is '$something', assume this is a scalar containing a # line number. # Set up for DB::eval() - evaluate in *user* context. if ( $spec =~ /\A(\$(?:[0-9]+|[^\W\d]\w*))\z/ ) { return _cmd_l_handle_var_name($spec); } # l name. Try to find a sub by that name. elsif ( ($subname) = $spec =~ /\A([\':A-Za-z_][\':\w]*(?:\[.*\])?)/s ) { return _cmd_l_handle_subname($subname); } # Bare 'l' command. elsif ( $spec !~ /\S/ ) { return _cmd_l_empty(); } # l [start]+number_of_lines elsif ( my ($new_start, $new_incr) = $spec =~ /\A(\d*)\+(\d*)\z/ ) { return _cmd_l_plus($new_start, $new_incr); } # l start-stop or l start,stop # Purposefully limited to ASCII; UTF-8 support would be nice sometime. elsif (my ($s, $e) = $spec =~ /\A(?:(\.|\d+)(?:[-,](\.|\d+))?)?\z/a ) { return _cmd_l_range($line, $s, $e); } # Protest at bizarre and incorrect specs. else { print {$OUT} "Invalid line specification '$spec'.\n"; } return; } ## end sub _cmd_l_main sub _DB__handle_l_command { my $self = shift; _cmd_l_main($self->cmd_args); next CMD; } # 't' is type. # 'm' is method. # 'v' is the value (i.e: method name or subroutine ref). # 's' is subroutine. my %cmd_lookup; BEGIN { %cmd_lookup = ( '-' => { t => 'm', v => '_handle_dash_command', }, '.' => { t => 's', v => \&_DB__handle_dot_command, }, '=' => { t => 'm', v => '_handle_equal_sign_command', }, 'H' => { t => 'm', v => '_handle_H_command', }, 'S' => { t => 'm', v => '_handle_S_command', }, 'T' => { t => 'm', v => '_handle_T_command', }, 'W' => { t => 'm', v => '_handle_W_command', }, 'c' => { t => 's', v => \&_DB__handle_c_command, }, 'f' => { t => 's', v => \&_DB__handle_f_command, }, 'i' => { t => 's', v => \&_DB__handle_i_command, }, 'l' => { t => 's', v => \&_DB__handle_l_command, }, 'm' => { t => 's', v => \&_DB__handle_m_command, }, 'n' => { t => 'm', v => '_handle_n_command', }, 'p' => { t => 'm', v => '_handle_p_command', }, 'q' => { t => 'm', v => '_handle_q_command', }, 'r' => { t => 'm', v => '_handle_r_command', }, 's' => { t => 'm', v => '_handle_s_command', }, 'save' => { t => 'm', v => '_handle_save_command', }, 'source' => { t => 'm', v => '_handle_source_command', }, 't' => { t => 'm', v => '_handle_t_command', }, 'w' => { t => 'm', v => '_handle_w_command', }, 'x' => { t => 'm', v => '_handle_x_command', }, 'y' => { t => 's', v => \&_DB__handle_y_command, }, (map { $_ => { t => 'm', v => '_handle_V_command_and_X_command', }, } ('X', 'V')), (map { $_ => { t => 'm', v => '_handle_enable_disable_commands', }, } qw(enable disable)), (map { $_ => { t => 's', v => \&_DB__handle_restart_and_rerun_commands, }, } qw(R rerun)), (map { $_ => {t => 'm', v => '_handle_cmd_wrapper_commands' }, } qw(a A b B e E h L M o O v w W)), ); }; sub DB { # lock the debugger and get the thread id for the prompt lock($DBGR); my $tid; my $position; my ($prefix, $after, $infix); my $pat; my $explicit_stop; my $piped; my $selected; if ($ENV{PERL5DB_THREADED}) { $tid = eval { "[".threads->tid."]" }; } my $cmd_verb; my $cmd_args; my $obj = DB::Obj->new( { position => \$position, prefix => \$prefix, after => \$after, explicit_stop => \$explicit_stop, infix => \$infix, cmd_args => \$cmd_args, cmd_verb => \$cmd_verb, pat => \$pat, piped => \$piped, selected => \$selected, }, ); $obj->_DB_on_init__initialize_globals(@_); # Preserve current values of $@, $!, $^E, $,, $/, $\, $^W. # The code being debugged may have altered them. DB::save(); # Since DB::DB gets called after every line, we can use caller() to # figure out where we last were executing. Sneaky, eh? This works because # caller is returning all the extra information when called from the # debugger. local ( $package, $filename, $line ) = caller; $filename_ini = $filename; # set up the context for DB::eval, so it can properly execute # code on behalf of the user. We add the package in so that the # code is eval'ed in the proper package (not in the debugger!). local $usercontext = _calc_usercontext($package); # Create an alias to the active file magical array to simplify # the code here. local (*dbline) = $main::{ '_<' . $filename }; # Last line in the program. $max = $#dbline; # The &-call is here to ascertain the mutability of @_. &_DB__determine_if_we_should_break; # Preserve the current stop-or-not, and see if any of the W # (watch expressions) has changed. my $was_signal = $signal; # If we have any watch expressions ... _DB__handle_watch_expressions($obj); =head2 C C is a function that can be defined by the user; it is a function which will be run on each entry to C; it gets the current package, filename, and line as its parameters. The watchfunction can do anything it likes; it is executing in the debugger's context, so it has access to all of the debugger's internal data structures and functions. C can control the debugger's actions. Any of the following will cause the debugger to return control to the user's program after C executes: =over 4 =item * Returning a false value from the C itself. =item * Altering C<$single> to a false value. =item * Altering C<$signal> to a false value. =item * Turning off the C<4> bit in C<$trace> (this also disables the check for C. This can be done with $trace &= ~4; =back =cut # If there's a user-defined DB::watchfunction, call it with the # current package, filename, and line. The function executes in # the DB:: package. if ( $trace & 4 ) { # User-installed watch return if watchfunction( $package, $filename, $line ) and not $single and not $was_signal and not( $trace & ~4 ); } ## end if ($trace & 4) # Pick up any alteration to $signal in the watchfunction, and # turn off the signal now. $was_signal = $signal; $signal = 0; =head2 GETTING READY TO EXECUTE COMMANDS The debugger decides to take control if single-step mode is on, the C command was entered, or the user generated a signal. If the program has fallen off the end, we set things up so that entering further commands won't cause trouble, and we say that the program is over. =cut # Make sure that we always print if asked for explicitly regardless # of $trace_to_depth . $explicit_stop = ($single || $was_signal); # Check to see if we should grab control ($single true, # trace set appropriately, or we got a signal). if ( $explicit_stop || ( $trace & 1 ) ) { $obj->_DB__grab_control(@_); } ## end if ($single || ($trace... =pod If there's an action to be executed for the line we stopped at, execute it. If there are any preprompt actions, execute those as well. =cut # If there's an action, do it now. if ($action) { $evalarg = $action; # The &-call is here to ascertain the mutability of @_. &DB::eval; } undef $action; # Are we nested another level (e.g., did we evaluate a function # that had a breakpoint in it at the debugger prompt)? if ( $single || $was_signal ) { # Yes, go down a level. local $level = $level + 1; # Do any pre-prompt actions. foreach $evalarg (@$pre) { # The &-call is here to ascertain the mutability of @_. &DB::eval; } # Complain about too much recursion if we passed the limit. if ($single & 4) { print $OUT $stack_depth . " levels deep in subroutine calls!\n"; } # The line we're currently on. Set $incr to -1 to stay here # until we get a command that tells us to advance. $start = $line; $incr = -1; # for backward motion. # Tack preprompt debugger actions ahead of any actual input. @typeahead = ( @$pretype, @typeahead ); =head2 WHERE ARE WE? XXX Relocate this section? The debugger normally shows the line corresponding to the current line of execution. Sometimes, though, we want to see the next line, or to move elsewhere in the file. This is done via the C<$incr>, C<$start>, and C<$max> variables. C<$incr> controls by how many lines the I line should move forward after a command is executed. If set to -1, this indicates that the I line shouldn't change. C<$start> is the I line. It is used for things like knowing where to move forwards or backwards from when doing an C or C<-> command. C<$max> tells the debugger where the last line of the current file is. It's used to terminate loops most often. =head2 THE COMMAND LOOP Most of C is actually a command parsing and dispatch loop. It comes in two parts: =over 4 =item * The outer part of the loop, starting at the C label. This loop reads a command and then executes it. =item * The inner part of the loop, starting at the C label. This part is wholly contained inside the C block and only executes a command. Used to handle commands running inside a pager. =back So why have two labels to restart the loop? Because sometimes, it's easier to have a command I another command and then re-execute the loop to do the new command. This is faster, but perhaps a bit more convoluted. =cut # The big command dispatch loop. It keeps running until the # user yields up control again. # # If we have a terminal for input, and we get something back # from readline(), keep on processing. CMD: while (_DB__read_next_cmd($tid)) { share($cmd); # ... try to execute the input as debugger commands. # Don't stop running. $single = 0; # No signal is active. $signal = 0; # Handle continued commands (ending with \): if ($cmd =~ s/\\\z/\n/) { $cmd .= DB::readline(" cont: "); redo CMD; } =head4 The null command A newline entered by itself means I. We grab the command out of C<$laststep> (where it was recorded previously), and copy it back into C<$cmd> to be executed below. If there wasn't any previous command, we'll do nothing below (no command will match). If there was, we also save it in the command history and fall through to allow the command parsing to pick it up. =cut # Empty input means repeat the last command. if ($cmd eq '') { $cmd = $laststep; } chomp($cmd); # get rid of the annoying extra newline if (length($cmd) >= option_val('HistItemMinLength', 2)) { push( @hist, $cmd ); } push( @truehist, $cmd ); share(@hist); share(@truehist); # This is a restart point for commands that didn't arrive # via direct user input. It allows us to 'redo PIPE' to # re-execute command processing without reading a new command. PIPE: { _DB__trim_command_and_return_first_component($obj); =head3 COMMAND ALIASES The debugger can create aliases for commands (these are stored in the C<%alias> hash). Before a command is executed, the command loop looks it up in the alias hash and substitutes the contents of the alias for the command, completely replacing it. =cut # See if there's an alias for the command, and set it up if so. if ( $alias{$cmd_verb} ) { # Squelch signal handling; we want to keep control here # if something goes loco during the alias eval. local $SIG{__DIE__}; local $SIG{__WARN__}; # This is a command, so we eval it in the DEBUGGER's # scope! Otherwise, we can't see the special debugger # variables, or get to the debugger's subs. (Well, we # _could_, but why make it even more complicated?) eval "\$cmd =~ $alias{$cmd_verb}"; if ($@) { local $\ = ''; print $OUT "Couldn't evaluate '$cmd_verb' alias: $@"; next CMD; } _DB__trim_command_and_return_first_component($obj); } ## end if ($alias{$cmd_verb}) =head3 MAIN-LINE COMMANDS All of these commands work up to and after the program being debugged has terminated. =head4 C - quit Quit the debugger. This entails setting the C<$fall_off_end> flag, so we don't try to execute further, cleaning any restart-related stuff out of the environment, and executing with the last value of C<$?>. =cut # All of these commands were remapped in perl 5.8.0; # we send them off to the secondary dispatcher (see below). $obj->_handle_special_char_cmd_wrapper_commands; _DB__trim_command_and_return_first_component($obj); if (my $cmd_rec = $cmd_lookup{$cmd_verb}) { my $type = $cmd_rec->{t}; my $val = $cmd_rec->{v}; if ($type eq 'm') { $obj->$val(); } elsif ($type eq 's') { $val->($obj); } } =head4 C - trace [n] Turn tracing on or off. Inverts the appropriate bit in C<$trace> (q.v.). If level is specified, set C<$trace_to_depth>. =head4 C - list subroutines matching/not matching a pattern Walks through C<%sub>, checking to see whether or not to print the name. =head4 C - list variables in current package Since the C command actually processes this, just change this to the appropriate C command and fall through. =head4 C - list variables Uses C to dump out the current values for selected variables. =head4 C - evaluate and print an expression Hands the expression off to C, setting it up to print the value via C instead of just printing it directly. =head4 C - print methods Just uses C to determine what methods are available. =head4 C - switch files Switch to a different filename. =head4 C<.> - return to last-executed line We set C<$incr> to -1 to indicate that the debugger shouldn't move ahead, and then we look up the line in the magical C<%dbline> hash. =head4 C<-> - back one window We change C<$start> to be one window back; if we go back past the first line, we set it to be the first line. We set C<$incr> to put us back at the currently-executing line, and then put a S> (list one window from C<$start>) in C<$cmd> to be executed later. =head3 PRE-580 COMMANDS VS. NEW COMMANDS: C, EE, E<0x7B>, E<0x7B>E<0x7B>> In Perl 5.8.0, a realignment of the commands was done to fix up a number of problems, most notably that the default case of several commands destroying the user's work in setting watchpoints, actions, etc. We wanted, however, to retain the old commands for those who were used to using them or who preferred them. At this point, we check for the new commands and call C to deal with them instead of processing them in-line. =head4 C - List lexicals in higher scope Uses C to find the lexicals supplied as arguments in a scope above the current one and then displays them using F. =head3 COMMANDS NOT WORKING AFTER PROGRAM ENDS All of the commands below this point don't work after the program being debugged has ended. All of them check to see if the program has ended; this allows the commands to be relocated without worrying about a 'line of demarcation' above which commands can be entered anytime, and below which they can't. =head4 C - single step, but don't trace down into subs Done by setting C<$single> to 2, which forces subs to execute straight through when entered (see C in L). We also save the C command in C<$laststep>, so a null command knows what to re-execute. =head4 C - single-step, entering subs Sets C<$single> to 1, which causes C to continue tracing inside subs. Also saves C as C<$lastcmd>. =head4 C - run continuously, setting an optional breakpoint Most of the code for this command is taken up with locating the optional breakpoint, which is either a subroutine name or a line number. We set the appropriate one-time-break in C<@dbline> and then turn off single-stepping in this and all call levels above this one. =head4 C - return from a subroutine For C to work properly, the debugger has to stop execution again immediately after the return is executed. This is done by forcing single-stepping to be on in the call level above the current one. If we are printing return values when a C is executed, set C<$doret> appropriately, and force us out of the command loop. =head4 C - stack trace Just calls C. =head4 C - List window around current line Just calls C. =head4 C - watch-expression processing Just calls C. =head4 C - search forward for a string in the source We take the argument and treat it as a pattern. If it turns out to be a bad one, we return the error we got from trying to C it and exit. If not, we create some code to do the search and C it so it can't mess us up. =cut _DB__handle_forward_slash_command($obj); =head4 C - search backward for a string in the source Same as for C, except the loop runs backwards. =cut _DB__handle_question_mark_command($obj); =head4 C<$rc> - Recall command Manages the commands in C<@hist> (which is created if C reports that the terminal supports history). It finds the command required, puts it into C<$cmd>, and redoes the loop to execute it. =cut # $rc - recall command. $obj->_handle_rc_recall_command; =head4 C<$sh$sh> - C command Calls the C<_db_system()> to handle the command. This keeps the C and C from getting messed up. =cut $obj->_handle_sh_command; =head4 C<$rc I $rc> - Search command history Another command to manipulate C<@hist>: this one searches it with a pattern. If a command is found, it is placed in C<$cmd> and executed via C. =cut $obj->_handle_rc_search_history_command; =head4 C<$sh> - Invoke a shell Uses C<_db_system()> to invoke a shell. =cut =head4 C<$sh I> - Force execution of a command in a shell Like the above, but the command is passed to the shell. Again, we use C<_db_system()> to avoid problems with C and C. =head4 C - display commands in history Prints the contents of C<@hist> (if any). =head4 C - look up documentation Just calls C to print the appropriate document. =cut $obj->_handle_doc_command; =head4 C

- print Builds a C expression in the C<$cmd>; this will get executed at the bottom of the loop. =head4 C<=> - define command alias Manipulates C<%alias> to add or list command aliases. =head4 C - read commands from a file Opens a lexical filehandle and stacks it on C<@cmdfhs>; C will pick it up. =head4 C C - enable or disable breakpoints This enables or disables breakpoints. =head4 C - send current history to a file Takes the complete history, (not the shrunken version you see with C), and saves it to the given filename, so it can be replayed using C. Note that all C<^(save|source)>'s are commented out with a view to minimise recursion. =head4 C - restart Restart the debugger session. =head4 C - rerun the current session Return to any given position in the B-history list =head4 C<|, ||> - pipe output through the pager For C<|>, we save C (the debugger's output filehandle) and C (the program's standard output). For C<||>, we only save C. We open a pipe to the pager (restoring the output filehandles if this fails). If this is the C<|> command, we also set up a C handler which will simply set C<$signal>, sending us back into the debugger. We then trim off the pipe symbols and C the command loop at the C label, causing us to evaluate the command in C<$cmd> without reading another. =cut # || - run command in the pager, with output to DB::OUT. _DB__handle_run_command_in_pager_command($obj); =head3 END OF COMMAND PARSING Anything left in C<$cmd> at this point is a Perl expression that we want to evaluate. We'll always evaluate in the user's context, and fully qualify any variables we might want to address in the C package. =cut } # PIPE: # trace an expression $cmd =~ s/^t\s/\$DB::trace |= 1;\n/; # Make sure the flag that says "the debugger's running" is # still on, to make sure we get control again. $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd"; # Run *our* eval that executes in the caller's context. # The &-call is here to ascertain the mutability of @_. &DB::eval; # Turn off the one-time-dump stuff now. if ($onetimeDump) { $onetimeDump = undef; $onetimedumpDepth = undef; } elsif ( $term_pid == $$ ) { eval { # May run under miniperl, when not available... STDOUT->flush(); STDERR->flush(); }; # XXX If this is the master pid, print a newline. print {$OUT} "\n"; } } ## end while (($term || &setterm... =head3 POST-COMMAND PROCESSING After each command, we check to see if the command output was piped anywhere. If so, we go through the necessary code to unhook the pipe and go back to our standard filehandles for input and output. =cut continue { # CMD: _DB__at_end_of_every_command($obj); } # CMD: =head3 COMMAND LOOP TERMINATION When commands have finished executing, we come here. If the user closed the input filehandle, we turn on C<$fall_off_end> to emulate a C command. We evaluate any post-prompt items. We restore C<$@>, C<$!>, C<$^E>, C<$,>, C<$/>, C<$\>, and C<$^W>, and return a null list as expected by the Perl interpreter. The interpreter will then execute the next line and then return control to us again. =cut # No more commands? Quit. unless (defined $cmd) { DB::Obj::_do_quit(); } # Evaluate post-prompt commands. foreach $evalarg (@$post) { # The &-call is here to ascertain the mutability of @_. &DB::eval; } } # if ($single || $signal) # Put the user's globals back where you found them. ( $@, $!, $^E, $,, $/, $\, $^W ) = @saved; (); } ## end sub DB # Because DB::Obj is used above, # # my $obj = DB::Obj->new( # # The following package declaration must come before that, # or else runtime errors will occur with # # PERLDB_OPTS="autotrace nonstop" # # ( rt#116771 ) BEGIN { package DB::Obj; sub new { my $class = shift; my $self = bless {}, $class; $self->_init(@_); return $self; } sub _init { my ($self, $args) = @_; %{$self} = (%$self, %$args); return; } { no strict 'refs'; foreach my $slot_name (qw( after explicit_stop infix pat piped position prefix selected cmd_verb cmd_args )) { my $slot = $slot_name; *{$slot} = sub { my $self = shift; if (@_) { ${ $self->{$slot} } = shift; } return ${ $self->{$slot} }; }; *{"append_to_$slot"} = sub { my $self = shift; my $s = shift; return $self->$slot($self->$slot . $s); }; } } sub _DB_on_init__initialize_globals { my $self = shift; # Check for whether we should be running continuously or not. # _After_ the perl program is compiled, $single is set to 1: if ( $single and not $second_time++ ) { # Options say run non-stop. Run until we get an interrupt. if ($runnonstop) { # Disable until signal # If there's any call stack in place, turn off single # stepping into subs throughout the stack. for my $i (0 .. $stack_depth) { $stack[ $i ] &= ~1; } # And we are now no longer in single-step mode. $single = 0; # If we simply returned at this point, we wouldn't get # the trace info. Fall on through. # return; } ## end if ($runnonstop) elsif ($ImmediateStop) { # We are supposed to stop here; XXX probably a break. $ImmediateStop = 0; # We've processed it; turn it off $signal = 1; # Simulate an interrupt to force # us into the command loop } } ## end if ($single and not $second_time... # If we're in single-step mode, or an interrupt (real or fake) # has occurred, turn off non-stop mode. $runnonstop = 0 if $single or $signal; return; } sub _my_print_lineinfo { my ($self, $i, $incr_pos) = @_; if ($frame) { # Print it indented if tracing is on. DB::print_lineinfo( ' ' x $stack_depth, "$i:\t$DB::dbline[$i]" . $self->after ); } else { DB::depth_print_lineinfo($self->explicit_stop, $incr_pos); } } sub _curr_line { return $DB::dbline[$line]; } sub _is_full { my ($self, $letter) = @_; return ($DB::cmd eq $letter); } sub _DB__grab_control { my $self = shift; # Yes, grab control. if ($client_editor) { # Tell the editor to update its position. $self->position("$sub_twice${DB::filename}:$line:0\n"); DB::print_lineinfo($self->position()); } =pod Special check: if we're in package C, we've gone through the C block at least once. We set up everything so that we can continue to enter commands and have a valid context to be in. =cut elsif ( $DB::package eq 'DB::fake' ) { # Fallen off the end already. if (!$DB::term) { DB::setterm(); } DB::print_help(< to quit or B to restart, use B I to avoid stopping after program termination, S>, S> or S> to get additional info. EOP $DB::package = 'main'; $DB::usercontext = DB::_calc_usercontext($DB::package); } ## end elsif ($package eq 'DB::fake') =pod If the program hasn't finished executing, we scan forward to the next executable line, print that out, build the prompt from the file and line number information, and print that. =cut else { # Still somewhere in the midst of execution. Set up the # debugger prompt. $DB::sub =~ s/\'/::/; # Swap Perl 4 package separators (') to # Perl 5 ones (sorry, we don't print Klingon #module names) $self->prefix($DB::sub =~ /::/ ? "" : ($DB::package . '::')); $self->append_to_prefix( "$DB::sub(${DB::filename}:" ); $self->after( $self->_curr_line =~ /\n$/ ? '' : "\n" ); # Break up the prompt if it's really long. if ( length($self->prefix()) > 30 ) { $self->position($self->prefix . "$line):\n$line:\t" . $self->_curr_line . $self->after); $self->prefix(""); $self->infix(":\t"); } else { $self->infix("):\t"); $self->position( $self->prefix . $line. $self->infix . $self->_curr_line . $self->after ); } # Print current line info, indenting if necessary. $self->_my_print_lineinfo($line, $self->position); my $i; my $line_i = sub { return $DB::dbline[$i]; }; # Scan forward, stopping at either the end or the next # unbreakable line. for ( $i = $line + 1 ; $i <= $DB::max && $line_i->() == 0 ; ++$i ) { #{ vi # Drop out on null statements, block closers, and comments. last if $line_i->() =~ /^\s*[\;\}\#\n]/; # Drop out if the user interrupted us. last if $signal; # Append a newline if the line doesn't have one. Can happen # in eval'ed text, for instance. $self->after( $line_i->() =~ /\n$/ ? '' : "\n" ); # Next executable line. my $incr_pos = $self->prefix . $i . $self->infix . $line_i->() . $self->after; $self->append_to_position($incr_pos); $self->_my_print_lineinfo($i, $incr_pos); } ## end for ($i = $line + 1 ; $i... } ## end else [ if ($client_editor) return; } sub _handle_t_command { my $self = shift; my $levels = $self->cmd_args(); if ((!length($levels)) or ($levels !~ /\D/)) { $trace ^= 1; local $\ = ''; $DB::trace_to_depth = $levels ? $stack_depth + $levels : 1E9; print {$OUT} "Trace = " . ( ( $trace & 1 ) ? ( $levels ? "on (to level $DB::trace_to_depth)" : "on" ) : "off" ) . "\n"; next CMD; } return; } sub _handle_S_command { my $self = shift; if (my ($print_all_subs, $should_reverse, $Spatt) = $self->cmd_args =~ /\A((!)?(.+))?\z/) { # $Spatt is the pattern (if any) to use. # Reverse scan? my $Srev = defined $should_reverse; # No args - print all subs. my $Snocheck = !defined $print_all_subs; # Need to make these sane here. local $\ = ''; local $, = ''; # Search through the debugger's magical hash of subs. # If $nocheck is true, just print the sub name. # Otherwise, check it against the pattern. We then use # the XOR trick to reverse the condition as required. foreach $subname ( sort( keys %sub ) ) { if ( $Snocheck or $Srev ^ ( $subname =~ /$Spatt/ ) ) { print $OUT $subname, "\n"; } } next CMD; } return; } sub _handle_V_command_and_X_command { my $self = shift; $DB::cmd =~ s/^X\b/V $DB::package/; # Bare V commands get the currently-being-debugged package # added. if ($self->_is_full('V')) { $DB::cmd = "V $DB::package"; } # V - show variables in package. if (my ($new_packname, $new_vars_str) = $DB::cmd =~ /\AV\b\s*(\S+)\s*(.*)/) { # Save the currently selected filehandle and # force output to debugger's filehandle (dumpvar # just does "print" for output). my $savout = select($OUT); # Grab package name and variables to dump. $packname = $new_packname; my @vars = split( ' ', $new_vars_str ); # If main::dumpvar isn't here, get it. do 'dumpvar.pl' || die $@ unless defined &main::dumpvar; if ( defined &main::dumpvar ) { # We got it. Turn off subroutine entry/exit messages # for the moment, along with return values. local $frame = 0; local $doret = -2; # must detect sigpipe failures - not catching # then will cause the debugger to die. eval { main::dumpvar( $packname, defined $option{dumpDepth} ? $option{dumpDepth} : -1, # assume -1 unless specified @vars ); }; # The die doesn't need to include the $@, because # it will automatically get propagated for us. if ($@) { die unless $@ =~ /dumpvar print failed/; } } ## end if (defined &main::dumpvar) else { # Couldn't load dumpvar. print $OUT "dumpvar.pl not available.\n"; } # Restore the output filehandle, and go round again. select($savout); next CMD; } return; } sub _handle_dash_command { my $self = shift; if ($self->_is_full('-')) { # back up by a window; go to 1 if back too far. $start -= $incr + $window + 1; $start = 1 if $start <= 0; $incr = $window - 1; # Generate and execute a "l +" command (handled below). $DB::cmd = 'l ' . ($start) . '+'; redo CMD; } return; } sub _n_or_s_commands_generic { my ($self, $new_val) = @_; # n - next next CMD if DB::_DB__is_finished(); # Single step, but don't enter subs. $single = $new_val; # Save for empty command (repeat last). $laststep = $DB::cmd; last CMD; } sub _n_or_s { my ($self, $letter, $new_val) = @_; if ($self->_is_full($letter)) { $self->_n_or_s_commands_generic($new_val); } else { $self->_n_or_s_and_arg_commands_generic($letter, $new_val); } return; } sub _handle_n_command { my $self = shift; return $self->_n_or_s('n', 2); } sub _handle_s_command { my $self = shift; return $self->_n_or_s('s', 1); } sub _handle_r_command { my $self = shift; # r - return from the current subroutine. if ($self->_is_full('r')) { # Can't do anything if the program's over. next CMD if DB::_DB__is_finished(); # Turn on stack trace. $stack[$stack_depth] |= 1; # Print return value unless the stack is empty. $doret = $option{PrintRet} ? $stack_depth - 1 : -2; last CMD; } return; } sub _handle_T_command { my $self = shift; if ($self->_is_full('T')) { DB::print_trace( $OUT, 1 ); # skip DB next CMD; } return; } sub _handle_w_command { my $self = shift; DB::cmd_w( 'w', $self->cmd_args() ); next CMD; return; } sub _handle_W_command { my $self = shift; if (my $arg = $self->cmd_args) { DB::cmd_W( 'W', $arg ); next CMD; } return; } sub _handle_rc_recall_command { my $self = shift; # $rc - recall command. if (my ($minus, $arg) = $DB::cmd =~ m#\A$rc+\s*(-)?(\d+)?\z#) { # No arguments, take one thing off history. pop(@hist) if length($DB::cmd) > 1; # Relative (- found)? # Y - index back from most recent (by 1 if bare minus) # N - go to that particular command slot or the last # thing if nothing following. $self->cmd_verb( scalar($minus ? ( $#hist - ( $arg || 1 ) ) : ( $arg || $#hist )) ); # Pick out the command desired. $DB::cmd = $hist[$self->cmd_verb]; # Print the command to be executed and restart the loop # with that command in the buffer. print {$OUT} $DB::cmd, "\n"; redo CMD; } return; } sub _handle_rc_search_history_command { my $self = shift; # $rc pattern $rc - find a command in the history. if (my ($arg) = $DB::cmd =~ /\A$rc([^$rc].*)\z/) { # Create the pattern to use. my $pat = "^$arg"; $self->pat($pat); # Toss off last entry if length is >1 (and it always is). pop(@hist) if length($DB::cmd) > 1; my $i; # Look backward through the history. SEARCH_HIST: for ( $i = $#hist ; $i ; --$i ) { # Stop if we find it. last SEARCH_HIST if $hist[$i] =~ /$pat/; } if ( !$i ) { # Never found it. print $OUT "No such command!\n\n"; next CMD; } # Found it. Put it in the buffer, print it, and process it. $DB::cmd = $hist[$i]; print $OUT $DB::cmd, "\n"; redo CMD; } return; } sub _handle_H_command { my $self = shift; if ($self->cmd_args =~ m#\A\*#) { @hist = @truehist = (); print $OUT "History cleansed\n"; next CMD; } if (my ($num) = $self->cmd_args =~ /\A(?:-(\d+))?/) { # Anything other than negative numbers is ignored by # the (incorrect) pattern, so this test does nothing. $end = $num ? ( $#hist - $num ) : 0; # Set to the minimum if less than zero. $hist = 0 if $hist < 0; # Start at the end of the array. # Stay in while we're still above the ending value. # Tick back by one each time around the loop. my $i; for ( $i = $#hist ; $i > $end ; $i-- ) { print $OUT "$i: ", $hist[$i], "\n"; } next CMD; } return; } sub _handle_doc_command { my $self = shift; # man, perldoc, doc - show manual pages. if (my ($man_page) = $DB::cmd =~ /\A(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?\z/) { DB::runman($man_page); next CMD; } return; } sub _handle_p_command { my $self = shift; my $print_cmd = 'print {$DB::OUT} '; # p - print (no args): print $_. if ($self->_is_full('p')) { $DB::cmd = $print_cmd . '$_'; } else { # p - print the given expression. $DB::cmd =~ s/\Ap\b/$print_cmd /; } return; } sub _handle_equal_sign_command { my $self = shift; if ($DB::cmd =~ s/\A=\s*//) { my @keys; if ( length $DB::cmd == 0 ) { # No args, get current aliases. @keys = sort keys %alias; } elsif ( my ( $k, $v ) = ( $DB::cmd =~ /^(\S+)\s+(\S.*)/ ) ) { # Creating a new alias. $k is alias name, $v is # alias value. # can't use $_ or kill //g state for my $x ( $k, $v ) { # Escape "alarm" characters. $x =~ s/\a/\\a/g; } # Substitute key for value, using alarm chars # as separators (which is why we escaped them in # the command). $alias{$k} = "s\a$k\a$v\a"; # Turn off standard warn and die behavior. local $SIG{__DIE__}; local $SIG{__WARN__}; # Is it valid Perl? unless ( eval "sub { s\a$k\a$v\a }; 1" ) { # Nope. Bad alias. Say so and get out. print $OUT "Can't alias $k to $v: $@\n"; delete $alias{$k}; next CMD; } # We'll only list the new one. @keys = ($k); } ## end elsif (my ($k, $v) = ($DB::cmd... # The argument is the alias to list. else { @keys = ($DB::cmd); } # List aliases. for my $k (@keys) { # Messy metaquoting: Trim the substitution code off. # We use control-G as the delimiter because it's not # likely to appear in the alias. if ( ( my $v = $alias{$k} ) =~ s