Go to main content

Oracle® Solaris 11.4 DTrace (Dynamic Tracing) Guide

Exit Print View

Updated: September 2020
 
 

D Program Structure

D programs consist of a set of clauses that describe probes to enable and predicate actions to bind to these probes. D programs can also contain declarations of variables and definitions of new types.

Probe Clauses and Declarations

A D program source file consists of one or more probe clauses that describe the instrumentation that must be enabled by DTrace. Each probe clause has the following general form:

probe descriptions
/ predicate /
{
        action statements
}

You can omit the predicate and list of action statements. Any directives found outside probe clauses are referred to as declarations. Declarations must be made outside of probe clauses. No declarations inside of the enclosing { } are permitted and declarations may not be interspersed between the elements of the probe clause shown in the preceding example. You can use whitespace to separate any D program elements and to indent action statements.

You can use declarations to declare D variables and external C symbols. For more information, see Variables in DTrace. You can use declarations to define types in D. For more information, see Type and Constant Definitions in DTrace. Special D compiler directives called pragmas may also appear anywhere in a D program, including outside of probe clauses. D pragmas are specified on lines beginning with a # character. For example, D pragmas are used to set run-time DTrace options. For more information, see DTrace Options and Tunables.

Probe Descriptions

Every D program clause begins with a list of one or more probe descriptions, each taking the following form:

provider:module:function:name

If one or more fields of the probe description are omitted, the specified fields are interpreted from right to left by the D compiler. For example, the probe description foo:bar would match a probe with function foo() and name bar regardless of the value of the probe's provider and module fields. Therefore, a probe description is really more accurately viewed as a pattern that can be used to match one or more probes based on their names.

You must write D probe descriptions specifying all four field delimiters so that you can specify the desired provider on the left side. If you do not specify the provider, you might obtain unexpected results if multiple providers publish probes with the same name. Similarly, future versions of DTrace might include new providers whose probes unintentionally match your partially specified probe descriptions. You can specify a provider but match any of its probes by leaving any of the module, function, and name fields blank. For example, the description syscall::: can be used to match every probe published by the DTrace syscall provider.

