STAP(1)
π NAME π
stap β systemtap script translator/driver. That's it, that's the whole icon. π
β¨ SYNOPSIS β¨
stap [ OPTIONS ] FILENAME [ ARGUMENTS ]
stap [ OPTIONS ] - [ ARGUMENTS ]
stap [ OPTIONS ] -e SCRIPT [ ARGUMENTS ]
stap [ OPTIONS ] -l PROBE [ ARGUMENTS ]
stap [ OPTIONS ] -L PROBE [ ARGUMENTS ]
stap [ OPTIONS ] --dump-probe-types
stap [ OPTIONS ] --dump-probe-aliases
stap [ OPTIONS ] --dump-functions
π¦ DESCRIPTION π¦
okay so bestie, stap is the front-end to the Systemtap tool. She takes probing instructions written in a cute little domain-specific language, translates those instructions into C code, compiles that C code, and then loads the resulting module into a running Linux kernel or a Dyninst user-space mutator, so it can do the requested system trace/probe functions. literally the whole pipeline, she does it. π
You can hand her the script in a named file (FILENAME), from standard input (just use - instead of FILENAME), or straight from the command line (that's the -e SCRIPT move). π«Ά
The program runs until one of these happens:
- it gets interrupted by the user,
- the script voluntarily invokes the
exit()function, - or there's a sufficient number of soft errors. π
The language β described in the SCRIPT LANGUAGE section below β is strictly typed, expressive, declaration free, procedural, prototyping-friendly, and inspired by awk and C. She lets you associate source code points or events in the system with handlers, which are subroutines that are executed synchronously. Conceptually it's somewhat similar to "breakpoint command lists" in the gdb debugger. iykyk. β¨
π DOCUMENTATION OVERVIEW π
systemtap comes with a whole variety of educational, documentation and reference resources. They come online and/or packaged for offline use. Some systemtap diagnostic warning/error messages specially suggest reading a man page by including a string like [man error::pass5]. For online documentation, see the project web site, https://sourceware.org/systemtap/ π
π man pages π
stap(this page) β language syntax, concepts, operation, optionserror::*β further explanation of error conditionswarning::*β further explanation of warning conditionsstapprobesβ probe points and their$contextvariablesstaprefβ quick reference to language syntaxstappathsβ list of directories, including books & referencesstap-prepβ program to install auxiliary dependencies like kernel debuginfotapset::*β generated list of tapsetsprobe::*β generated list of tapset probe aliasesfunction::*β generated list of tapset functionsmacro::*β generated list of tapset macrosstapvarsβ some of the tapset global variablesstaprun,stapdyn,stapbpfβ programs for executing compiled systemtap scriptssystemtapβ initscript, boot-time probingstap-serverβ compilation serverstapexβ a few very basic script examples
π books π
- Beginner's Guide β tutorial book, language essentials, examples
- Tutorial β shorter tutorial, exercises
- Language Reference β detailed language manual, covers statistics/analysis
- Tapset Reference β the tapset man pages, reformatted into a book
π references π
- example scripts β over a hundred directly usable sysadmin tools, toys, hacks to learn from π
π OPTIONS π
The systemtap translator supports the following options. Any other option prints a list of supported options. Options may be given on the command line, as usual. If the file $SYSTEMTAP_DIR/rc exists, options are also loaded from there and interpreted first. ($SYSTEMTAP_DIR defaults to $HOME/.systemtap if unset.) ποΈ
In some cases, the default value of an option depends on particular system configuration and thus can't be mentioned here directly. In some of those cases running stap --help might display the default. π
-β Use standard input instead of a givenFILENAMEas probe language input, unless-e SCRIPTis given.-h,--helpβ Show help message.-V,--versionβ Show version message.-p NUMβ stop after pass NUM, bestie. The passes are numbered1-5: parse, elaborate, translate, compile, run. Wanna know what each one actually does? Peep the PROCESSING section π-vβ bump the verbosity for all the passes. Every time you repeat this option, you get a bigger volume of informative (?) output. yes the question mark is canon, we don't make the rules π--vp ABCDEβ verbosity, but make it per-pass, a custom lil cocktail for each one πΉ For example,"--vp 002"adds 2 units of verbosity to pass 3 only. And the combo"-v --vp 00004"adds 1 unit of verbosity for all passes, plus 4 more for pass 5. Mix responsibly.-kβ keep the temporary directory after all processing is done. Super useful if you wanna peek at the generated C code, or reuse the compiled kernel object later. it's giving "saving the leftovers" energy π«Ά-gβ Guru mode. Unlocks parsing of unsafe expert-level constructs like embedded C. > bestie this is the "I know what I'm doing" button and it will absolutely let you hurt yourself. unsafe is right there in the name. β οΈ-Pβ Prologue-searching mode. This is literally the same as--prologue-searching=always. It activates heuristics to work around incorrect debugging information for function parameter$contextvariables.-uβ Unoptimized mode. Disables unused code elision and a whole bunch of other optimizations during elaboration / translation.-wβ Suppressed warnings mode. Turns off all warning messages. poof, gone π-Wβ Treat all warnings as errors. No more gentle lil warnings, everything's a hard fail now.-bβ Use bulk mode (percpu files) for kernel-to-user data transfer. Then use thestap-mergeprogram to multiplex them back together later.-i,--interactiveβ Interactive mode. Enables an interface to build the systemtap script incrementally and interactively. yes, live-coding but make it kernel probes β¨-tβ Collect timing information on the number of times a probe executes and the average amount of time spent in each probe-point. Also shows the derivation for each probe-point. she's nosy and we love that for her π΅οΈβοΈ-s NUMβ Use NUM megabyte buffers for kernel-to-user data transfer per processor. The default is16MB, or less on smaller memory machines.-I DIRβ Add the given directory to the tapset search directory. See the description of pass 2 for the deets.-D NAME=VALUEβ Add the given C preprocessor directive to the module Makefile. These can be used to override the limit parameters described below.-B NAME=VALUEβ In kernel-runtime mode, add the given make directive to the kernel module build's make invocation. These can be used to add or override kconfig options. For example, use
-B CONFIG_DEBUG_INFO=y
to add debugging information.
-B FLAGβ In dyninst-runtime mode, add the given parameter to the compiler CFLAGS used for building the dyninst shared library. For example, use
-B -g
to add debugging information.
--debugβ Build the generated kernel module (.ko) or dyninst module (.so) with maximum debugging information, for diagnosing code generation problems. This enablesCONFIG_DEBUG_INFO=y(kernel mode), passes-gto the compiler, uses-save-temps=objto preserve intermediate.i/.sfiles, and (if available) runspahole(1)on the resulting module, saving its output as$module.paholein the temporary directory. Implies-k(keep temporary directory). > heads up: this option is disallowed when--client-optionsis used. π«-a ARCHβ Use a cross-compilation mode for the given target architecture. This requires access to the cross-compiler and the kernel build tree, and it goes along with the
-B CROSS_COMPILE=arch-tool-prefix-
and
-r /build/tree
options.
--modinfo NAME=VALUEβ Add the name/value pair as aMODULE_INFOmacro call to the generated module. This may be useful to inform or override various module-related checks in the kernel.-G NAME=VALUEβ Sets the value of global variable NAME to VALUE whenstaprunis invoked. This applies to scalar variables declared global in the script/tapset.-R DIRβ Look for the systemtap runtime sources in the given directory. Your DIR default can be seen using"stap --help".-r /DIRβ Build for kernel in the given build tree. Can also be set with theSYSTEMTAP_RELEASEenvironment variable.-r RELEASEβ Build for kernel in build tree/lib/modules/RELEASE/build. Can also be set with theSYSTEMTAP_RELEASEenvironment variable.-m MODULEβ Use the given name for the generated kernel object module, instead of a unique randomized name. The generated kernel object module is copied to the current directory. no more mystery-meat filenames π-d MODULEβ Add symbol/unwind information for the given module into the kernel object module. This may enable symbolic tracebacks from those modules/programs, even if they don't have an explicit probe placed into them.--lddβ Add symbol/unwind information for all user-space shared libraries thatlddsuspects are necessary for user-space binaries being probed or listed with the-doption. > Caution: this can make the probe modules considerably larger. And ngl, note that this option does not deal with kernel-space modules: see instead--all-modulesbelow.--all-modulesβ Equivalent to specifying"-dkernel"and a"-d"for each kernel module that is currently loaded. > Caution: this can make the probe modules considerably larger. bestie those modules are gonna be THICC π-o FILEβ Send standard output to the named file. In bulk mode, percpu files will start withFILE_(FILE_cpuwith-F) followed by the cpu number. This supportsstrftime(3)formats for FILE.-c CMDβ Start the probes, run CMD, and exit when CMD finishes. This also has the effect of settingtarget()to the pid of that process. Note that many probe types trigger independently of this setting. Consider including something like this to focus your script:
probe FOO { if (pid() != target()) next; .... }
-x PIDβ Setstarget()to PID. The script runs independently of the PID's lifespan.-e SCRIPTβ Run the given SCRIPT specified on the command line.-E SCRIPTβ Run the given SCRIPT specified. This SCRIPT is run in addition to the main script specified, through-e, or as a script file. This option can be repeated to run multiple scripts, and can be used in listing mode (-l/-L).-l PROBEβ Instead of running a probe script, just list all the available probe points matching the given single probe point. The pattern may include wildcards and aliases, but not comma-separated multiple probe points. The process result code will indicate failure if there are no matches. like so:
% stap -e 'probe syscall.* { }'
[...]
% stap -l 'syscall.*'
syscall.accept
[...]
syscall.writev
-L PROBEβ Similar to"-l", but list matching probe points plus their available context variables. When-vis set with-L, the output includes duplicate probe points which are distinguished by their PC address.
% stap -L 'process("/lib64/libpython*.so.*").mark("*")'
process("/usr/lib64/libpython3.6m.so.1.0").mark("function__entry") $arg1:long $arg2:long $arg3:long
process("/usr/lib64/libpython3.6m.so.1.0").mark("function__return") $arg1:long $arg2:long $arg3:long
process("/usr/lib64/libpython3.6m.so.1.0").mark("gc__done") $arg1:long
process("/usr/lib64/libpython3.6m.so.1.0").mark("gc__start") $arg1:long
process("/usr/lib64/libpython3.6m.so.1.0").mark("line") $arg1:long $arg2:long $arg3:long
-Fβ Without the-ooption, load the module and start the probes, then detach from the module leaving the probes running. With the-ooption, runstaprunin the background as a daemon and show its pid. set it and forget it β¨-S size[,N]β Sets the maximum size of output file and the maximum number of output files. If the size of the output file will exceedsizemegabytes, systemtap switches the output file to the next file. And if the number of output files exceedsN, systemtap removes the oldest output file. You can omit the second argument.-T TIMEOUTβ Exit the script after TIMEOUT seconds. bye bestie, timer's up β°--skip-badvarsβ Ignore unresolvable or run-time-inaccessible context variables and substitute with0, without errors. no drama, just zeroes π«Ά--prologue-searching[=WHEN]β Prologue-searching mode. Activate heuristics to work around incorrect debugging information for function parameter$contextvariables. WHEN can be either"never","always", or"auto"(i.e. enabled by heuristic). If WHEN is missing, then"always"is assumed. If the option is missing, then"auto"is assumed.--suppress-handler-errorsβ Wrap all probe handlers into something like this
try { ... } catch { next }
block, which causes any runtime errors to be quietly suppressed. Suppressed errors do not count against MAXERRORS limits. In this mode, the MAXSKIPPED limits are also suppressed, so that many errors and skipped probes may be accumulated during a script's runtime. Any overall counts will still be reported at shutdown. > lowkey this is the "pretend it's fine" button, and the receipts still show up at the end π
--compatible VERSIONβ Suppress recent script language or tapset changes which are incompatible with the given older version of systemtap. This may be useful if a much older systemtap script fails to run. See the DEPRECATION section for more details.--check-versionβ This option is used to check if the active script has any constructs that may be systemtap version specific. See the DEPRECATION section for more details.--clean-cacheβ This option prunes stale entries from the cache directory. This is normally done automatically after successful runs, but this option will trigger the cleanup manually and then exit. See the CACHING section for more details about cache limits. spring cleaning but for your cache π§ΉπΈ--color[=WHEN],--colour[=WHEN]β This option controls coloring of error messages. WHEN can be either"never","always", or"auto"(i.e. enable only if at a terminal). If WHEN is missing, then"always"is assumed. If the option is missing, then"auto"is assumed. yes bestie, spelling it with auis valid, this page is bilingual in vibe π
Okay so the colors? Fully remixable with the SYSTEMTAP_COLORS environment variable π¨β¨. The format has to be exactly this shape:
key1=val1:key2=val2:key3=val3 ...etc.
Valid keys are "error", "warning", "source", "caret", and "token" β that's the whole roster, no extras π
. Values are Select Graphic Rendition (SGR) parameter(s), so go consult your terminal's documentation for the SGRs it actually supports. For example, the default colors would be expressed as
error=01;31:warning=00;33:source=00;34:caret=01:token=01
If SYSTEMTAP_COLORS is absent, the default colors will be used. If it is empty or invalid, coloring is turned off. bye bestie π
--disable-cacheβ turns off all use of the cache directory. Like, no files will be either read from or written to the cache. The cache is simply not invited π«--poison-cacheβ treats files in the cache directory as invalid π. Nothing gets read from the cache, but files resulting from this run will still be written to it. This is meant as a troubleshooting aid for when stap's cached behavior seems to be misbehaving. And if it helped? There is a probably a bug in systemtap that the developers would like you to report π (they genuinely want the report, fr fr).--privilege[=stapusr | =stapsys | =stapdev]β tells stap to examine the script looking for constructs which are not allowed for the specified privilege level (see UNPRIVILEGED USERS). Compilation fails if any such constructs are used, no exceptions. Ifstapusrorstapsysare specified when using a compile server (see--use-server), the server will examine the script and, if compilation succeeds, the server will cryptographically sign the resulting kernel module, certifying that is it safe for use by users at the specified privilege level π
And here's the auto-magic, bestie: if --privilege has not been specified, -pN has not been specified with N < 5, and the invoking user is not root, and is not a member of the group stapdev, then stap will automatically add the appropriate --privilege option to the options already specified. It just does it. main character energy π
--semantic-keep-goingβ likemake -kfor translator pass 2 (elaboration) π οΈ. When asemantic_erroris encountered, record it and continue elaborating sibling probes/functions as far as practical, instead of aborting the rest of the batch. At the end of the pass that saw errors, stap dumps a machine-parseable catalog on stderr:
SEMANTIC_ERRORS: N
SEMANTIC_ERROR\tfile\tline\tcolumn\ttoken\tmessage
...
SEMANTIC_ERRORS_END
Each chained cause is listed as its own SEMANTIC_ERROR line. The token field is the primary token text (often an identifier name), or "-" when absent. Tabs/newlines in token/message are flattened to spaces. stap still exits non-zero if any errors occurred, and does not proceed to later passes. Optional probe-point ? semantics are unchanged. This one is intended for automated testing (omnibus expected-failure scripts).
--unprivilegedβ literally just--privilege=stapusr. same vibe, shorter name π«--use-server[=HOSTNAME[:PORT] | =IP_ADDRESS[:PORT] | =CERT_SERIAL]β specify compile-server(s) to be used for compilation and/or, in conjunction with--list-serversand--trust-servers(see below), for listing. If no argument is supplied, then the default in unprivileged mode (see--privilege) is to select compatible servers which are trusted as SSL peers and as module signers and currently online. Otherwise the default is to select compatible servers which are trusted as SSL peers and currently online π
--use-server may be specified more than once, in which case a list of servers is accumulated in the order specified π. Servers may be specified by host name, ip address, or by certificate serial number (obtained using --list-servers). That last one is most commonly used when adding or revoking trust in a server (see --trust-servers below). If a server is specified by host name or ip address, then an optional port number may be specified. This is useful for accessing servers which are not on the local network or to specify a particular server.
IP addresses may be IPv4 or IPv6 addresses β¨
If a particular IPv6 address is link local and exists on more than one interface, the intended interface may be specified by appending the address with a percent sign (%) followed by the intended interface name. For example, "fe80::5eff:35ff:fe07:55ca%eth0".
In order to specify a port number with an IPv6 address, it is necessary to enclose the IPv6 address in square brackets ([]) in order to separate the port number from the rest of the address. For example, "[fe80::5eff:35ff:fe07:55ca]:5000" or "[fe80::5eff:35ff:fe07:55ca%eth0]:5000".
Auto-add round two: if --use-server has not been specified, -pN has not been specified with N < 5, and the invoking user is not root, is not a member of the group stapdev, but is a member of the group stapusr, then stap will automatically add --use-server to the options already specified π«Ά
--use-server-on-error[=yes|=no]β instructs stap to retry compilation of a script using a compile server if compilation on the local host fails in a manner which suggests that it might succeed using a server. If this option is not specified, the default isno. If no argument is provided, then the default isyes. Compilation will be retried for certain types of errors (e.g. insufficient data or resources) which may not occur during re-compilation by a compile server. Compile servers will be selected automatically for the re-compilation attempt as if--use-serverwas specified with no arguments π--list-servers[=SERVERS]β display the status of the requested SERVERS, where SERVERS is a comma-separated list of server attributes. The list of attributes is combined to filter the list of servers displayed. Supported attributes are:allβ specifies all known servers (trusted SSL peers, trusted module signers, online servers).specifiedβ specifies servers specified using--use-server.onlineβ filters the output by retaining information about servers which are currently online.trustedβ filters the output by retaining information about servers which are trusted as SSL peers.signerβ filters the output by retaining information about servers which are trusted as module signers (see--privilege).compatibleβ filters the output by retaining information about servers which are compatible with the current kernel release and architecture.
If no argument is provided, then the default is specified. And if no servers were specified using --use-server, then the default servers for --use-server are listed.
Heads up bestie π¨:--list-serversuses theavahi-daemonservice to detect online servers. If this service is not available, then--list-serverswill fail to detect any online servers. In order for--list-serversto detect servers listening on IPv6 addresses, theavahi-daemonconfiguration file/etc/avahi/avahi-daemon.confmust contain an active"use-ipv6=yes"line. The service must be restarted after adding this line in order for IPv6 to be enabled.
--trust-servers[=TRUST_SPEC]β grant or revoke trust in compile-servers, specified using--use-serveras specified by TRUST_SPEC, where TRUST_SPEC is a comma-separated list specifying the trust which is to be granted or revoked. Supported elements are:sslβ trust the specified servers as SSL peers.signerβ trust the specified servers as module signers (see--privilege). Only root can specifysigner.all-usersβ grant trust as an ssl peer for all users on the local host. The default is to grant trust as an ssl peer for the current user only. Trust as a module signer is always granted for all users. Only root can specifyall-users.revokeβ revoke the specified trust. The default is to grant it.no-promptβ do not prompt the user for confirmation before carrying out the requested action. The default is to prompt the user for confirmation.
If no argument is provided, then the default is ssl. If no servers were specified using --use-server, then no trust will be granted or revoked.
And unless no-prompt has been specified, the user will be prompted to confirm the trust to be granted or revoked before the operation is performed π¬
--sign-moduleβ sign the module with a MOK (Machine Owner Key) on UEFI/SecureBoot systems π. See the SECUREBOOT section for more details.--dump-probe-typesβ dumps a list of supported probe types and exits. If--privilege=stapusris also specified, the list will be limited to probe types available to unprivileged users.--dump-probe-aliasesβ dumps a list of all probe aliases found in library files and exits.--dump-functionsβ dumps a list of all the public functions found in library files and exits. Also includes their parameters and types. A function of type'unknown'indicates a function that does not return a value. Note that not all function/parameter types may be resolved (these are also shown by'unknown'). This feature is very memory-intensive and thus may not work properly with--use-serverif the target server imposes an rlimit on process memory (i.e. through the~stap-server/.systemtap/rcconfiguration file, seestap-server(8)).--remote URLβ set the execution target to the given host. This option may be repeated to target multiple execution targets π―. Passes 1-4 are completed locally as normal to build the script, and then pass 5 will copy the module to the target and run it. Acceptable URL forms include:[USER@]HOSTNAME,ssh://[USER@]HOSTNAMEβ this mode uses ssh, optionally using a username not matching your own. If a customssh_configfile is in use, addSendEnv LANGto retain internationalization functionality.
okay so these are the other ways to point --remote at a target, bestie β pick your fighter:
libvirt://DOMAIN,libvirt://DOMAIN/LIBVIRT_URIβ this mode usesstapvirtto run your script on a domain that libvirt is managing. If you want, you can hand over aLIBVIRT_URIto connect to a specific driver and/or a remote host. Like, to hit the local privileged QEMU driver, you'd do:
--remote libvirt://MyDomain/qemu:///system
The supported URIs live at http://libvirt.org/uri.html. And go peep stapvirt(1) for the whole tea on prepping your domain for stap probing. π«Ά
unix:PATHβ this one connects to a UNIX socket. Perfect when you're pairing it with a QEMU virtio-serial port so you can execute scripts inside a running virtual machine. β¨direct://β special loopback mode, just runs on the local host. Simple, iconic, no notes.
--remote-prefixβ slaps a prefix on every line of remote output in the form"N: ", whereNis the index of the remote execution target that line came from. So you always know who said what. π--download-debuginfo[=OPTION]β turns the abrt auto-debuginfo-downloading feature on, off, or sets a timeout for it, depending on whatOPTIONyou give it. AndOPTIONis one of these:yesβ enable automatic debuginfo downloading, no timeout. Literally the same as giving--download-debuginfowith noOPTIONvalue at all.noβ explicitly disable the automatic downloading. Same as not using the option at all. (yes, fr, it's the "off switch" that's identical to never touching it π)askβ show abrt's output and ask before continuing the download. No timeout gets set here.<timeout>β give a positive number and it'll stop the download if it's taking longer than<timeout>seconds. Patience has limits, periodt.
--rlimit-as=NUMβ sets the maximum size of the process's virtual memory (address space), in bytes.--rlimit-cpu=NUMβ sets the CPU time limit, in seconds.--rlimit-nproc=NUMβ sets the max number of processes that can be created.--rlimit-stack=NUMβ sets the max size of the process stack, in bytes.--rlimit-fsize=NUMβ sets the max size of files the process is allowed to create, in bytes.--sysroot=DIRβ tells it where the target files (executables, libraries, etc.) are chillin'. If you pair this with-r RELEASE, the sysroot gets searched for the right kernel build directory. But with-r /DIR? Nah β the sysroot won't be used to find the kernel build. Noted. π--sysenv=VAR=VALUEβ gives an alternate value for an environment variable when the value on a remote system is different. Path variables (thinkPATH,LD_LIBRARY_PATH) are assumed to be relative to the directory you gave with--sysroot, if you gave one.--suppress-time-limitsβ disables the-DSTP_OVERLOADrelated options, plus-DMAXACTIONand-DMAXTRYLOCK. Heads up bestie: this one requires guru mode. π€--runtime=MODEβ sets the pass-5 runtime mode. The valid options arekernel(that's the default),dyninstandbpf. Scroll down to ALTERNATE RUNTIMES for the full story.--dyninstβ shorthand for--runtime=dyninst. We love a shortcut. π--bpfβ shorthand for--runtime=bpf.--save-uprobesβ on machines that need SystemTap to build its own uprobes module (kernels before version 3.5, iykyk), this tells SystemTap to also save a copy of the module in the current directory β and yes, it makes a fresh"uprobes"directory first. πΈ--target-namespaces=PIDβ lets you set a whole set of target namespaces based on the namespaces that the givenPIDis in. This is for namespace-aware tapset functions. If you never set the target namespaces, it just defaults to the stap process's own namespaces.--monitor=INTERVALβ opens up an interface showing you status info about the module (uptime, module name, invoker uid, memory sizes, global variables, and a list of probes with their stats). You can optionally passINTERVALto set the refresh rate of the status window, in seconds. You can also drive the module with a bunch of commands using these keys:cβ resets all global variables to their initial values, or zeros them out if they didn't have an initial value.sβ rotates the attribute used to sort the list of probes.tβ brings up a prompt so you can toggle probes on/off by index. (Probe points are still affected by their conditions, so don't get it twisted.)rβ resumes the script by toggling on all probes.pβ pauses the script by toggling off all probes.xβ hides/shows the status window, so you can actually see more output. πnavigation-keysβ these scroll up and down the windows.Tabβ toggles scrolling between the status and output windows.
--exampleβ runs example scripts without you having to type out the whole entire path to the script. The example scripts live in the directory named in thestappaths(7)manual page. β¨--no-global-var-displayβ disables the automatic logging of unused global variables at the end of a stap session. Bye, clutter.--language-serverβ language server mode. It starts a language server that chats via stdio. The language server respects stap verbosity, so it's on the same wavelength. π§--build-asβ executes passes 1-4 under a specified user, to increase safety. Fair warning bestie: this approach may have limitations. Unprivileged users might not have access tokallsymsor/proc. At RPM install time, thestapunprivuser gets created, so stap can be invoked with--build-as=stapunpriv. π
π ARGUMENTS π
Any extra arguments you drop on the command line get passed to the script parser for substitution. The deets are below. β
π SCRIPT LANGUAGE π
The systemtap script language gives major awk and C energy. There are two main outermost constructs: probes and functions. Inside those, statements and expressions use C-like operator syntax and precedence. It's giving familiar but make it systemtap.
π GENERAL SYNTAX π
Whitespace is ignored, so format it however your heart desires. Three forms of comments are supported:
# ... shell style, to the end of line, except for $# and @#
// ... C++ style, to the end of line
/* ... C style ... */
Literals are either strings in double-quotes (which pass through the usual C escape codes with backslashes, and adjacent string literals get glued together, also as in C), or integers (in decimal, hexadecimal, or octal, using the same notation as C). All strings are limited in length to some reasonable value β like a few hundred bytes. Integers are 64-bit signed quantities, although the parser also accepts (and wraps around) values above positive 2**63. Slay, but careful. π
On top of that, script arguments given at the end of the command line can be inserted. Use $1 ... $<NN> for insertion unquoted, and @1 ... @<NN> for insertion as a string literal. You can grab the number of arguments through $# (as an unquoted number) or through @# (as a quoted number). These work anywhere a token can begin, including inside the preprocessing stage. And referencing an argument number beyond what you actually gave? That's an error. π
β¨ PREPROCESSING β¨
A simple conditional preprocessing stage runs as part of parsing. The general form is similar to the cond ? exp1 : exp2 ternary operator:
%( CONDITION %? TRUE-TOKENS %)
%( CONDITION %? TRUE-TOKENS %: FALSE-TOKENS %)
The CONDITION is either an expression whose format is determined by its first keyword, or a string literals comparison, or a numeric literals comparison. You can also stack up a bunch of alternatives and conjunctions of CONDITIONs (same meaning as in the previous sentence) using || and &&. But β parentheses aren't supported yet, so remembering that conjunction takes precedence over alternative is lowkey important. π
If the first part is the identifier kernel_vr or kernel_v to refer to the kernel version number β with ("2.6.13-1.322FC3smp") or without ("2.6.13") the release code suffix β then the second part is one of the six standard numeric comparison operators <, <=, ==, !=, >, and >=, and the third part is a string literal holding an RPM-style version-release value. The condition is satisfied if the version of the target kernel (optionally overridden by the -r option) compares to the given version string. The comparison is done by the glibc function strverscmp. Special case: if the operator is simple equality (==) or inequality (!=), and the third part contains any wildcard characters (* or ? or [), then the expression is treated as a wildcard (mis)match, evaluated by fnmatch. π
If, on the other hand, the first part is the identifier arch to refer to the processor architecture (as named by the kernel build system ARCH/SUBARCH), then the second part is one of the two string comparison operators == or !=, and the third part is a string literal to match against. This comparison is a wildcard (mis)match.
Same energy: if the first part is an identifier like CONFIG_something to refer to a kernel configuration option, then the second part is == or !=, and the third part is a string literal for matching the value (commonly "y" or "m"). Nonexistent or unset kernel configuration options are represented by the empty string. This comparison is also a wildcard (mis)match. π¦
If the first part is the identifier systemtap_v, the test refers to the systemtap compatibility version, which may be overridden for old scripts with the --compatible flag. The comparison operator works just like it does for kernel_v, and the right operand is a version string. Also peep the DEPRECATION section below.
If the first part is the identifier systemtap_privilege, the test refers to the privilege level the systemtap script is compiled with. Here the second part is == or !=, and the third part is a string literal β either "stapusr" or "stapsys" or "stapdev".
And if the first part is the identifier guru_mode, the test refers to whether the systemtap script is compiled with guru_mode. Here the second part is == or !=, and the third part is a number, either 1 or 0. Periodt. π
If that first part is the identifier runtime, bestie, then the whole test is about the systemtap runtime mode. The ALTERNATE RUNTIMES section further down has all the tea on runtimes π«. The second part is one of the two string comparison operators == or !=, and the third part is a string literal you're matching it against. And ngl, this comparison is a wildcard (mis)match, so don't come in here expecting exact strings.
Otherwise? The CONDITION is expected to be a comparison between two string literals or two numeric literals. In that case the arguments are the only variables usable β that's the whole guest list, nobody else got an invite π
.
The TRUE-TOKENS and FALSE-TOKENS are zero or more general parser tokens (nested preprocessor conditionals absolutely allowed in there, it's giving inception), and they get passed into the input stream depending on whether the condition came out true or false. For example, this next bit induces a parse error unless the target kernel version is newer than 2.6.5:
%( kernel_v <= "2.6.5" %? **ERROR** %) # invalid token sequence
And this one might adapt to hypothetical kernel version drift:
probe kernel.function (
%( kernel_v <= "2.6.12" %? "__mm_do_fault" %:
%( kernel_vr == "2.6.13*smp" %? "do_page_fault" %:
UNSUPPORTED %) %)
) { /* ... */ }
%( arch == "ia64" %?
probe syscall.vliw = kernel.function("vliw_widget") {}
%)
π PREPROCESSOR MACROS π
Ok so the preprocessor ALSO supports a simple macro facility, and it runs as a separate pass before conditional preprocessing. Two passes, two vibes, no cap.
Macros get defined using this construct right here:
@define NAME %( BODY %)
@define NAME(PARAM_1, PARAM_2, ...) %( BODY %)
Macros, and parameters inside a macro body, are both invoked by prefixing the macro name with an @ symbol. Like so:
@define foo %( x %)
@define add(a,b) %( ((@a)+(@b)) %)
@foo = @add(2,2)
β οΈ Macro expansion is currently performed in a separate pass before conditional compilation. Which means β bestie, listen β bothTRUE- andFALSE-tokens in conditional expressions will be macroexpanded regardless of how the condition is actually evaluated. And yeah, that can sometimes lead to errors:
// The following results in a conflict:
%( CONFIG_UPROBE == "y" %?
@define foo %( process.syscall %)
%:
@define foo %( **ERROR** %)
%)
// The following works properly as expected:
@define foo %(
%( CONFIG_UPROBE == "y" %? process.syscall %: **ERROR** %)
%)
The first example is incorrect because both @defines are evaluated in a pass prior to the conditional being evaluated. The second one gets it right by moving the conditional inside the macro body. Order of operations really said "main character energy" here π.
Normally, a macro definition is local to the file it occurs in. So defining a macro in a tapset does not make it available to the user of the tapset β sorry bestie, it's not yours. Publically available library macros can be defined by including .stpm files on the tapset search path. These files may only contain @define constructs, which become visible across all tapsets and user scripts. And optionally, within the .stpm files, a public macro definition can be surrounded by a preprocessor conditional, as described above. Fancy β¨.
β¨ CONSTANTS β¨
Tapsets or guru-mode user scripts can access header file constant tokens β typically macros β using the built-in @const() operator. The respective header file inclusion is possible either via the tapset library, or by using a top-level guru mode embedded-C construct. This results in appropriate embedded C pragma comments setting. Look at it:
@const("STP_SKIP_BADVARS")
Enumeration constants from debugged programs can be accessed using the built-in @enum() operator. This operator looks up the enumeration constant name in DWARF debug information and replaces it with its integer value. It's giving "I know a guy" π
:
@enum("MY_ENUM_CONSTANT")
The reverse mapping is available via @enumname(), which turns an integral rvalue into the enumerator name string. The enumeration type is taken from a typed context variable, or from optional type and module string arguments (same shape as @cast). Values that do not match any enumerator are rendered as a decimal string. No match, no name, just numbers:
@enumname($state)
@enumname(flags, "enum foo", "kernel")
π¦ VARIABLES π¦
Identifiers for variables and functions are an alphanumeric sequence, and may include _ and $ characters. They may not start with a plain digit, as in C. Each variable is by default local to the probe or function statement block within which it is mentioned, and therefore its scope and lifetime is limited to a particular probe or function invocation. Blink and it's gone, honestly.
Scalar variables are implicitly typed as either string or integer. Associative arrays also have a string or integer value, and a tuple of strings and/or integers serving as a key. Here are a few basic expressions, eat them up:
var1 = 5
var2 = "bar"
array1 [pid()] = "name" # single numeric key
array2 ["foo",4,i++] += 5 # vector of string/num/num keys
if (["hello",5,4] in array2) println ("yes") # membership test
The translator performs type inference on all identifiers, including array indexes and function parameters. Inconsistent type-related use of identifiers signals an error. So don't be chaotic about it, the translator will notice.
Variables may be declared global, so that they're shared amongst all probes and functions and live as long as the entire systemtap session. There is one namespace for all global variables, regardless of which script file they are found within. Concurrent access to global variables is automatically protected with locks β see the SAFETY AND SECURITY section for more details, it's important fr fr. A global declaration may be written at the outermost level anywhere, not within a block of code. Global variables which are written but never read will be displayed automatically at session shutdown (yes, it will snitch on you π). The translator will infer for each its value type, and if it is used as an array, its key types. Optionally, scalar globals may be initialized with a string or number literal. The following declaration marks variables as global:
global var1, var2, var3=4
Global variables can also be set as module options. One can do this by either using the -G option, or the module must first be compiled using stap -p4. Global variables can then be set on the command line when calling staprun on the module generated by stap -p4. See staprun(8) for more information. Two-step process, but it slays π«Ά.
The scope of a global variable may be limited to a tapset or user script file using the private keyword. The global keyword is optional when defining a private global variable. Following declaration marks var1 and var2 private globals:
private global var1=2
private var2
Arrays are limited in size by the MAXMAPENTRIES variable β see the SAFETY AND SECURITY section for details. Optionally, global arrays may be declared with a maximum size in brackets, overriding MAXMAPENTRIES for that array only. Note that this doesn't indicate the type of keys for the array, just the size. Size β shape, okurrr:
global tiny_array[10], normal_array, big_array[50000]
Arrays may be configured for wrapping using the % suffix. This causes older elements to be overwritten if more elements are inserted than the array can hold. This works for both associative and statistics typed arrays. Out with the old, in with the new π
:
global wrapped_array1%[10], wrapped_array2%
Many types of probe points provide context variables, which are run-time values, safely extracted from the kernel or userspace program being probed. These are prefixed with the $ character. The CONTEXT VARIABLES section in stapprobes(3stap) lists what's available for each type of probe point. These context variables become normal string or numeric scalars once they are stored in normal script variables. See the TYPECASTING section below on how to to turn them back into typed pointers for further processing as context variables. There is some automation to help! π
π STATEMENTS π
Statements enable procedural control flow. They may occur within functions and probe handlers. The total number of statements executed in response to any single probe event is limited to some number defined by the MAXACTION macro in the translated C code, and is in the neighbourhood of 1000. So like, budget your statements bestie, it's not infinite.
EXPβ execute the string- or integer-valued expression and throw away the value. Use it, lose it, no refunds.{ STMT1 STMT2 ... }β execute each statement in sequence in this block. Note that separators or terminators are generally not necessary between statements. Comfy.;β null statement, do nothing. It's useful as an optional separator between statements to improve syntax-error detection and to handle certain grammar ambiguities. A whole mood.if (EXP) STMT1 [ else STMT2 ]β compare integer-valuedEXPto zero. Execute the first (non-zero) or secondSTMT(zero).while (EXP) STMTβ while integer-valuedEXPevaluates to non-zero, executeSTMT. Loop-de-loop π.for (EXP1; EXP2; EXP3) STMTβ executeEXP1as initialization. WhileEXP2is non-zero, executeSTMT, then the iteration expressionEXP3.foreach (VAR in ARRAY [ limit EXP ]) STMTβ loop over each element of the named global array, assigning current key toVAR. The array may not be modified within the statement. By adding a single+or-operator after theVARor theARRAYidentifier, the iteration will proceed in a sorted order, by ascending or descending index or value. If the array contains statistics aggregates, adding the desired@operatorbetween theARRAYidentifier and the+or-will specify the sorting aggregate function. See the STATISTICS section below for the ones available. Default is@count. Using the optionallimitkeyword limits the number of loop iterations toEXPtimes.EXPis evaluated once at the beginning of the loop.foreach ([VAR1, VAR2, ...] in ARRAY [ limit EXP ]) STMTβ same as above, used when the array is indexed with a tuple of keys. A sorting suffix may be used on at most oneVARorARRAYidentifier.foreach ([VAR1, VAR2, ...] in ARRAY [INDEX1, INDEX2, ...] [ limit EXP ]) STMTβ same as above, where iterations are limited to elements in the array where the keys match the index values specified. The symbol*can be used to specify an index and will be treated as a wildcard.foreach (VAR0 = VAR in ARRAY [ limit EXP ]) STMTβ this variant offoreachsaves current value intoVAR0on each iteration, so it is the same asARRAY[VAR]. This also works with a tuple of keys. Sorting suffixes onVAR0have the same effect as onARRAY.foreach (VAR0 = VAR in ARRAY [INDEX1, INDEX2, ...] [ limit EXP ]) STMTβ literally the same as the one right above π except the loop only visits the elements in the array whose keys match the index values you spelled out. And yes bestie, you can drop a*in as an index and it gets treated as a wildcard β¨.break,continueβ bounce out of, or jump to the next round of, the innermost nesting loop (sowhile,for, orforeach). That's it, that's the whole job π«Ά.return EXPβ handsEXPback as the value of the enclosing function. If nobody ever takes that function's value, you don't even need areturnβ the function just gets a special "unknown" type with no return value. Vibes only π .nextβ peaces out of the enclosing probe handler right now. This is especially the move in probe aliases that apply event filtering predicates. And when you use it inside functions, execution gets immediately handed over to the next overloaded function. Slay β¨.try { STMT1 } catch { STMT2 }β runs the first block, and if any run-time errors show up, it abortsSTMT1and starts runningSTMT2. Any errors insideSTMT2will propagate up to outer try/catch blocks, if there are any. No cap.try { STMT1 } catch(VAR) { STMT2 }β same thing as above, plus it assigns the error message to the string scalar variableVARπ.delete ARRAY[INDEX1, INDEX2, ...]β removes the element specified by the index tuple fromARRAY. If the index tuple has a*where an index should be, that*is treated as a wildcard and all the elements with keys matching the index tuple get removed fromARRAY. The value is no longer available and later iterations won't report the element. And ngl, it is not an error to delete an element that doesn't exist π.delete ARRAYβ removes all elements fromARRAY. Clean slate, periodt π .delete SCALARβ removes the value ofSCALAR. Integers and strings get cleared to0and""respectively, while statistics are reset to the initial empty state πΈ.
β¨ EXPRESSIONS β¨
Systemtap supports a bunch of operators that have the same general syntax, semantics, and precedence as in C and awk. Arithmetic is performed as per typical C rules for signed integers. And heads up: division by zero or overflow is detected and results in an error. Watch it π.
binary numeric operators
* / % + - >> << & ^ | && ||
binary string operators
. (string concatenation)
numeric assignment operators
= *= /= %= += -= >>= <<= &= ^= |=
string assignment operators
= .=
unary numeric operators
+ - ! ~ ++ --
binary numeric, string comparison or regex matching operators
< > <= >= == != =~ !~
ternary operator
cond ? exp1 : exp2
grouping operator
( exp )
function call
fn ([ arg1, arg2, ... ])
array membership check
exp in array
[exp1, exp2, ... ] in array
[*, *, ... ] in array
π¦ REGULAR EXPRESSION MATCHING π¦
The scripting language supports regular expression matching, bestie. The basic syntax is giving:
exp =~ regex
exp !~ regex
(The first operand must be an expression evaluating to a string; the second operand must be a string literal containing a syntactically valid regular expression.) π
The regular expression syntax supports POSIX Extended Regular Expression features as documented in grep(1) β with one exception: subexpression reuse ("\1") functionality is not supported. Sad but true π.
After a successful match, the contents of the matched string and subexpressions can be extracted using the matched() and ngroups() tapset functions, like this:
if ("an example string" =~ "str(ing)") {
matched(0) // -> returns "string", the matched substring
matched(1) // -> returns "ing", the 1st matched subexpression
ngroups() // -> returns 2, the number of matched groups
}
π₯ PROBES π₯
The main construct in the scripting language identifies probes. Probes associate abstract events with a statement block (a "probe handler") that gets executed when any of those events occur. The general syntax is as follows:
probe PROBEPOINT [, PROBEPOINT] { [STMT ...] }
probe PROBEPOINT [, PROBEPOINT] if (CONDITION) { [STMT ...] }
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 further ones using aliases. Probe points may be wildcarded, grouped, or listed in preference sequences, or declared optional. More deets on probe point syntax and semantics live on the stapprobes(3stap) manual page π.
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 spot. These "context variables" are presented to the script as variables whose names are prefixed with $. They may be accessed only if the kernel's compiler preserved them despite optimization β same constraint a debugger user faces when working with optimized code π« . On top of that, the objects must exist in paged-in memory at the moment of the systemtap probe handler's execution, because systemtap must not cause (suppresses) any additional paging. Some probe types have very little context. Peep the stapprobes(3stap) man pages to see the kinds of context variables available at each kind of probe point. As of systemtap version 4.3, functions called from the handlers of some probe point types may also refer to context variables. These are treated as if a clone of that function was inlined into the calling probe handler and $variables evaluated in its context. Iconic β¨.
Probes may be decorated with an arming condition, consisting of a simple boolean expression on read-only global script variables. While disarmed (inactive, condition evaluates to false), some probe types reduce or eliminate their run-time overheads. When an arming condition evaluates to true, probes will be soon re-armed, and their probe handlers will start getting called as the events fire. (Some events may be lost during the arming interval. If this is unacceptable, do not use arming conditions for those probes.) Example of the syntax:
probe timer.us(TIMER) if (enabled) {
}
New probe points may be defined using "aliases". Probe point aliases look similar to probe definitions, but instead of activating a probe at the given point, they just define a new probe point name as an alias to an existing one. There are two types of alias, i.e. the prologue style and the epilogue style, which are identified by = and += respectively.
For 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. While for the epilogue style alias, the statement block that follows an alias definition is implicitly added as an epilogue to any probe that refers to the alias. For example:
probe syscall.read = kernel.function("sys_read") {
fildes = $fd
if (execname() == "init") next # skip rest of probe
}
defines a new probe point syscall.read, which expands to kernel.function("sys_read"), with the given statement as a prologue, which is useful to predefine some variables for the alias user and/or to skip probe processing entirely based on some conditions. And
probe syscall.read += kernel.function("sys_read") {
if (tracethis) println ($fd)
}
defines a new probe point with the given statement as an epilogue, which is useful to take actions based upon variables set or left over by the alias user. Please note that in each case, the statements in the alias handler block are treated ordinarily, so that variables assigned there constitute mere initialization, not a macro substitution π.
Aliases can also be defined to include both a prologue and an epilogue.
probe syscall.read = kernel.function("sys_read") {
fildes = $fd
if (execname() == "init") next
},{
if (tracethis) println ($fd)
}
An alias is used just like a built-in probe type.
probe syscall.read {
printf("reading fd=%d\n", fildes)
if (fildes > 10) tracethis = 1
}
Probes with an alias can make use of the @probewrite predicate. This check is used to detect whether a script variable or target variable has been written to in the probe handler body π
.
@probewrite(var)
expands to 1 iff var has been written to in the probe handler body, otherwise it expands to 0.
In the following example, @probewrite(var) expands to 1 because var has been written to in the probe handler body and consequently, the conditional statement will run.
probe foo = begin { var = 0 }, { if (@probewrite(var)) println(var) }
probe foo {
var = 1
}
π FUNCTIONS π
Systemtap scripts may define subroutines to factor out common work. Functions take any number of scalar (integer or string) arguments, and must return a single scalar (integer or string). An example function declaration looks like this:
function thisfn (arg1, arg2) {
return arg1 + arg2
}
Note the general absence of type declarations, which are instead inferred by the translator π§. However, if you want, a function definition may include explicit type declarations for its return value and/or its arguments. This is especially 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 sprint(arg1) . arg2
}
Functions may call others or themselves recursively, up to a fixed nesting limit. This limit is defined by the MAXNESTING macro in the translated C code and is in the neighbourhood of 10. So like, don't go wild π« .
Functions may be marked private using the private keyword to limit their scope to the tapset or user script file they are defined in. An example definition of a private function follows:
private function three:long () { return 3 }
Functions terminating without reaching an explicit return statement will return an implicit 0 or "", determined by type inference. It's giving autopilot πΈ.
Functions may be overloaded during both runtime and compile time.
Runtime overloading allows the executed function to be selected while the module is running based on runtime conditions, and is achieved using the "next" statement in script functions and STAP_NEXT macro for embedded-C functions. For example,
function f() { if (condition) next; print("first function") }
function f() %{ STAP_NEXT; print("second function") %}
function f() { print("third function") }
So when you call f() like that, the execution lowkey bounces to the third function if condition evaluates to true, and it prints "third function". π
And notice how the second function is unconditionally nexted β like it just dips out, no questions asked, no conditions, periodt.
Parameter overloading is what lets the translator pick which function runs at compile time</>, based on how many args you handed the functioncall. Watch:
function g() { print("first function") }
function g(x) { print("second function") }
g() -> "first function"
g(1) -> "second function"
Okay but real talk β runtime overloading does not occur in the example above, because exactly one function gets resolved for the functioncall. If you use a next statement inside a function and there are no more overloads left, that triggers a runtime exception. π Runtime overloading only happens when the functions have the same arity β functions sharing a name but with different numbers of parameters are completely unrelated to each other. Fr fr.
Execution order? Determined by a priority value which you may specify. And if you don't specify an explicit priority, user script functions get a higher priority than library functions β user script functions default to 0, library functions default to 1. Functions with the same priority run in declaration order. Like so:
function f():3 { if (condition) next; print("first function") }
function f():1 { if (condition) next; print("second function") }
function f():2 { print("third function") }
Since the second function has the highest priority, it gets executed first. β¨ And the first function is never executed, because there are no next statements in the third function to transfer execution along. It's giving ghosted. π»
π¨οΈ PRINTING π¨οΈ
There's a whole set of function names that the translator treats extra specially. They format values for printing to the standard systemtap output stream in a way that's way more convenient (heads up bestie: data generated in the kernel module has to get transferred to user-space before it can actually be printed).
The sprint* variants return the formatted string instead of printing it. Iconic.
print,sprintβ prints one or more values of any type, concatenated directly together.println,sprintlnβ prints values likeprintandsprint, but also appends a newline. π«Άprintd,sprintdβ takes a string delimiter and two or more values of any type, and prints the values with the delimiter interposed. The delimiter must be a literal string constant.printdln,sprintdlnβ prints values with a delimiter likeprintdandsprintd, but also appends a newline.printf,sprintfβ takes a formatting string and a number of values of corresponding types, and prints them all. The format must be a literal string constant.
The printf formatting directives are similar to those of C, except that they're fully type-checked by the translator. No cap, that's a glow-up:
%bβ writes a binary blob of the value given, instead of ASCII text. The width specifier determines the number of bytes to write; valid specifiers are%b%1b%2b%4b%8b. Default (%b) is 8 bytes.%cβ character.%d,%iβ signed decimal.%mβ safely reads kernel (without#) or user (with#) memory at the given address, and outputs its content. The optional precision specifier (not field width) determines the number of bytes to read β default is 1 byte.%10.4mprints 4 bytes of the memory in a 10-character-wide field. Note: on some architectures, user memory can still be read without#.%Mβ same as%m, but outputs in hexadecimal. The minimal size of output is double the optional precision specifier β default is 1 byte (2 hex chars).%10.4Mprints 4 bytes of the memory as 8 hexadecimal characters in a 10-character-wide field.%.*Mhex-dumps a given number of bytes from a given buffer.%oβ unsigned octal.%pβ unsigned pointer address.%sβ string.%uβ unsigned decimal.%xβ unsigned hex value, in all lower-case.%Xβ unsigned hex value, in all upper-case.%%β writes a%.
The # flag selects the alternate forms. For octal, this prefixes a 0. For hex, this prefixes 0x or 0X, depending on case. For characters, this escapes non-printing values with either C-like escapes or raw octal. And in the case of %#m/%#M, this safely accesses user space memory rather than kernel space memory. π
Examples, because seeing it is believing:
a = "alice", b = "bob", p = 0x1234abcd, i = 123, j = -1, id[a] = 1234, id[b] = 4567
print("hello")
Prints: hello
println(b)
Prints: bob\n
println(a . " is " . sprint(16))
Prints: alice is 16
foreach (name in id) printdln("|", strlen(name), name, id[name])
Prints: 5|alice|1234\n3|bob|4567
printf("%c is %s; %x or %X or %p; %d or %u\n",97,a,p,p,p,j,j)
Prints: a is alice; 1234abcd or 1234ABCD or 0x1234abcd; -1 or 18446744073709551615\n
printf("2 bytes of kernel buffer at address %p: %2m", p, p)
Prints: 2 byte of kernel buffer at address 0x1234abcd: <binary data>
printf("%4b", p)
Prints (these values as binary data): 0x1234abcd
printf("%#o %#x %#X\n", 1, 2, 3)
Prints: 01 0x2 0X3
printf("%#c %#c %#c\n", 0, 9, 42)
Prints: \000 \t *
π STATISTICS π
Okay so it is often desirable to collect statistics in a way that avoids the penalties of repeatedly exclusively locking the global variables those numbers are being put into. (Yes, that sentence is a mouthful, breathe.) Systemtap provides a solution using a special operator to accumulate values, plus several pseudo-functions to extract the statistical aggregates. πΈ
The aggregation operator is <<<, and it resembles an assignment, or a C++ output-streaming operation. The left operand specifies a scalar or array-index lvalue, which must be declared global. The right operand is a numeric expression. The meaning is intuitive: add the given number to the pile of numbers you're computing statistics of. (The specific list of statistics to gather is given separately, by the extraction functions.) Obsessed with the ergonomics honestly:
foo <<< 1
stats[pid()] <<< memsize
The extraction functions are special too. For each appearance of a distinct extraction function operating on a given identifier, the translator arranges to compute a set of statistics that satisfy it. So the statistics system is "on-demand". Each execution of an extraction function causes the aggregation to be computed for that moment, across all processors.
Here's the whole set of extractor functions. The first argument of each is the same style of lvalue used on the left hand side of the accumulate operation. The @count(v), @sum(v), @min(v), @max(v), @avg(v), @variance(v[, b]) extractor functions compute the number / total / minimum / maximum / average / variance of all accumulated values. All the resulting values are simple integers. Arrays containing aggregates may be sorted and iterated β see the foreach construct above. π«
Variance uses Welford's online algorithm. The calculations are based on integer arithmetic, so they may suffer from low precision and overflow. To improve this, @variance(v[, b]) accepts an optional parameter b, the bit-shift, ranging from 0 (default) to 62, for internal scaling. Only one value of bit-shift may be used with a given global variable. A larger bitshift value increases precision, but also increases the likelihood of overflow. π
$ stap -e \
> 'global x probe oneshot { for(i=1;i<=5;i++) x<<<i println(@variance(x)) }'
12
$ stap -e \
> 'global x probe oneshot { for(i=1;i<=5;i++) x<<<i println(@variance(x,1)) }'
2
$ python3 -c 'import statistics; print(statistics.variance([1, 2, 3, 4, 5]))'
2.5
$
Overflow (from internal multiplication of large numbers) may occur and may cause a negative variance result. π Consider normalizing your input data. Adding or subtracting a fixed value from all variance inputs preserves the original variance. Dividing the variance inputs by a fixed value shrinks the original variance by that value squared.
Histograms are also available, but they're more complicated because they have a vector rather than a scalar value. @hist_linear(v,start,stop,interval) represents a linear histogram from "start" to "stop" (inclusive) by increments of "interval". The interval must be positive. Similarly, @hist_log(v) represents a base-2 logarithmic histogram. Printing a histogram with the print family of functions renders a histogram object as a tabular "ASCII art" bar chart. β¨π
probe timer.profile {
x[1] <<< pid()
x[2] <<< uid()
y <<< tid()
}
global x // an array containing aggregates
global y // a scalar
probe end {
foreach ([i] in x @count+) {
printf ("x[%d]: avg %d = sum %d / count %d\n",
i, @avg(x[i]), @sum(x[i]), @count(x[i]))
println (@hist_log(x[i]))
}
println ("y:")
println (@hist_log(y))
}
The counts of each histogram bucket may be individually accessed via the [index] operator. Each bucket is addressed from 1 through N (for each natural bucket). On top of that, bucket #0 counts all the samples beneath the start value, and bucket #N+1 counts all the samples above the stop value. Histogram buckets (including the two out-of-range buckets) may also be iterated with foreach. π
global x
probe oneshot {
x <<< -100
x <<< 1
x <<< 2
x <<< 3
x <<< 100
foreach (bucket in @hist_linear(x,1,3,1))
// expecting 1 out-of-range-low bucket
// 3 payload buckets
// 1 out-of-range-high bucket
printf("bucket %d count %d\n",
bucket, @hist_linear(x,1,3,1)[bucket])
}
π§ TYPECASTING π§
Once a pointer (see the CONTEXT VARIABLES section of stapprobes(3stap)) has been saved into a script integer variable, the translator attempts to keep the type information necessary to access members from that pointer. Bestie, it's literally keeping receipts for you. π
π«Ά
okay so the translator tries so hard to track DWARF typing for script variables that got assigned from addresses of context $variables, or from @cast or @var operators. Depending on how messy your script is, that association can spread to related variables, which means you can use -> and [] operators on them just like on the original context variable. slay. Like:
foo = $param->foo; printf("x:%d y:%d\n", foo->x, foo->y)
printf("my value is %d\n", ($type == 42 ? $foo : $bar)->value)
printf("my parent pid is %d\n", task_parent(task_current())->tgid)
But bestie, if that heuristic just doesn't vibe with your script, you hit it with the @cast() operator and tell the translator how to read that number as a typed pointer:
@cast(p, "type_name"[, "module"])->member
That reads p as a pointer to a struct/union named type_name and dereferences the member value. You can chain more ->subfield expressions to dereference even more levels. heads up tho: for direct dereferencing of a pointer you should use {kernel,user}_{char,int,...}($p) instead. (go read stapfuncs(5) for the tea on that.) NOTE: the same dereferencing operator -> handles both direct containment and pointer indirection, and Systemtap figures out which one on its own, no cap. The optional module tells the translator where to look for info about that type. You can list multiple modules with : separators. If you don't specify a module, it defaults either to the probe module for dwarf probes, or to "kernel" for functions and all other probe types.
ngl up through systemtap version 4.2, "kernel" was what got inferred when you left it unspecified. Wanna bring that default back? Use --compatible=4.2.
The translator can also build its own module with type info from a header wrapped in angle brackets, in case the normal debuginfo isn't around. For kernel headers, prefix it with "kernel" so it uses the appropriate build system. All other headers get built with default GCC parameters into a user module. And yes, you can list multiple headers in sequence to resolve a codependency. π
As of systemtap version 5.4, the kernel "<vmlinux.h>" header gets tried before any kernel headers or modules you specified β which lowkey might mean you don't have to list any explicit module or header file names at all for kernel data structures. iconic behavior honestly.
@cast(tv, "timeval", "<sys/time.h>")->tv_sec
@cast(task, "task_struct", "kernel<linux/sched.h>")->tgid
@cast(task, "task_struct",
"kernel<linux/sched.h><linux/fs_struct.h>")->fs->umask
Values you get from @cast can be pretty-printed by the $ and $$ suffix operators, same way as described in the CONTEXT VARIABLES section of the stapprobes(3stap) manual page. π«Ά
When you're in guru mode, the translator will also let scripts assign new values to members of typecasted pointers. guru mode stays guru mode, bestie.
Typecasting is also that girl when you've got void* members whose type might only be determinable at runtime:
probe foo {
if ($var->type == 1) {
value = @cast($var->data, "type1")->bar
} else {
value = @cast($var->data, "type2")->baz
}
print(value)
}
π EMBEDDED C π
When you're in guru mode, the translator accepts embedded C code at the top level of the script. That code goes between %{ and %} markers and gets transcribed verbatim, with zero analysis, in some sequence, into the top level of the generated C code. At the outermost level this is useful for adding #include instructions and any auxiliary definitions that other embedded code is gonna use. β¨
Another place embedded code is allowed is as a function body. In that case the script-language body gets replaced entirely by a piece of C code again wrapped in %{ and %} markers. This C code can do anything reasonable and safe. There are a bunch of undocumented but complex safety constraints on atomicity, concurrency, resource consumption, and run time limits β so yeah, this is an advanced technique, not a beginner vibe.
The memory locations set aside for input and output values are made available to it using macros STAP_ARG_* and STAP_RETVALUE. Errors can be signalled with STAP_ERROR. Output can be written with STAP_PRINTF. The function can return early with STAP_RETURN. Here are some examples:
function integer_ops (val) %{
STAP_PRINTF("%d\n", STAP_ARG_val);
STAP_RETVALUE = STAP_ARG_val + 1;
if (STAP_RETVALUE == 4)
STAP_ERROR("wrong guess: %d", (int) STAP_RETVALUE);
if (STAP_RETVALUE == 3)
STAP_RETURN(0);
STAP_RETVALUE ++;
%}
function string_ops (val) %{
strlcpy (STAP_RETVALUE, STAP_ARG_val, MAXSTRINGLEN);
strlcat (STAP_RETVALUE, "one", MAXSTRINGLEN);
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 have to be inferred by the translator from the call sites for any of this to work. So the user should peek at the C code generated for ordinary script-language functions in order to write compatible embedded-C ones. iykyk π
The last place embedded code is permitted is as an expression rvalue. Here the C code between %{ and %} markers is interpreted as an ordinary expression value. It's assumed to be a normal 64-bit signed number, unless the marker /* string */ is included β in which case it's treated as a string instead. π
function add_one (val) {
return val + %{ 1 %}
}
function add_string_two (val) {
return val . %{ /* string */ "two" %}
}
@define SOME_STAP_MACRO %( %{ SOME_C_MACRO %} %)
probe begin {
printf("SOME_C_MACRO has value: %d\n", @SOME_STAP_MACRO);
}
The embedded-C code may contain markers to assert optimization and safety properties. vibe check time, here's every single one:
/* pure */β means the C code has no side effects and may be elided entirely if its value isn't used by script code./* stable */β means the C code always has the same value (in any given probe handler invocation), so repeated calls may be automatically replaced by memoized values. Such functions must take no parameters, and also be pure./* unprivileged */β means the C code is so safe that even unprivileged users are permitted to use it./* myproc-unprivileged */β means the C code is so safe that even unprivileged users are permitted to use it, provided that the target of the current probe is within the user's own process./* guru */β means the C code is so unsafe that a systemtap user must specify-g(guru mode) to use this. (Tapsets are permitted and presumed to call them safely.)/* unmangled */β in an embedded-C function, means that the legacy (pre-1.8) argument access syntax should be made available inside the function. So on top ofSTAP_ARG_fooandSTAP_RETVALUEyou can also useTHIS->fooandTHIS->__retvaluerespectively inside the function. This is useful for quickly migrating code written for SystemTap version 1.7 and earlier./* pragma:suffix */β emit the file-level containing C code near the end of the resulting kernel module C source file./* unmodified-fnargs */β in an embedded-C function, means that the function arguments are not modified inside the function body./* string */β in embedded-C expressions only, means the expression hasconst char *type and should be treated as a string value, instead of the defaultlongnumeric.
Script-level global variables may be accessed in embedded-C functions and blocks. To read or write the global variable var, the /* pragma:read:var */ or /* pragma:write:var */ marker must be placed first in the embedded-C function or block. This provides the macros STAP_GLOBAL_GET_* and STAP_GLOBAL_SET_* macros to allow reading and writing, respectively. For example:
global var
global var2[100]
function increment() %{
/* pragma:read:var */ /* pragma:write:var */
/* pragma:read:var2 */ /* pragma:write:var2 */
STAP_GLOBAL_SET_var(STAP_GLOBAL_GET_var()+1); //var++
STAP_GLOBAL_SET_var2(1, 1, STAP_GLOBAL_GET_var2(1, 1)+1); //var2[1,1]++
%}
Variables may be read and set in both embedded-C functions and expressions. Strings returned from embedded-C code are decayed to pointers. Variables must also be assigned at script level to allow for type inference. And heads up: map assignment does not return the value written, so chaining does not work. π
β BUILT-INS β
A whole set of builtin probe point aliases is provided by the scripts installed in the directory specified in the stappaths(7) manual page. The functions themselves are described in the stapprobes(3stap) manual page. go look, they're good.
πΈ DEREFERENCING πΈ
Integers can be dereferenced from pointers saved as a script integer variables using the @kderef() or @uderef() operators. @kderef() is the one for kernel space addresses, and @uderef() is for user space addresses.
@kderef(SIZE, addr)
@uderef(SIZE, addr)
This interprets addr as a kernel/user address and reads SIZE bytes starting at that address. SIZE should be either 1, 2, 4 or 8 bytes. no other numbers, bestie, don't try it.
π REGISTERS π
The value stored within a register can be accessed using the @kregister() or @uregister() operators. @kregister() is for kernel space registers, @uregister() is for user space registers. The register you want is specified using its DWARF number. π¦
@kregister(0)
@uregister(5)
π« PROCESSING π«
okay so here's the whole β¨journeyβ¨ of what happens when you run a script, bestie. buckle up, it's giving multi-pass pipeline.
The translator begins pass 1 by parsing the given input script, and all scripts (files named *.stp) found in a tapset directory. The directories listed with -I are processed in sequence, each processed in "guru mode". For each directory, a number of subdirectories are also searched. These subdirectories are derived from the selected kernel version (the -R option), in order to allow more kernel-version-specific scripts to override less specific ones. For example, for a kernel version 2.6.12-23.FC3 the following patterns would be searched, in sequence: 2.6.12-23.FC3/*.stp, 2.6.12/*.stp, 2.6/*.stp, and finally *.stp. Stopping the translator after pass 1 causes it to print the parse trees. π³
In pass 2, the translator analyzes the input script to resolve symbols and types. References to variables, functions, and probe aliases that are unresolved internally are satisfied by searching through the parsed tapset script files. If any tapset script file is selected because it defines an unresolved symbol, then the entirety of that file is added to the translator's resolution queue. This process iterates until all symbols are resolved and a subset of tapset script files is selected. π
Next, all probe point descriptions are validated against the wide variety supported by the translator. Probe points that refer to code locations ("synchronous probe points") require the appropriate kernel debugging information to be installed. In the associated probe handlers, target-side variables (whose names begin with "$") are found and have their run-time locations decoded. π
Next, all probes and functions are analyzed for optimization opportunities, in order to remove variables, expressions, and functions that have no useful value and no side-effect. Embedded-C functions are assumed to have side-effects unless they include the magic string /* pure */. Since this optimization can hide latent code errors such as type mismatches or invalid $context variables, it sometimes may be useful to disable the optimizations with the -u option. π
Finally, all variable, function, parameter, array, and index types are inferred from context (literals and operators). Stopping the translator after pass 2 causes it to list all the probes, functions, and variables, along with all inferred types. Any inconsistent or unresolved types cause an error. π
In pass 3, the translator writes C code that represents the actions of all selected script files, and creates a Makefile to build that into a kernel object. These files are placed into a temporary directory. Stopping the translator at this point causes it to print the contents of the C file. π
In pass 4, the translator invokes the Linux kernel build system to create the actual kernel object file. This involves running make in the temporary directory, and requires a kernel module build system (headers, config and Makefiles) to be installed in the usual spot /lib/modules/VERSION/build. Stopping the translator after pass 4 is the last chance before running the kernel object. This may be useful if you want to archive the file. π¦
In pass 5, the translator invokes the systemtap auxiliary program staprun program for the given kernel object. This program arranges to load the module then communicates with it, copying trace data from the kernel into temporary files, until the user sends an interrupt signal. Any run-time error encountered by the probe handlers, such as running out of memory, division by zero, exceeding nesting or runtime limits, results in a soft error indication. Soft errors in excess of MAXERRORS block of all subsequent probes (except error-handling probes), and terminate the session. Finally, staprun unloads the module, and cleans up. π§Ήβ¨
π ABNORMAL TERMINATION π
One should avoid killing the stap process forcibly, for example with SIGKILL, because the stapio process (a child process of the stap process) and the loaded module may be left running on the system. If this happens, send SIGTERM or SIGINT to any remaining stapio processes, then use rmmod to unload the systemtap module. π«Ά
πΈ EXAMPLES πΈ
See the stapex(3stap) manual page for a brief collection of samples, or a large set of installed samples under the systemtap documentation/testsuite directories. See stappaths(7stap) for the likely location of these on the system. ππ
π CACHING π
The systemtap translator caches the pass 3 output (the generated C code) and the pass 4 output (the compiled kernel module) if pass 4 completes successfully. This cached output is reused if the same script is translated again assuming the same conditions exist (same kernel version, same systemtap version, etc.). Cached files are stored in the $SYSTEMTAP_DIR/cache directory. The cache can be limited by having the file cache_mb_limit placed in the cache directory (shown above) containing only an ASCII integer representing how many MiB the cache should not exceed. In the absence of this file, a default will be created with the limit set to 256MiB. This is a 'soft' limit in that the cache will be cleaned after a new entry is added if the cache clean interval is exceeded, so the total cache size may temporarily exceed this limit. This interval can be specified by having the file cache_clean_interval_s placed in the cache directory (shown above) containing only an ASCII integer representing the interval in seconds. In the absence of this file, a default will be created with the interval set to 300 s. ποΈπ«
π SAFETY AND SECURITY π
Systemtap may be used as a powerful administrative tool. It can expose kernel internal data structures and potentially private user information. (In dyninst runtime mode, this is not the case, see the ALTERNATE RUNTIMES section below.) π«£
The translator asserts many safety constraints during compilation and more during run-time. It aims to ensure that no handler routine can run for very long, allocate boundless memory, perform unsafe operations, or in unintentionally interfere with the system. Uses of script global variables are automatically read/write locked as appropriate, to protect against manipulation by concurrent probe handlers. Locks are taken so as to run the global-variable manipulation portion of probe handlers atomically (locks are taken all-or-none). Deadlocks are detected with timeouts. Use the -t flag to receive reports of excessive lock contention. Experimenting with scripts is therefore generally safe. The guru-mode -g option allows administrators to bypass most safety measures, which permits invasive or state-changing operations, embedded-C code, and increases the risk of upset. By default, overload prevention is turned on for all modules. If you would like to disable overload processing, use the --suppress-time-limits option. β οΈ
Errors that are caught at run time normally result in a clean script shutdown and a pass-5 error message. The --suppress-handler-errors option lets scripts tolerate soft errors without shutting down. π
π PERMISSIONS π
For the normal linux-kernel-module runtime, to run the kernel objects systemtap builds, a user must be one of the following:
- the root user;
- a member of the
stapdevandstapusrgroups; - a member of the
stapsysandstapusrgroups; or - a member of the
stapusrgroup.
The root user or a user who is a member of both the stapdev and stapusr groups can build and run any systemtap script. πͺ
A user who is a member of both the stapsys and stapusr groups can only use pre-built modules under the following conditions:
- The module has been signed by a trusted signer. Trusted signers are normally systemtap compile-servers which sign modules when the
--privilegeoption is specified by the client. See thestap-server(8)manual page for more information. - The module was built using the
--privilege=stapsysor the--privilege=stapusroptions.
Members of only the stapusr group can only use pre-built modules under the following conditions:
- The module is located in the
/lib/modules/VERSION/systemtapdirectory. This directory must be owned by root and not be world writable.
or
- The module has been signed by a trusted signer. Trusted signers are normally systemtap compile-servers which sign modules when the
--privilegeoption is specified by the client. See thestap-server(8)manual page for more information. - The module was built using the
--privilege=stapusroption.
The kernel modules generated by stap program are run by the staprun program. The latter is a part of the Systemtap package, dedicated to module loading and unloading (but only in the white zone), and kernel-to-user data transfer. Since staprun verifies a detached .sgn signature (created by the compile server or stap-sign-module) against certificates in its trust database before loading a module for unprivileged users. By default those signatures use RSA-4096. Set SYSTEMTAP_SIGN_KEY_TYPE to rsa, ml-dsa-44, ml-dsa-65, or ml-dsa-87 before stap-gen-cert to choose NIST FIPS-204 ML-DSA instead (requires NSS with CKM_ML_DSA). Re-authorize the new certificate into the staprun database after regenerating. ML-DSA compile-server certificates may not yet be usable for NSS TLS. π
It would be unwise for a system administrator to add untrusted users to thestapdevorstapusrgroups. bestie. don't do it. π
π¦ SECUREBOOT π¦
If the current system has SecureBoot turned on in the UEFI firmware, all kernel modules must be signed. (Some kernels may allow disabling SecureBoot long after booting with a key sequence such as SysRq-X, making it unnecessary to sign modules.) There are two ways to sign a systemtap module. The systemtap compile server can sign modules with a MOK (Machine Owner Key) that it has in common with a client system. For example:
stap --use-server=HOSTNAME:PORT -e 'SCRIPT'
# If there is no mok key in common with the server's systemtap mok key
# list and the client's mok database then the user is directed by stap
# to invoke:
sudo mokutil --import signing_key.x509
# then after rebooting the system:
stap --use-server=HOSTNAME:PORT -e 'SCRIPT'
# will use the server to build and sign the module and the module will run
# on the client
Another way to sign modules is to use the stap --sign-module option, which uses a MOK on the client system without using a server. For example:
stap --sign-module -e 'SCRIPT'
# If there is no systemtap mok key in the system mok database
# then the user is directed by stap to invoke:
sudo mokutil --import /home/USER/.systemtap/ssl/server/moks/FINGERPRINT/signing_key.x509
# then after rebooting the system:
stap --sign-module -e 'SCRIPT'
# will sign and run the module
See the wiki page for the deets, bestie:
https://sourceware.org/systemtap/wiki/SecureBoot
Some kernels just will not let systemtap guess whether module signing is in effect π. On those machines, set the SYSTEMTAP_SIGN environment variable to any value at all while you're running stap. Literally any value. It just needs to exist.
By default, newly generated Machine Owner Keys are RSA-4096. But here's the thing β kernels that verify modules with NIST FIPS-204 ML-DSA (CONFIG_CRYPTO_MLDSA, and typically CONFIG_MODULE_SIG_KEY_TYPE_MLDSA_44 / _65 / _87) need a MOK that matches. So set SYSTEMTAP_MOK_KEY_TYPE to rsa, ml-dsa-44, ml-dsa-65, or ml-dsa-87 when you're generating a new MOK (for example with --sign-module when no enrolled Systemtap MOK is present). If you leave it unset, stap picks ML-DSA automatically when the target kernel's CONFIG_MODULE_SIG_KEY_TYPE_MLDSA_* is enabled, and RSA otherwise. ML-DSA key generation needs OpenSSL 3.5 or later (OpenSSL 4+ preferred, periodt). After switching algorithms, import the new signing_key.x509 with mokutil --import and reboot. Module signing still uses the kernel's scripts/sign-file against the chosen private key, and the running kernel has to support ML-DSA verification to load those modules. No cap.
β¨ RESOURCE LIMITS β¨
So many of the resource use limits are set by macros in the generated C code π. You can override them with -D flags. Here's a selection, because there are a lot:
MAXNESTINGβ the maximum number of nested function calls. The default is determined by script analysis, plus a lil bonus of 10 slots added for recursive scripts. πMAXSTRINGLENβ maximum length of strings, default128.MAXTRYLOCKβ maximum number of iterations to wait for locks on global variables before declaring possible deadlock and skipping the probe, default1000. πMAXACTIONβ maximum number of statements to execute during any single probe hit (with interrupts disabled), default1000. Note that for straight-through probe handlers that don't have loops or recursion, optimization means this parameter may be interpreted too conservatively.MAXACTION_INTERRUPTIBLEβ maximum number of statements to execute during any single probe hit which is executed with interrupts enabled (likebegin/endprobes), default(MAXACTION * 10).MAXBACKTRACEβ maximum number of stack frames that will be processed by thestapruntime unwinder as produced by the backtrace functions in the[u]context-unwind.stptapsets, default20.MAXMAPENTRIESβ maximum number of rows in any single global array, default2048. Individual arrays can be declared with a bigger or smaller limit instead:
global big[10000],little[5]
or you can denote them with % to make them wrap-around (replace old entries) automatically, like this:
global big%
or both, bestie, go wild. π¦
MAPHASHBIASβ the number of powers-of-two to add or subtract from the natural size of the hash table backing each global associative array. Default is0. Try small positive numbers to get extra performance at the cost of more memory consumption, because that should reduce hash table collisions. Try small negative numbers for the opposite tradeoff.MAXERRORSβ maximum number of soft errors before an exit is triggered, default0, which means the very first error will exit the script. Note that with the--suppress-handler-errorsoption, this limit is not enforced.MAXSKIPPEDβ maximum number of skipped probes before an exit is triggered, default100. Running systemtap with-t(timing) mode gives you more details about skipped probes. With the default-DINTERRUPTIBLE=1setting, probes skipped due to reentrancy are not accumulated against this limit. Note that with the--suppress-handler-errorsoption, this limit is not enforced.MINSTACKSPACEβ minimum number of free kernel stack bytes required in order to run a probe handler, default1024. This number should be large enough for the probe handler's own needs, plus a safety margin. π«ΆMAXUPROBESβ maximum number of concurrently armed user-space probes (uprobes), default somewhat larger than the number of user-space probe points named in the script. This pool needs to be potentially large because individual uprobe objects (about64bytes each) are allocated for each process for each matching script-level probe.STP_EXECTRACEβ enable execution tracing of systemtap scripts. When defined, the generated code will emit a detailed trace of every statement executed in the script to the kernel log (or stderr in dyninst mode). Note: this may generate a massive amount of output. π Like, so much.STP_MAXMEMORYβ maximum amount of memory (in kilobytes) that the systemtap module should use, default unlimited. The memory size includes the size of the module itself, plus any additional allocations. This only tracks direct allocations by the systemtap runtime. It does not track indirect allocations (as done by kprobes/uprobes/etc. internals).STP_OVERLOAD_THRESHOLD,STP_OVERLOAD_INTERVALβ maximum number of machine cycles spent in probes on any cpu per given interval, before an overload condition is declared and the script shut down. The defaults are500million and1billion, so as to limitstapscript cpu consumption at around 50%.STP_PROCFS_BUFSIZEβ size of procfs probe read buffers (in bytes). Defaults toMAXSTRINGLEN. This value can be overridden on a per-procfs file basis using the procfs read probe.maxsize(MAXSIZE)parameter.
With scripts that contain probes on any interrupt path, it's possible that those interrupts may occur in the middle of another probe handler. The probe in the interrupt handler would be skipped in this case, to avoid reentrance. To work around this issue, execute stap with the option -DINTERRUPTIBLE=0 to mask interrupts throughout the probe handler. This does add some extra overhead to the probes, but it may prevent reentrance for common problem cases. However β probes in NMI handlers and in the callpath of the stap runtime may still be skipped due to reentrance. π
In case something goes wrong with stap or staprun after a probe has already started running, you may safely kill both user processes, and remove the active probe kernel module with rmmod. Any pending trace messages may be lost. π
π UNPRIVILEGED USERS
okay bestie, real talk. systemtap can peek into kernel internal data structures and even into potentially private user information. so likeβ¦ obviously the full-power version is locked down π. It's restricted to root and to users who are members of the groups stapdev and stapusr. that's the whole vibe.
but!! a restricted set of systemtap's features can still be made available to trusted, unprivileged users π. Those users are members of the group stapusr only, or members of the groups stapusr and stapsys.
These users can load systemtap modules which have been compiled and certified by a trusted systemtap compile-server. go look at the descriptions of the options --privilege and --use-server. And see README.unprivileged in the systemtap source code for info about setting up a trusted compile server π«Ά.
The restrictions enforced when --privilege=stapsys is specified are designed to prevent unprivileged users from:
- harming the system maliciously.
The restrictions enforced when --privilege=stapusr is specified are designed to prevent unprivileged users from:
- harming the system maliciously.
- gaining access to information which would not normally be available to an unprivileged user.
- disrupting the performance of processes owned by other users of the system. Some overhead to the system in general is unavoidable since the unprivileged user's probes will be triggered at the appropriate times. What we would like to avoid is targeted interruption of another user's processes which would not normally be possible by an unprivileged user.
π΅οΈ PROBE RESTRICTIONS
A member of the groups stapusr and stapsys may use all probe points. slay π
.
A member of only the group stapusr may use only the following probes:
begin,begin(n)end,end(n)error(n)neverprocess.*, where the target process is owned by the user.timer.{jiffies,s,sec,ms,msec,us,usec,ns,nsec}(n)*timer.hz(n)
π SCRIPT LANGUAGE RESTRICTIONS
The following scripting language features are unavailable to all unprivileged users:
- any feature enabled by the Guru Mode (
-g) option. - embedded C code.
β±οΈ RUNTIME RESTRICTIONS
The following runtime restrictions are placed upon all unprivileged users:
- Only the default runtime code (see
-R) may be used.
Additional restrictions are placed on members of only the group stapusr:
- Probing of processes owned by other users is not permitted.
- Access of kernel memory (read and write) is not permitted.
π« COMMAND LINE OPTION RESTRICTIONS
Some command line options provide access to features which must not be available to all unprivileged users:
-gmay not be specified.- The following options may not be used by the compile-server client:
-a, -B, -D, -I, -r, -R
π± ENVIRONMENT RESTRICTIONS
The following environment variables must not be set for all unprivileged users:
SYSTEMTAP_RUNTIME
SYSTEMTAP_TAPSET
SYSTEMTAP_DEBUGINFO_PATH
π§ TAPSET RESTRICTIONS
In general, tapset functions are only available for members of the group stapusr when they do not gather information that an ordinary program running with that user's privileges would be denied access to. no sneaky info grabs, periodt π
.
There are two categories of unprivileged tapset functions. The first category consists of utility functions that are unconditionally available to all users; these include such things as:
cpu:long ()
exit ()
str_replace:string (prnt_str:string, srch_str:string, rplc_str:string)
The second category consists of so-called myproc-unprivileged functions that can only gather information <em>within their own processes</em>. Scripts that wish to use these functions must test the result of the tapset function is_myproc and only call these functions if the result is 1. The script will exit immediately if any of these functions are called by an unprivileged user within a probe within a process which is not owned by that user π. Examples of myproc-unprivileged functions include:
print_usyms (stk:string)
user_int:long (addr:long)
usymname:string (addr:long)
A compile error is triggered when any function not in either of the above categories is used by members of only the group stapusr.
No other built-in tapset functions may be used by members of only the group stapusr.
π ALTERNATE RUNTIMES
As described above, systemtap's default runtime mode involves building and loading kernel modules, with various security tradeoffs presented. Systemtap now includes two new prototype backends: --runtime=dyninst and --runtime=bpf.
--runtime=dyninst uses Dyninst to instrument a user's own processes at runtime. This backend does not use kernel modules, and does not require root privileges, but is restricted with respect to the kinds of probes and other constructs that a script may use. Userspace process.data hardware watchpoints are supported when Dyninst provides them on the host; kernel.data probes are not. dyninst runtime operates in target-attach mode, so it does require a -c COMMAND or -x PID process. For example:
stap --runtime=dyninst -c 'stap -V' \
-e 'probe process.function("main")
{ println("hi from dyninst!") }'
It may be necessary to disable a conflicting selinux check with
# setsebool allow_execstack 1
--runtime=bpf compiles the user script into extended Berkeley Packet Filter (eBPF) programs instead of a kernel module. eBPF programs are verified by the kernel for safety and are executed by an in-kernel virtual machine. This runtime is in an early stage of development and currently lacks support for a number of features available in the default runtime. Please see the stapbpf(8) man page for more information. π
πͺ EXIT STATUS
The systemtap translator generally returns with a success code of 0 if the requested script was processed and executed successfully through the requested pass. Otherwise, errors may be printed to stderr and a failure code is returned. Use -v or -vp N to increase (global or per-pass) verbosity to identify the source of the trouble π.
In listings mode (-l and -L), error messages are normally suppressed. A success code of 0 is returned if at least one matching probe was found.
A script executing in pass 5 that is interrupted with ^C / SIGINT is considered to be successful π.
π DEPRECATION
Over time, some features of the script language and the tapset library may undergo incompatible changes, so that a script written against an old version of systemtap may no longer run. In these cases, it may help to run systemtap with the --compatible VERSION flag, specifying the last known working version. Running systemtap with the --check-version flag will output a warning if any possible incompatible elements have been parsed. Deprecation historical details may be found in the NEWS file.
The purpose of deprecation facility is to improve the experience of scripts written for newer versions of systemtap (by adding better alternatives and removing conflicting or messy older alternatives), while at the same time permitting scripts written for older versions of systemtap to continue running. Deprecation is thus intended a service to users (and an inconvenience to systemtap's developers), rather than the other way around. we love a feature that serves the girlies π«Ά.
Please note that underscore-prefixed identifiers in the tapset sometimes undergo such changes that are difficult to preserve compatibility for, even with the deprecation mechanisms. Avoid relying on these in your scripts; instead propose them for promotion to non-underscored status. no cap.
π FILES
Important files and their corresponding paths can be located in the stappaths (7) manual page.
π SEE ALSO
stapprobes(3stap)function::*(3stap)probe::*(3stap)tapset::*(3stap)stappaths(7)staprun(8)stapdyn(8)systemtap(8)stapvars(3stap)stapex(3stap)stap-server(8)stap-prep(1)stapref(1)awk(1)gdb(1)
π BUGS
Use the Bugzilla link of the project web page or our mailing list. http://sourceware.org/systemtap/, <systemtap@sourceware.org>.
aaaand that's the whole page bestie!! πβ¨ if you read all the way here you're literally the main character of the manpage-reading community, no cap. this was STAP(1) β the systemtap translator page, straight from the systemtap source, dated and versioned like a proper classic (iykyk ππ
). go forth and probe responsibly, and pls don't get yourself banned from stapusr bestie π«Άππ¦
π¦ where this page comes from
- arch rolling: systemtap 5.6-1 Β· GPL-2.0-or-later
- centos-stream 10: systemtap-client 5.6-3.el10 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND GFDL-1.2-or-later AND BSD-2-Clause
- centos-stream 10: systemtap-devel 5.6-3.el10 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND BSD-2-Clause
- centos-stream 9: systemtap-client 5.6-3.el9 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND GFDL-1.2-or-later AND BSD-2-Clause
- centos-stream 9: systemtap-devel 5.6-3.el9 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND BSD-2-Clause
- centos-stream 9: systemtap-devel 5.6-3.el9 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND BSD-2-Clause
- fedora 43: systemtap-client 5.6-1.fc43 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND GFDL-1.2-or-later AND BSD-2-Clause
- fedora 43: systemtap-devel 5.6-1.fc43 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND BSD-2-Clause
- fedora 43: systemtap-devel 5.6-1.fc43 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND BSD-2-Clause
- fedora 44: systemtap-client 5.6-1.fc44 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND GFDL-1.2-or-later AND BSD-2-Clause
- fedora 44: systemtap-devel 5.6-1.fc44 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND BSD-2-Clause
- fedora 44: systemtap-devel 5.6-1.fc44 Β· GPL-2.0-or-later AND GPL-2.0-only AND BSD-3-Clause AND LGPL-2.1-only AND BSD-2-Clause
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms