next up previous contents index
Next: 4 Probe points Up: SystemTap Language Reference Previous: 2 Types of SystemTap   Contents   Index


3 Components of a SystemTap script

The main construct in the scripting language identifies probes. Probes associate abstract events with a statement block, or probe handler, that is to be executed when any of those events occur.

The following example shows how to trace entry and exit from a function using two probes.

probe kernel.function("sys_mkdir").call { log ("enter") }
probe kernel.function("sys_mkdir").return { log ("exit") }

To list the probe-able functions in the kernel, use the listing option (-l). For example:

$ stap -l 'kernel.function("*")' | sort

3.1 Probe definitions

The general syntax is as follows.

Events are specified in a special syntax called probe points. There are several varieties of probe points defined by the translator, and tapset scripts may define others using aliases. The provided probe points are listed in the stapprobes(3), tapset::*(3stap), and probe::*(3stap) man pages. The STMT statement block is executed whenever iany of the named PROBEPOINT events occurs.

The probe handler is interpreted relative to the context of each event. For events associated with kernel code, this context may include variables defined in the source code at that location. These target variables (or ``context variables'') are presented to the script as variables whose names are prefixed with a dollar sign ($). They may be accessed only if the compiler used to compile the kernel preserved them, despite optimization. This is the same constraint imposed by a debugger when working with optimized code. Other events may have very little context.

3.2 Probe aliases

The general syntax is as follows.

probe <alias> = <probepoint> { <prologue_stmts> }
probe <alias> += <probepoint> { <epilogue_stmts> }

New probe points may be defined using aliases. A probe point alias looks similar to probe definitions, but instead of activating a probe at the given point, it defines a new probe point name as an alias to an existing one. New probe aliases may refer to one or more existing probe aliases. Multiple aliases may share the same underlying probe points. The following is an example.

probe socket.sendmsg = kernel.function ("sock_sendmsg") { ... }
probe socket.do_write = kernel.function ("do_sock_write") { ... }
probe socket.send = socket.sendmsg, socket.do_write { ... }

There are two types of aliases, the prologue style and the epilogue style which are identified by the equal sign (=) and "+=" respectively.

A probe that uses a probe point alias will create an actual probe, with the handler of the alias pre-pended.

This pre-pending behavior serves several purposes. It allows the alias definition to pre-process the context of the probe before passing control to the handler specified by the user. This has several possible uses, demonstrated as follows.

# Skip probe unless given condition is met:
if ($flag1 != $flag2) next

# Supply values describing probes:
name = "foo"

# Extract the target variable to a plain local variable:
var = $var

3.2.1 Prologue-style aliases (=)

For a prologue style alias, the statement block that follows an alias definition is implicitly added as a prologue to any probe that refers to the alias. The following is an example.

