Skip to main content

Imports

ยท 2 min read
Jordan Rome
Software Engineer

This is a continuation of the posts on The Path to 1.0.

Coming in the next release is the ability to import bpftrace scripts into other bpftrace scripts. This new functionality comes on the heels of bpftrace macros, which allow you to factor out common code. Imports were the next logical step to support larger and more complex bpftrace scripts. Instead of shoving all your common code into the top of one script, you can now import them to preserve readability and sharability.

Here is a trivial example:

import "my_library.bt"

begin {
print(add_one(1));
}

And the "my_library.bt" file:

macro add_one(arg) { 1 + 1 }

As you can see, the "my_library.bt" script has no probes. All it does is define a macro "add_one" that is being called from the main script. In fact, bpftrace itself is already using this functionality to import all the standard library macros, which are defined in base.bt. To be clear, imported scripts can contain probes and they will be attached in the order they are imported. For example:

import "other.bt"

begin {
print("second");
}

"other.bt":

begin {
print("first");
}

This will print "first" then "second".

The one part of an imported script that is not carried over to the main script is the config. There can only be one config block in the main script, which also influences the imported scripts, e.g., if you set the default stack_mode then all ustack or kstack invocations will use this config setting.

There is also support for importing entire folders of bpftrace scripts, e.g., import "my_library_of_stuff/" and support for imported files to import other files.

Additionally, and here is the exciting part, you can also import C files! Read more in the next post on C Interop.