| Debugging a Program With dbx |
Event Management
Event management refers to the capability of
dbxto perform actions when events take place in the program being debugged.This chapter is organized into the following sections:
- Event Handlers
- Creating Event Handlers
- Manipulating Event Handlers
- Using Event Counters
- Setting Event Specifications
- Parsing and Ambiguity
- Using Predefined Variables
- Setting Event Handler Examples
Event Handlers
Event management is based on the concept of a handler. The name comes from an analogy with hardware interrupt handlers. Each event management command typically creates a handler, which consists of an event specification and a series of side-effect actions. (See Setting Event Specifications.) The event specification specifies the event that will trigger the handler.
When the event occurs and the handler is triggered, the handler evaluates the event according to any modifiers included in the event specification. (See Event Specification Modifiers.) If the event meets the conditions imposed by the modifiers, the handler's side-effect actions are performed (that is, the handler "fires").
An example of the association of a program event with a
dbxaction is setting a breakpoint on a particular line.The most generic form of creating a handler is by using the
whencommand.
whenevent-specification{action; ... }Examples in this chapter show how you can write a command (like
stop,step, orignore) in terms ofwhen. These examples are meant to illustrate the flexibility ofwhenand the underlying handler mechanism, but they are not always exact replacements.Creating Event Handlers
Use the commands
when,stop, andtraceto create event handlers.
stopis shorthand for a commonwhenidiom.
whenevent-specification{ stop -update; whereami; }An event-specification is used by the event management commands
stop,when, andtraceto specify an event of interest. (see Setting Event Specifications).Most of the
tracecommands can be handcrafted using thewhencommand,kshfunctionality, and event variables. This is especially useful if you want stylized tracing output.For detailed information, see "when Command," "stop Command," and "trace Command" in the Using dbx Commands section of the Sun WorkShop online help.
Every command returns a number known as a handler id (hid). You can access this number using the predefined variable
$newhandlerid.An attempt has been made to make the
stopandwhencommands conform to the handler model. However, backward compatibility with previousdbxreleases forces some deviations.For example, the following samples from an earlier
dbxrelease are equivalent.
whencond bodywhen step -ifcond bodywhencondinfuncbodywhen next -ifcond-infuncbody
These samples illustrate that cond is not a pure event; there is no internal handler for conditions.
Manipulating Event Handlers
You can use the following commands to manipulate event handlers. For more information on each command, see the cited topic in the Using dbx Commands section of the Sun WorkShop online help.
status- lists handlers (see "status Command").delete- deletes all handlers including temporary handlers (see "delete Command").clear- deletes handlers based on breakpoint position (see "clear Command").handler -enable- enables handlers (see "handler Command").handler -disable- disables handlers.cancel- cancels signals and lets the process continue (see "cancel Command").Using Event Counters
An event handler has a trip counter, which has a count limit. Whenever the specified event occurs, the counter is incremented. The action associated with the handler is performed only if the count reaches the limit, at which point the counter is automatically reset to 0. The default limit is 1. Whenever a process is rerun, all event counters are reset.
You can set the count limit using the
-countmodifier with astop,when, ortracecommand (see -count n -count infinity). Otherwise, use thehandlercommand to individually manipulate event handlers:.
handler [ -count | -reset ] hidnew-countnew-count-limitSetting Event Specifications
Event specifications are used by the
stop,when, andtracecommands to denote event types and parameters. The format consists of a keyword representing the event type and optional parameters. For more information, see "Event Specification" in the Using dbx Commands section of the Sun WorkShop online help.Breakpoint Event Specifications
The following are event specifications for breakpoint events.
infunctionThe function has been entered, and the first line is about to be executed. If the
-instrmodifier is used (see -instr), it is the first instruction of the function about to be executed. The func specification can take a formal parameter signature to help with overloaded function names or template instance specification. For example:
stop in mumble(int, float, struct Node *)
Note Do not confuseinfunction with the-infunction modifier.
at [filename:]linenoThe designated line is about to be executed. If you specify filename, then the designated line in the specified file is about to be executed. The file name can be the name of a source file or an object file. Although quotation marks are not required, they may be necessary if the file name contains special characters. If the designated line is in template code, a breakpoint is placed on all instances of that template.
infunctionfunctionEquivalent to
infunction for all overloaded functions named function or all template instantiations thereof.
inmemberfunctioninmethodfunctionEquivalent to
infunction for the member function named function for every class.
inclassclassnameEquivalent to
infunction for all member functions that are members of classname.
inobjectobject-expressionA member function called on the specific object at the address denoted by object-expression has been called.
Watchpoint Event Specifications
The following are event specifications for watchpoint events. For more information, see "Watchpoint Specification" in the Using dbx Commands section of the Sun WorkShop online help.
accessmode addr-expression [, byte-size-expression]The memory specified by addr-expression has been accessed.
mode specifies that the memory was accessed. It can be composed of one or all of the letters:
rThe memory has been read. wThe memory has been written to. xThe memory has been executed.
mode can also contain either of the following:
aStops the process after the access (default). bStops the process before the access.
In both cases the program counter will point at the offending instruction. The "before" and "after" refer to the side effect.
address-expression is any expression that can be evaluated to produce an address. If you give a symbolic expression, the size of the region to be watched is automatically deduced; you can override it by specifying byte-size-expression. You can also use nonsymbolic, typeless address expressions; in which case, the size is mandatory. For example:
stop access 0x5678, sizeof(Complex)The
accesscommand has the limitation that no two matched regions may overlap.
Note Theaccessevent specification is a replacement for themodifyevent specification. While both syntaxes work on Solaris 2.6, Solaris 7, and Solaris 8, on all of these operating environments except Solaris 2.6,accesssuffers the same limitations asmodifyand accepts only a mode ofwa.
changevariableThe value of variable has changed.
condcondition-expressionThe condition denoted by cond-expression evaluates to true. You can specify any expression for cond-expression, but it must evaluate to an integral type.
modifyaddress-expression[,byte-size-expression]The specified address range has been modified. This is the older watchpoint facility.
address-expression is any expression that can be evaluated to produce an address. If you give a symbolic expression, the size of the region to be watched is automatically deduced; you can override it by specifying byte-size-expression. You can also use nonsymbolic, typeless address expressions; in which case, the size is mandatory. For example:
stop modify 0x5678, sizeof(Complex)
Note Multithreaded applications are prone to deadlock so mt watchpoints are nominally disallowed. They can be turned on by setting thedbxenvironment variablemt_watchpoints.
System Event Specifications
The following are event specifications for system events.
dlopen [lib-path] | dlclose [lib-path]These events occur after a
dlopen() or adlclose() call succeeds. Adlopen() ordlclose() call can cause more than one library to be loaded. The list of these libraries is always available in the predefined variable$dllist. The first word in$dllistis a "+" or a "-", indicating whether the list of libraries is being added or deleted.lib-path is the name of a shared library. If it is specified, the event occurs only if the given library was loaded or unloaded. In that case,
$dlobjcontains the name of the library.$dllistis still available.If lib-path begins with a
/, a full string match is performed. Otherwise, only the tails of the paths are compared.If lib-path is not specified, then the events always occur whenever there is any
dl-activity. In this case,$dlobjis empty but$dllistis valid.
faultfaultThe
faultevent occurs when the specified fault is encountered. The faults are architecture-dependent. The following set of faults known todbxis defined in theproc(4) man page.
Note BPT,TRACE, andBOUNDSare used bydbxto implement breakpoints, single-stepping, and watchpoints. Handling them might interfere with howdbxworks.
These faults are taken from /
sys/fault.h. fault can be any of those listed above, in uppercase or lowercase, with or without theFLT- prefix, or the actual numerical code.
lwp_exitThe
lwp_exitevent occurs whenlwphas been exited.$lwpcontains the id of the exited LWP (lightweight process).
sigsigThe
sigsig event occurs when the signal is first delivered to the program being debugged. sig can be either a decimal number or the signal name in uppercase or lowercase; the prefix is optional. This is completely independent of thecatch/ignorecommands, although thecatchcommand can be implemented as follows:
function simple_catch {when sig $1 {stop;echo Stopped due to $sigstr $sigwhereami}}
Note When thesigevent is received, the process has not seen it yet. Only if you continue the process with the specified signal is the signal forwarded to it.
sigsigsub-codeWhen the specified signal with the specified sub-code is first delivered to the child, the
sigsig sub-code event occurs. As with signals, you can type the sub-code as a decimal number, in uppercase or lowercase; the prefix is optional.
sysincode|nameThe specified system call has just been initiated, and the process has entered kernel mode.
The concept of system call supported by
dbxis that provided by traps into the kernel as enumerated in/usr/include/sys/syscall.h.This is not the same as the ABI notion of system calls. Some ABI system calls are partially implemented in user mode and use non-ABI kernel traps. However, most of the generic system calls (the main exception being signal handling) are the same between
syscall.hand the ABI.
sysoutcode|nameThe specified system call is finished, and the process is about to return to user mode.
sysin|sysoutWithout arguments, all system calls are traced. Certain
dbxfeatures, for example, themodifyevent and runtime checking, cause the child to execute system calls for its own purposes and show up if traced.Execution Progress Event Specifications
The following are event specifications for events pertaining to execution progress.
nextThe
nextevent is similar to thestepevent except that functions are not stepped into.
returnsThe
returnsevent is a breakpoint at the return point of the current visited function. The visited function is used so that you can use thereturnsevent specification after giving a number ofstepupcommands. Thereturnsevent is always-tempand can only be created in the presence of a live process.
returnsfuncThe
returnsfunc event executes each time the given function returns to its call site. This is not a temporary event. The return value is not provided, but you can find integral return values by accessing the following registers:
Sparc $o0Intel $eax
The event is another way of saying:
when in func { stop returns; }
stepThe
stepevent occurs when the first instruction of a source line is executed. For example, you can get simple tracing with:
when step { echo $lineno: $line; }When enabling a step event, you instruct
dbxto single-step automatically next time thecontcommand is used. You can implement thestepcommand as follows:
alias step="when step -temp { whereami; stop; }; cont"Other Event Specifications
The following are event specifications for other types of events.
attach
dbxhas successfully attached to a process.
detachdbx has successfully detached from the program being debugged.
lastritesThe process being debugged is about to expire. This can happen for the following reasons:
- The
_exit(2) system call has been called. (This happens either through an explicit call or whenmain() returns.)- A terminating signal is about to be delivered.
- The process is being killed by the
killcommand.
proc_goneThe
proc_goneevent occurs whendbxis no longer associated with a debugged process. The predefined variable$reasonmay besignal,exit,kill, ordetach.
prog_newThe
prog_newevent occurs when a new program has been loaded as a result offollowexec.
Note Handlers for this event are always permanent.
stopThe process has stopped. The
stopevent occurs whenever the process stops such that the user receives a prompt, particularly in response to astophandler. For example, the following commands are equivalent:
display xwhen stop {print x;}
syncThe process being debugged has just been executed with
exec(). All memory specified ina.outis valid and present, but preloaded shared libraries have not been loaded. For example,printf, although available todbx, has not been mapped into memory.A
stopon this event is ineffective; however, you can use thesyncevent with thewhencommand.
syncrtldThe
syncrtldevent occurs after async(orattachif the process being debugged has not yet processed shared libraries). It executes after the dynamic linker startup code has executed and the symbol tables of all preloaded shared libraries have been loaded, but before any code in the.initsection has run.A
stopon this event is ineffective; however, you can use thesyncrtldevent with thewhencommand.
throwThe
throwevent occurs whenever any exception that is not unhandled or unexpected is thrown by the application.
throwtypeIf an exception type is specified with the
throwevent, only exceptions of that type cause thethrowevent to occur.
throw -unhandled
-unhandledis a special exception type signifying an exception that is thrown but for which there is no handler.
throw -unexpected
-unexpectedis a special exception type signifying an exception that does not satisfy the exception specification of the function that threw it.
timersecondsThe
timerevent occurs when the program being debugged has been running for seconds. The timer used with this event is shared withcollectorcommand. The resolution is in milliseconds, so a floating point value for seconds is acceptable.Event Specification Modifiers
An event specification modifier sets additional attributes of a handler, the most common kind being event filters. Modifiers must appear after the keyword portion of an event specification. A modifier begins with a dash (
-). The following are the valid event specification modifiers.
-ifconditionThe condition is evaluated when the event specified by the event specification occurs. The side effect of the handler is allowed only if the condition evaluates to nonzero.
If the
-ifmodifier is used with an event that has an associated singular source location, such asinorat, condition is evaluated in the scope corresponding to that location. Otherwise, qualify it with the desired scope.
-infunctionThe handler is active only while within the given function or any function called from function. The number of times the function is entered is reference counted to properly deal with recursion.
-disableThe
-disablemodifier creates the handler in the disabled state.
-countn-count infinityThe
-countn and-count infinitymodifiers have the handler count from 0 (see Using Event Counters). Each time the event occurs, the count is incremented until it reaches n. Once that happens, the handler fires and the counter is reset to zero.Counts of all enabled handlers are reset when a program is run or rerun. More specifically, they are reset when the
syncevent occurs.
-tempCreates a temporary handler. Once the event has occurred it is automatically deleted. By default, handlers are not temporary. If the handler is a counting handler, it is automatically deleted only when the count reaches 0 (zero).
Use the
delete-tempcommand to delete all temporary handlers.
-instrMakes the handler act at an instruction level. This event replaces the traditional '
i' suffix of most commands. It usually modifies two aspects of the event handler:
- Any message prints assembly-level rather than source-level information.
- The granularity of the event becomes instruction level. For instance,
step -instrimplies instruction-level stepping.
-threadthread_IDThe action is executed only if the thread that caused the event matches thread_ID.
-lwplwp_IDThe action is executed only if the thread that caused the event matches lwp_ID.
-hiddenHides the handler in a regular
statuscommand. Usestatus -hto see hidden handlers.
-permNormally all handlers are thrown away when a new program is loaded. Using the
-permmodifier retains the handler across debuggings. A plaindeletecommand does not delete a permanent handler. Usedelete -pto delete a permanent handler.Parsing and Ambiguity
The syntax for event specifications and modifiers is:
- Keyword driven
- Based on
kshconventions; everything is split into words delimited by spacesExpressions can have spaces embedded in them, causing ambiguous situations. For example, consider the following two commands:
when a -tempwhen a-tempIn the first example, even though the application might have a variable named temp, the
dbxparser resolves the event specification in favor of-tempbeing a modifier. In the second example,a-tempis collectively passed to a language-specific expression parser. There must be variables named a and temp or an error occurs. Use parentheses to force parsing.Using Predefined Variables
Certain read-only
kshpredefined variables are provided. The following variables are always valid:
As an example, consider that
whereamican be implemented as:
function whereami {echo Stopped in $func at line $lineno in file $(basename $file)echo "$lineno\t$line"}Variables Valid for
whenCommandThe following variables are valid only within the body of a
whencommand.
$handleridDuring the execution of the body,
$handleridis the id of thewhencommand to which the body belongs. These commands are equivalent:
when X -temp { do_stuff; }when X { do_stuff; delete $handlerid; }
$booting
$bootingis set totrueif the event occurs during the boot process. Whenever a new program is debugged, it is first run without the user's knowledge so that the list and location of shared libraries can be ascertained. The process is then killed. This sequence is termed booting.While booting is occurring, all events are still available. Use this variable to distinguish the
syncand thesyncrtldevents occurring during adebugand the ones occurring during a normalrun.Variables Valid for Specific Events
Certain variables are valid only for specific events as shown in the following tables.
TABLE 6-2 Variable Valid for exitEvent$exitcodeValue of the argument passed to _exit(2)orexit(3)or the return value ofmain
TABLE 6-3 Variable Valid for dlopenanddlcloseEvents$dlobjPathname of the load object dlopened or dlclosed
TABLE 6-4 Variables Valid for sysinandsysoutEvents$syscodeSystem call number $sysnameSystem call name
TABLE 6-5 Variable Valid for proc_goneEvents$reasonOne of signal, exit, kill, or detach Setting Event Handler Examples
The following are some examples of setting event handlers.
Setting a Watchpoint for Store to an Array Member
To set a watchpoint on
array[99], type:
(dbx)stop access w &array[99](2) stop access w &array[99], 4(dbx)runRunning: watch.x2watchpoint array[99] (0x2ca88[4]) at line 22 in file "watch.c"22 array[i] = i;Implementing a Simple Trace
To implement a simple trace, type:
(dbx)when step { echo at line $lineno; }Enabling a Handler While Within a Function (
infunction)To enable a handler while within a function, type:
<dbx>trace step -in fooThis is equivalent to:
Determining the Number of Lines Executed
To see how many lines have been executed in a small program, type:
(dbx)stop step -count infinity# step and stop when count=inf(2) stop step -count 0/infinity(dbx)run...(dbx)status(2) stop step -count 133/infinityThe program never stops--the program terminates. The number of lines executed is 133. This process is very slow. It is most useful with breakpoints on functions that are called many times.
Determining the Number of Instructions Executed by a Source Line
To count how many instructions a line of code executes, type:
(dbx) ... # get to the line in question(dbx)stop step -instr -count infinity(dbx)step ...(dbx)status(3) stop step -count 48/infinity # 48 instructions were executedIf the line you are stepping over makes a function call, the lines in the function are counted as well. You can use the
nextevent instead ofstepto count instructions, excluding called functions.Enabling a Breakpoint After An Event Occurs
Enable a breakpoint only after another event has occurred. For example, if your program begins to execute incorrectly in function
hash, but only after the 1300'th symbol lookup, you would type:
(dbx)when in lookup -count 1300 {stop in hashhash_bpt=$newhandleridwhen proc_gone -temp { delete $hash_bpt; }}
Note $newhandleridis referring to the just executedstopincommand.
Resetting Application Files for
replayIf your application processes files that need to be reset during a
replay, you can write a handler to do that each time you run the program:
Checking Program Status
To see quickly where the program is while it is running, type:
(dbx)ignore sigint(dbx)when sig sigint { where; cancel; }Then type
^Cto see a stack trace of the program without stopping it.This is basically what the collector hand sample mode does (and more). Use
SIGQUIT (^\)to interrupt the program because^Cis now used up.Catch Floating Point Exceptions
To catch only specific floating point exceptions, for example, IEEE underflow, type:
(dbx)ignore FPE# turn off default handler(dbx)help signals | grep FPE# can't remember the subcode name...(dbx)stop sig fpe FPE_FLTUND...
|
Sun Microsystems, Inc. Copyright information. All rights reserved. Feedback |
Library | Contents | Previous | Next | Index |