# Defines a new probe point, which expands to
# kernel.function("sys_read"), with the given statement as
# a prologue.
probe = kernel.function("sys_read") {
    fildes = $fd

3.2.2 Epilogue-style aliases (+=)

The statement block that follows an alias definition is implicitly added as an epilogue to any probe that refers to the alias. It is not useful to define new variables there (since no subsequent code will see them), but rather the code can take action based upon variables set by the prologue or by the user code. The following is an example:

# Defines a new probe point with the given statement as an
# epilogue.
probe += kernel.function("sys_read") {
    if (traceme) println ("tracing me")

3.2.3 Probe alias usage

A probe alias is used the same way as any built-in probe type, by naming it:

probe {
    printf("reading fd=%d\n", fildes)

3.2.4 Alias suffixes

It is possible to include a suffix with a probe alias invocation. If only the initial part of a probe point matches an alias, the remainder is treated as a suffix and attached to the underlying probe point(s) when the alias is expanded. For example:

/* Define an alias: */
probe sendrecv = tcp.sendmsg, tcp.recvmsg { ... }

/* Use the alias in its basic form: */
probe sendrecv { ... }

/* Use the alias with an additional suffix: */
probe sendrecv.return { ... }

Here, the second use of the probe alias is equivalent to writing probe tcp.sendmsg.return, tcp.recvmsg.return.

As another example, the probe points tcp.sendmsg.return and tcp.recvmsg.return are actually defined as aliases in the tapset tcp.stp. They expand to a probe point of the form kernel.function("...").return, so they can also be suffixed:

probe tcp.sendmsg.return.maxactive(10) {
    printf("returning from sending %d bytes\n", size)

Here, the probe point expands to kernel.function("tcp_sendmsg").return.maxactive(10).

3.2.5 Alias suffixes and wildcards

When expanding wildcards, SystemTap generally avoids considering alias suffixes in the expansion. The exception is when a wildcard element is encountered that does not have any ordinary expansions. Consider the following example:

probe some_unrelated_probe = ... { ... }

probe myprobe = { ... }

probe myprobe.test = some_unrelated_probe { ... }

probe myprobe.* { ... }

probe myprobe.ret* { ... }

Here, return would be a valid suffix for myprobe. The wildcard myprobe.* matches the ordinary alias myprobe.test, and hence the suffix expansion myprobe.return is not included. Conversely, myprobe.ret* does not match any ordinary aliases, so the suffix myprobe.return is included as an expansion.

3.3 Variables

Identifiers for variables and functions are alphanumeric sequences, and may include the underscore (_) and the dollar sign ($) characters. They may not start with a plain digit. Each variable is by default local to the probe or function statement block where it is mentioned, and therefore its scope and lifetime is limited to a particular probe or function invocation. Scalar variables are implicitly typed as either string or integer. Associative arrays also have a string or integer value, and a tuple of strings or integers serves as a key. Arrays must be declared as global. Local arrays are not allowed.

The translator performs type inference on all identifiers, including array indexes and function parameters. Inconsistent type-related use of identifiers results in an error.

Variables may be declared global. Global variables are shared among all probes and remain instantiated as long as the SystemTap session. There is one namespace for all global variables, regardless of the script file in which they are found. Because of possible concurrency limits, such as multiple probe handlers, each global variable used by a probe is automatically read- or write-locked while the handler is running. A global declaration may be written at the outermost level anywhere in a script file, not just within a block of code. Global variables which are written but never read will be displayed automatically at session shutdown. The following declaration marks var1 and var2 as global. The translator will infer a value type for each, and if the variable is used as an array, its key types.

global var1[=<value>], var2[=<value>]

3.3.1 Unused variables

The SystemTap translator removes unused variables. Global variable that are never written or read are discarded. Every local variables where the variable is only written but never read are also discarded. This optimization prunes unused variables defined in the probe aliases, but never used in the probe handler. If desired, this optimization can disabled with the -u option.

3.4 Auxiliary functions

General syntax:

function <name>[:<type>] ( <arg1>[:<type>], ... ) { <stmts> }
SystemTap scripts may define subroutines to factor out common work. Functions may take any number of scalar arguments, and must return a single scalar value. Scalars in this context are integers or strings. For more information on scalars, see Section [*] and Section [*]. The following is an example function declaration.

function thisfn (arg1, arg2) {
    return arg1 + arg2

Note the general absence of type declarations, which are inferred by the translator. If desired, a function definition may include explicit type declarations for its return value, its arguments, or both. This is helpful for embedded-C functions. In the following example, the type inference engine need only infer the type of arg2, a string.

function thatfn:string(arg1:long, arg2) {
    return sprintf("%d%s", arg1, arg2)

Functions may call others or themselves recursively, up to a fixed nesting limit. See Section [*].

3.5 Embedded C

SystemTap supports a guru mode where script safety features such as code and data memory reference protection are removed. Guru mode is set by passing the -g option to the stap command. When in guru mode, the translator accepts C code enclosed between ``%{'' and ``%}'' markers in the top level of the script file. The embedded C code is transcribed verbatim, without analysis, in sequence, into the top level of the generated C code. Thus, guru mode may be useful for adding #include instructions at the top level of the generated module, or providing auxiliary definitions for use by other embedded code.

When in guru mode, embedded C code blocks are also allowed as the body of a SystemTap function (as described in Section [*]), and in place of any SystemTap expression. In the latter case, the code block must contain a valid expression according to C syntax.

Here is an example of the various permitted methods of embedded C code inclusion:

#include <linux/in.h>
#include <linux/ip.h>
%} /* <-- top level */

/* Reads the char value stored at a given address: */ 
function __read_char:long(addr:long) %{ /* pure */
         STAP_RETURN(kderef(sizeof(char), STAP_ARG_addr));
         CATCH_DEREF_FAULT ();
%} /* <-- function body */

/* Determines whether an IP packet is TCP, based on the iphdr: */
function is_tcp_packet:long(iphdr) {
         protocol = @cast(iphdr, "iphdr")->protocol
         return (protocol == %{ IPPROTO_TCP %}) /* <-- expression */

3.6 Embedded C functions

General syntax:

function <name>:<type> ( <arg1>:<type>, ... ) %{ <C_stmts> %}
Embedded C code is permitted in a function body. In that case, the script language body is replaced entirely by a piece of C code enclosed between ``%{'' and ``%}'' markers. The enclosed code may do anything reasonable and safe as allowed by the C parser.

There are a number of undocumented but complex safety constraints on concurrency, resource consumption and runtime limits that are applied to code written in the SystemTap language. These constraints are not applied to embedded C code, so use embedded C code with extreme caution. Be especially careful when dereferencing pointers. Use the kread() macro to dereference any pointers that could potentially be invalid or dangerous. If you are unsure, err on the side of caution and use kread(). The kread() macro is one of the safety mechanisms used in code generated by embedded C. It protects against pointer accesses that could crash the system.

For example, to access the pointer chain name = skb->dev->name in embedded C, use the following code.

struct net_device *dev;
char *name;
dev = kread(&(skb->dev));
name = kread(&(dev->name));

The memory locations reserved for input and output values are provided to a function using macros named STAP_ARG_foo (for arguments named foo) and STAP_RETVALUE. Errors may be signalled with STAP_ERROR. Output may be written with STAP_PRINTF. The function may return early with STAP_RETURN. Here are some examples:

function integer_ops:long (val) %{
  STAP_PRINTF("%d\n", STAP_ARG_val);
  if (STAP_RETVALUE == 4)
      STAP_ERROR("wrong guess: %d", (int) STAP_RETVALUE);
  if (STAP_RETVALUE == 3)
function string_ops:string (val) %{
  if (strcmp (STAP_RETVALUE, "three-two-one"))
      STAP_RETURN("parameter should be three-two-");
function no_ops () %{
    STAP_RETURN(); /* function inferred with no return value */

The function argument and return value types should be stated if the translator cannot infer them from usage. The translator does not analyze the embedded C code within the function.

You should examine C code generated for ordinary script language functions to write compatible embedded-C. Usually, all SystemTap functions and probes run with interrupts disabled, thus you cannot call functions that might sleep within the embedded C.

3.7 Embedded C pragma comments

Embedded C blocks may contain various markers to assert optimization and safety properties.

next up previous contents index
Next: 4 Probe points Up: SystemTap Language Reference Previous: 2 Types of SystemTap   Contents   Index