Wednesday, March 25, 2015

Adding DTrace probes to user applications

The DTrace probes that come bundled with your operating system are extremely helpful, but sometimes they still don't provide us access to the information we need. Common examples of that are leaf or inlined functions, tailcalls or some other type of compiler optimization that strips a function call from our app.

Here's how you can define and add your own DTrace probes to applications.

(a) create a .d file with a probe specification
# cat user_probe_provider.d
provider my_provider {
        probe   main__probe(int, string);
};
(b) add the probe to your c file(s)
#include <sys/sdt.h>

int
main(int argc, char **argv)
{
        char *str = "foo";
        int n = 7;

        DTRACE_PROBE2(my_provider, main__probe, n, str);

        return (0);
}
(c) compile but don't link the application
# cc -c user_probe.c
(d) compile the provider/probe definitions
# dtrace -G -32 -s user_probe_provider.d user_probe.o
(e) build and link everything
# cc -o user_probe user_probe_provider.o user_probe.o
(f) try it out
# dtrace -n 'my_provider$target:::{printf("%d %s\n", arg0, copyinstr(arg1))}' -c ./user_probe

dtrace: description 'my_provider$target:::' matched 1 probe
dtrace: pid 14744 has exited
CPU     ID                    FUNCTION:NAME
  2  92968                  main:main-probe 7 foo


No comments:

Post a Comment