Probe descriptions also support a pattern matching syntax similar to the shell globbing pattern matching syntax. For more information, see the sh(1) man page. Before matching a probe to a description, DTrace scans each description field for the characters *, ?, and [. If one of these characters appears in a probe description field and is not preceded by a \, the field is regarded as a pattern. The description pattern must match the entire corresponding field of a given probe. The complete probe description must match on every field in order to successfully match and enable a probe. A probe description field that is not a pattern must exactly match the corresponding field of the probe. A description field that is empty matches any probe.

The following table lists the special characters that are recognized in probe name patterns.

Table 1  Probe Name Pattern Matching Characters
Symbol
Description
*
Matches any string, including the null string.
?
Matches any single character.
[ ... ]
Matches any one of the enclosed characters. A pair of characters separated by - matches any character between the pair, inclusive. If the first character after the [ is !, any character not enclosed in the set is matched.
\
Interpret the next character as itself, without any special meaning.

Pattern match characters can be used in any or all of the four fields of the probe descriptions. You can also use patterns to list matching probes by using the patterns on the command line with the dtrace -l command. For example, the command dtrace -l -f kmem_* lists all DTrace probes in functions whose names begin with the prefix kmem_.

If you want to specify the same predicate and actions for more than one probe description or description pattern, you can place the descriptions in a comma-separated list. For example, the following D program would trace a timestamp each time probes associated with entry to system calls containing the words "lwp" or "sock" fire:

syscall::*lwp*:entry, syscall::*sock*:entry
{
        trace(timestamp);
}

A probe description may also specify a probe using its integer probe ID. For example:

12345
{
        trace(timestamp);
}

You can use the preceding clause to enable probe ID 12345, as reported by the dtrace -l -i 12345 command. You must always write D programs using human-readable probe descriptions. Integer probe IDs are not guaranteed to remain consistent as DTrace provider kernel modules are loaded and unloaded or following a reboot.

Predicates in DTrace

Predicates are expressions enclosed in slashes / / that are evaluated at probe firing time to determine whether the associated actions should be executed. Predicates are the primary conditional construct used for building more complex control flow in a D program. You can omit the predicate section of the probe clause entirely for any probe, in which case the actions are always executed when the probe fires.

Predicate expressions can use any of the previously described D operators and may refer to any D data objects such as variables and constants. The predicate expression must evaluate to a value of integer or pointer type so that it can be considered as true or false. As with all D expressions, a zero value is interpreted as false and any non-zero value is interpreted as true.

One major difference between D and other programming languages such as C, C++, and the Java programming language is the absence of control-flow constructs such as if-statements and loops. D program clauses are written as single straight-line statement lists that trace an optional, fixed amount of data. D does provide the ability to conditionally trace data and modify control flow using logical expressions called predicates that can be used to prefix program clauses. A predicate expression is evaluated at probe firing time prior to executing any of the statements associated with the corresponding clause. If the predicate evaluates to true, represented by any non-zero value, the statement list is executed. If the predicate is false, represented by a zero value, none of the statements are executed and the probe firing is ignored.

Example 2  Creating a 10-Second Countdown Timer

Type the following source code and save it in a file named countdown.d:

dtrace:::BEGIN
{
        i = 10;
}

profile:::tick-1sec
/i > 0/
{
        trace(i--);
}

profile:::tick-1sec
/i == 0/
{
        trace("blastoff!");
        exit(0);
}

This D program implements a 10-second countdown timer using predicates. When executed, countdown.d counts down from 10 and then prints a message and exits:

# dtrace -s countdown.d
dtrace: script 'countdown.d' matched 3 probes
CPU     ID                    FUNCTION:NAME
        0  25499                       :tick-1sec 10
        0  25499                       :tick-1sec 9
        0  25499                       :tick-1sec 8
        0  25499                       :tick-1sec 7
        0  25499                       :tick-1sec 6
        0  25499                       :tick-1sec 5
        0  25499                       :tick-1sec 4
        0  25499                       :tick-1sec 3
        0  25499                       :tick-1sec 2
        0  25499                       :tick-1sec 1
        0  25499                       :tick-1sec blastoff!
#

This example uses the BEGIN probe to initialize an integer i to 10 to begin the countdown. The program uses the tick-1sec probe to implement a timer that fires once per second. Notice that in countdown.d, the tick-1sec probe description is used in two different clauses, each with a different predicate and action list. The predicate is a logical expression surrounded by enclosing slashes / / that appears after the probe name and before the braces { } that surround the clause statement list.

The first predicate tests whether i is greater than zero, indicating that the timer is still running:

profile:::tick-1sec
/i > 0/
{
        trace(i--);
}

The relational operator > means greater than and returns the integer value zero for false and one for true. All of the C relational operators are supported in D; the complete list is found in Types, Operators, and Expressions in DTrace. If i is not yet zero, the script traces i and then decrements it by one using the - operator.

The second predicate uses the == operator to return true when i is exactly equal to zero, indicating that the countdown is complete:

profile:::tick-1sec
/i == 0/
{
        trace("blastoff!");
        exit(0);
}

The countdown.d program uses a sequence of characters enclosed in double quotes, called a string constant, to print a final message when the countdown is complete. The exit() function is then used to exit dtrace and return to the shell prompt.

If you look back at the structure of countdown.d, you will see that by creating two clauses with the same probe description, but different predicates and actions, effectively created the logical flow:

i = 10
once per second,
        if i is greater than zero
                trace(i--);
        otherwise if i is equal to zero
                trace("blastoff!");
                exit(0);

When you want to write complex programs using predicates, try to first visualize your algorithm in this manner, and then transform each path of your conditional constructs into a separate clause and predicate.

Now combine predicates with a new provider, the syscall provider, and create the first real D tracing program. The syscall provider permits you to enable probes on entry to or return from any Oracle Solaris system call. The next example uses DTrace to observe every time your shell performs a read or write system call. For more information, see the read(2) and write(2) man page. First, open two terminal windows, one to use for DTrace and the other containing the shell process you are going to watch. In the second window, type the following command to obtain the process ID of this shell:

# echo $$
12345

Now go back to your first terminal window and type the following D program and save it in a file named rw.d. As you type in the program, replace the integer constant 12345 with the process ID of the shell that was printed in response to your echo command.

syscall::read:entry,
syscall::write:entry
/pid == 12345/
{
}

Notice that the body of rw.d's probe clause is left empty because the program is only intended to trace notification of probe firings and not to trace any additional data. Once you have typed in rw.d, use dtrace to start your experiment and then go to your second shell window and type a few commands, pressing return after each command. As you type, you should see dtrace report probe firings in your first window, similar to the following example:

# dtrace -s rw.d
dtrace: script 'rw.d' matched 2 probes
CPU     ID                    FUNCTION:NAME
        0     34                      write:entry
        0     32                      read:entry
        0     34                      write:entry
        0     32                      read:entry
        0     34                      write:entry
        0     32                      read:entry
        0     34                      write:entry
        0     32                      read:entry
...

The read and write system calls read a character from your terminal window and echo back the result. This example includes many of the concepts described so far and a few new ones as well. First, to instrument read and write in the same manner, the script uses a single probe clause with multiple probe descriptions by separating the descriptions with commas like this:

syscall::read:entry,
syscall::write:entry

For readability, each probe description appears on its own line. This arrangement is not strictly required, but it makes for a more readable script. Next the script defines a predicate that matches only those system calls that are executed by your shell process:

/pid == 12345/

The predicate uses the predefined DTrace variable pid, which always evaluates to the process ID associated with the thread that fired the corresponding probe. DTrace provides many built-in variable definitions for useful things like the process ID. The following table lists a few DTrace variables you can use to write your first D program.

Variable
Data Type
Meaning
errno
int
Current errno value for system calls
execname
string
Name of the current process's executable file
pid
pid_t
Process ID of the current process
tid
id_t
Thread ID of the current thread
probeprov
string
Current probe description's provider field
probemod
string
Current probe description's module field
probefunc
string
Current probe description's function field
probename
string
Current probe description's name field

Now that you have written a real instrumentation program, try experimenting with it on different processes running on your system by changing the process ID and the system call probes that are instrumented. Then, you can make one more simple change and turn rw.d into a very simple version of a system call tracing tool like truss. An empty probe description field acts as a wildcard, matching any probe, so change the program to the following new source code to trace any system call executed by your shell:

syscall:::entry
/pid == 12345/
{
}

Try typing a few commands in the shell such as cd, ls, and date to see what your DTrace program reports.

Probe Actions

Probe actions are described by a list of statements separated by semicolons (;) and enclosed in braces { }. If you only want to note that a particular probe fired on a particular CPU without tracing any data or performing any additional actions, you can specify an empty set of braces with no statements inside.

Order of Executing DTrace Actions

Each clause is represented by its predicate, if any, and the clause's actions. When an enabled probe fires, its actions will execute if the predicate evaluates to true or if no predicate is given. Program order determines the order in which actions are executed. Two or more clauses that enable the same probe will also execute in program order.

Use of the C Preprocessor

The C programming language used for defining system interfaces in Oracle Solaris includes a preprocessor that performs a set of initial steps in C program compilation. The C preprocessor is commonly used to define macro substitutions where one token in a C program is replaced with another predefined set of tokens, or to include copies of system header files. You can use the C preprocessor in conjunction with D programs by specifying the dtrace -C option. This option causes dtrace to first execute the cpp preprocessor on your program source file and then pass the results to the D compiler.

The D compiler automatically loads the set of C type descriptions associated with the operating system implementation, but you can use the preprocessor to include type definitions such as types used in your own C programs. You can also use the preprocessor to perform tasks such as creating macros that expand to chunks of D code and other program elements. If you use the preprocessor with D program, you may only include files that contain valid D declarations. Typical C header files include only external declarations of types and symbols, which will be correctly interpreted by the D compiler. The D compiler cannot parse C header files that include additional program elements like C function source code and produces an appropriate error message.