Getting started with Instruments in GraalVM

Tools are sometimes referred to as Instruments within the GraalVM platform.The Truffle Instrument API is used to implement such instruments.Instruments can track very fine-grained VM-level runtime events to profile, inspect, and analyze the runtime behavior of applications running on GraalVM.

Simple Tool

To provide an easier starting point for tool developers we have created aSimple Tool example project. This is ajavadoc-rich maven project which implements a simple code coverage tool. Werecommend cloning the repository and exploring the source code as a startingpoint for tool development. The following sections will give a guided tour ofthe steps needed to build and run a GraalVM tool, using Simple Tool source codeas the running example. These sections do not cover all the features of theTruffle Instrumentation API so we encourage you to check the javadoc for more details.

The Requirements

As mentioned before, Simple Tool is a code coverage tool. Ultimately, itshould provide the developer with information on what percentage of source codelines was executed, as well as exactly which lines were executed. With that inmind, we can define some high level requirements from our tool:

  • The tool keeps track of loaded source code
  • The tool keeps track of executed source code
  • On application exit, the tool calculates and prints per line coverage information

Truffle Instrument

The main starting point for Truffle tools is subclassing the TruffleInstrument class.Unsurprisingly, the simple tool code base does exactly this creating the SimpleCoverageInstrument class.

TheRegistrationannotation on the class ensures that the newly created instrument is registeredwith the Truffle Instrumentation framework, i.e., that it will be automaticallydiscovered by the framework. It also provides some meta-data about theinstrument: id, name, version, which services the instrument provides andwhether the instrument is internal or not. In order for this annotation to beeffective the Truffle DSL processor needs to process this class. This is, in case of Simple Tool, done automatically by having the DSL processor as a dependency in the maven configuration.

Now we will look back at the implementation of the SimpleCoverageInstrument class, namely which methods from TruffleInstrument does it override.These are onCreate, onDispose and getOptionDescriptors.The onCreate and onDispose methods are quite self-explanatory: called by the framework when the instrument is created and disposed.We will discuss their implementations later, but first let us discuss the remaining one: getOptionDescriptors.

Truffle comes with its own system for specifying command line options.These options allow tool users to control the tool either from the command line or when creating polyglot contexts.It is annotation based, and examples for such options are the ENABLED and PRINT_COVERAGE fields of SimpleCoverageInstrument.Both of these are static final fields of the type OptionKey annotated with Option which, similarly to the Registration annotation, provides some meta data for the option.Again, as with the Registration annotation, for the Option annotation to be effective the Truffle DSL processor is needed, which generates a subclass of OptionDescriptors (in our case named SimpleCoverageInstrumentOptionDescriptors).An instance of this class should be returned from the getOptionDescriptors method to let the framework know which options the instrument provides.

Let us return to the onCreate method. As an argument we receive an instance of the Env class.This object gives a lot of useful information, but for the onCreate method we are primarily interested in the getOptions method, which can be used to read which options are passed to the tool.We use this to check whether the ENABLED option has been set and if so we enable our tool by calling the enable method.Similarly, in the onDispose method we check the options for the state of the PRINT_COVERAGE option, and if it is enabled we call the printResults method which will print our results.

What does it mean “to enable a tool”?In general, it means that we tell the framework about the events we areinterested in and how we want to react to them. Looking at our enablemethod it does the following:

  • Firstly, it defines SourceSectionFilter.This filter is a declarative definition of the parts of the source code we areinterested in. In our example, we care about all nodes that are consideredexpressions, and we do not care about internal language parts.
  • Secondly, we obtain a instance of anInstrumenterclass which is an object allowing to specify which parts of the system we wishto instrument.
  • Finally, using the Instrumenter class, we specify a Source Section Listener and an Execution Event Factory which are both described in the next two sections.

Source Section Listener

Truffle API provides the notion of a Source which is the source code unit, and a SourceSection which is one continuous part of a Source, e.g. one method, one statement, one expression, and so on. More details can be found in the respective javadoc.

The first requirement for Simple Tool is to keep track of loaded source code.The Truffle Instrumentation API provides the LoadSourceSectionListener which, when subclassed and registered with the instrumenter, allows to react to the runtime loading source sections.This is exactly what we do with the GatherSourceSectionsListener, which is registered in the enable method of the instrument.The implementation of GatherSourceSectionsListener is quite simple: we override the onLoad method to notify the instrument of each loaded source section.The instrument keeps a mapping from each Source to a Coverage object which keeps a set of loaded source sections for each source.

Execution Event Node

Truffle languages are implemented as Abstract Syntax Tree (AST) interpreters.The language implementers annotate certain nodes with tags, which allows toselect which nodes we are interested in, by using the aforementionedSourceSectionFilter, in a language agnostic manner. The main power of theTruffle Instrumentation framework lies in its ability to insert specialisednodes in the AST which “wrap” the nodes of interest. These nodes are built usingthe same infrastructure that the language developers use, and are, from theperspective of the runtime, indistinguishable from the language nodes. Thismeans that all the techniques used to optimize Truffle languages into such highperforming language implementations are available to the tool developers aswell. More information about these techniques is available in the language implementation documentation.Suffice it to say that for Simple Tool to meet its second requirement, we need toinstrument all expressions with our own node that will notify when thatexpression is executed.

For this task we use the CoverageNode.It is a subclass of ExecutionEventNode which, as the name implies, is used to instrument events during execution.The ExecutionEventNode offers many methods to override, but we are only interested in onReturnValue.This method is invoked when the “wrapped” node returns a value, i.e. is successfully executed.The implementation is rather simple. We just notify the instrument that the node with this particular SourceSection has been executed, and the instrument updates the Coverage object in its coverage map.

The instrument is notified only once per node, as the logic is guarded by the flag.The fact that this flag is annotated with CompilationFinal and that the calls to the instrument is preceded by a call to transferToInterpreterAndInvalidate() is a standard technique in Truffle which ensures that once this instrumentation is no longer needed (i.e. a node has been executed) the instrumentation is removed from further compilations removing with it any performance overhead.

In order for the framework to know how to instantiate the CoverageNode when itis needed we need to provide a factory for them.The factory is the CoverageEventFactory, a subclass of ExecutionEventNodeFactory.This class just ensures that each CoverageNode knows the SourceSection it is instrumenting by looking it up in the provided EventContext.

Finally, when we are enabling the instrument,we tell the instrumenter to use our factory to “wrap” the nodes selected by ourfilter.

Interaction Between Users and Instruments

The third and final requirement Simple Tool has is to actually interact with its user by printing line coverage to standard output.The instrument overriders the onDispose method which is unsurprisingly called when the instrument is being disposed of.In this method we check that the proper option has been set and, if so, calculate and print the coverage as recorded by our map of Coverage objects.

This is a simple way of providing useful information to a user, but it is definitely not the only one.A tool could dump its data directly to a file, or run a web endpoint which shows the information, etc..One of the mechanisms that the Truffle Instrumentation framework provides users is registering instruments as services to be looked up by other instruments.If we look at the Registration annotation of our instrument we can see that it provides a services field where we can specify which services the instrument provides to other instruments.These services need to be explicitly registered.This allows a nicer separation of concerns among instruments so that, for example, we could have a “real time coverage” instrument which would use our SimpleCoverageInstrument to provide on demand coverage information to a user through a REST API, and a “aborts on low coverage” instrument which stops the execution if coverage drops bellow a threshold, both using the SimpleCoverageInstrument as a service.

Note that, for reasons of isolation, instrument services are not available to application code, and instrument services can only be used from other instruments or Truffle languages.

Installing a Tool into GraalVM

So far, Simple Tool seems to meet all requirements but the question remains: how do we use it?As mentioned before, Simple Tool is a maven project.Setting JAVA_HOME to a GraalVM installation and running mvn package produces a target/simpletool-<version>.jar.This is the Simple Tool distribution form.

The Truffle framework offers a clear separation between the language/tooling code and the application code.For this reason, putting the jar on the class path will not result in the framework realizing a new tool is needed.To achieve this we use —vm.Dtruffle.class.path.append=/path/to/simpletool- as is illustrated in a launcher script for our simple tool.This script also shows we can set the CLI options we specified for Simple Tool.This means that if we execute ./simpletool js example.js, we will launch the js launcher of GraalVM, add the tool to the Truffle class path, and run the included example.js file with Simple Tool enabled resulting in the following output:

  1. ==
  2. Coverage of /path/to/simpletool/example.js is59.42%
  3. +var N =2000;
  4. +var EXPECTED =17393;
  5. functionNatural(){
  6. + x =2;
  7. +return{
  8. +'next':function(){return x++;}
  9. +};
  10. }
  11. functionFilter(number, filter){
  12. +varself=this;
  13. +this.number = number;
  14. +this.filter = filter;
  15. +this.accept =function(n){
  16. +var filter =self;
  17. +for(;;){
  18. +if(n % filter.number ===0){
  19. +returnfalse;
  20. +}
  21. + filter = filter.filter;
  22. +if(filter ===null){
  23. +break;
  24. +}
  25. +}
  26. +returntrue;
  27. +};
  28. +returnthis;
  29. }
  30. functionPrimes(natural){
  31. +varself=this;
  32. +this.natural = natural;
  33. +this.filter =null;
  35. +for(;;){
  36. +var n;
  37. +if(self.filter ===null||self.filter.accept(n)){
  38. +self.filter =newFilter(n,self.filter);
  39. +return n;
  40. +}
  41. +}
  42. +};
  43. }
  44. +var holdsAFunctionThatIsNeverCalled =function(natural){
  45. -varself=this;
  46. -this.natural = natural;
  47. -this.filter =null;
  49. -for(;;){
  50. -var n;
  51. -if(self.filter ===null||self.filter.accept(n)){
  52. -self.filter =newFilter(n,self.filter);
  53. -return n;
  54. -}
  55. -}
  56. -};
  57. +}
  58. -var holdsAFunctionThatIsNeverCalledOneLine =function(){returnnull;}
  59. function primesMain(){
  60. +var primes =newPrimes(Natural());
  61. +var primArray =[];
  62. +for(var i=0;i<=N;i++){ primArray.push(;}
  63. -if(primArray[N]!= EXPECTED){thrownewError('wrong prime found: '+ primArray[N]);}
  64. }
  65. + primesMain();

Other Examples

The following examples are intended to show common use-cases that can be solved with the Truffle Instrumentation framework.

  • Coverage Instrument: A coverage tool example which was used to build up Simple Tool. It is used as the running example in further text where appropriate.
  • Debugger Instrument: A sketch on how a debugger can be implemented. Please note that Truffle already provides a Debugger Instrument that can be used directly.
  • Statement Profiler: A profiler that is able to profile the execution of statements.

Instrumentation Event Listeners

The Truffle Instrument application programming interface is defined in the package. Instrumentation agents can be developed by extending the TruffleInstrument class, and can be attached to a running GraalVM instance using in the Instrumenter class. Once attached to a running language runtime, instrumentation agents remain usable as long as the language runtime is not disposed. Instrumentation agents on GraalVM can monitor a variety of VM-level runtime events, including any of the following:

  • Source code-related events: the agent can be notified every time a new Source or SourceSection element is loaded by the monitored language runtime.
  • Allocation events: the agent can be notified every time a new object is allocated in the memory space of the monitored language runtime.
  • Language runtime and thread creation events: the agent can be notified as soon as a new execution context or a new thread for a monitored language runtime is created.
  • Application execution events: the agent gets notified every time a monitored application executes a specific set of language operations. Examples of such operations include language statements and expressions, thus allowing an instrumentation agent to inspect running applications with very high precision.For each execution event, instrumentation agents can define filtering criteria that will be used by the GraalVM instrumentation runtime to monitor only the relevant execution events. Currently, GraalVM instruments accept one of the following two filter types:

  • AllocationEventFilter to filter allocation events by allocation type.

  • SourceSectionFilter to filter source code locations in an application.Filters can be created using the provided builder object. For example, the following builder creates a SourceSectionFilter:
  1. SourceSectionFilter.newBuilder()
  2. .tagIs(StandardTag.StatementTag)
  3. .mimeTypeIs("x-application/js")
  4. .build()

The filter in the example can be used to monitor the execution of all JavaScript statements in a given application. Other filtering options such as line numbers or file extensions can also be provided.

Source section filters like the one in the example can use Tags to specify a set of execution events to be monitored. Language-agnostic tags such as statements and expressions are defined in the class, and are supported by all GraalVM languages. In addition to standard tags, GraalVM languages may provide other, language-specific, tags to enable fine-grained profiling of language-specific events (as an example, the GraalVM JavaScript engine provides JavaScript-specific tags to track the usages of ECMA builtin objects such as Array, Map, or Math).

Monitoring execution events

Application execution events enable very precise and detailed monitoring. GraalVM supports two different types of instrumentation agents to profile such events, namely:

  • Execution listener: an instrumentation agent that can be notified every time a given runtime event happens. Listeners implement the ExecutionEventListener interface, and cannot associate any state with source code locations.
  • Execution event node: an instrumentation agent that can be expressed using Truffle Framework AST nodes. Such agents extend the ExecutionEventNode class and have the same capabilities of an execution listener, but can associate state with source code locations.

Simple Instrumentation Agent

A simple example of a custom instrumentation agent to perform runtime code coverage can be found in the CoverageExample class. What follows is an overview of the agent, of its design, and of its capabilities.

All instruments extend the TruffleInstrument abstract class, and are registered in the GraalVM runtime through the @Registration annotation:

  1. @Registration(id =CoverageExample.ID, services =Object.class)
  2. publicfinalclassCoverageExampleextendsTruffleInstrument{
  3. @Override
  4. protectedvoid onCreate(finalEnv env){
  5. }
  6. /* Other methods omitted... */
  7. }

Instruments override the onCreate(Env env) method to perform custom operations at instrument loading time. Typically, an instrument would use this method to register itself in the existing GraalVM execution environment. As an example, an instrument using AST nodes can be registered in the following way:

  1. @Override
  2. protectedvoid onCreate(finalEnv env){
  3. SourceSectionFilter.Builder builder =SourceSectionFilter.newBuilder();
  4. SourceSectionFilter filter = builder.tagIs(EXPRESSION).build();
  5. Instrumenter instrumenter = env.getInstrumenter();
  6. instrumenter.attachExecutionEventFactory(filter,newCoverageEventFactory(env));
  7. }

The instrument connects itself to the running GraalVM using the attachExecutionEventFactory method, providing the following two arguments:

  • SourceSectionFilter: a source section filter used to inform the GraalVM about specific code sections to be tracked.
  • ExecutionEventNodeFactory: a Truffle Framework AST factory that provides instrumentation AST nodes to be executed by the agent every time a runtime event (as specified by the source filter) is executed.A basic ExecutionEventNodeFactory that instruments the AST nodes of an application can be implemented in the following way:
  1. publicExecutionEventNode create(finalEventContext ec){
  2. returnnewExecutionEventNode(){
  3. @Override
  4. publicvoid onReturnValue(VirtualFrame vFrame,Object result){
  5. /*
  6. * Code to be executed every time a filtered source code
  7. * element is evaluated by the guest language.
  8. */
  9. }
  10. };
  11. }

Execution event nodes can implement certain callback methods to intercept runtime execution events. Examples include:

  • onEnter: executed before an AST node corresponding to a filtered source code element (e.g., a language statement or an expression) is evaluated.
  • onReturnValue: executed after a source code element returns a value.
  • onReturnExceptional: executed in case the filtered source code element throws an exception.Execution event nodes are created on a per code location basis. Therefore, they can be used to store data specific to a given source code location in the instrumented application. As an example, an instrumentation node can simply keep track of all code locations that have already been visited using a node-local flag. Such a node-local boolean flag can be used to track the execution of AST nodes in the following way:
  1. // To keep track of all source code locations executed
  2. privatefinalSet<SourceSection> coverage =newHashSet<>();
  3. publicExecutionEventNode create(finalEventContext ec){
  4. returnnewExecutionEventNode(){
  5. // Per-node flag to keep track of execution for this node
  6. @CompilationFinalprivateboolean visited =false;
  7. @Override
  8. publicvoid onReturnValue(VirtualFrame vFrame,Object result){
  9. if(!visited){
  10. CompilerDirectives.transferToInterpreterAndInvalidate();
  11. visited =true;
  12. SourceSection src = ec.getInstrumentedSourceSection();
  13. coverage.add(src);
  14. }
  15. }
  16. };
  17. }

As the above code shows, an ExecutionEventNode is a valid AST node. This implies that the instrumentation code will be optimized by the GraalVM together with the instrumented application, resulting in minimal instrumentation overhead. Furthermore, this allows instrument developers to use Truffle Framework compiler directives directly from instrumentation nodes. In the example, compiler directives are used to inform the GraalVM compiler that visited can be considered compilation-final.

Each instrumentation node is bound to a specific code location. Such locations can be accessed by the agent using the provided EventContext object.The context object gives instrumentation nodes access to a variety of information about the current AST nodes being executed. Examples of query APIs available to instrumentation agents through EventContext include:

  • hasTag to query an instrumented node for a certain node Tag (e.g., to check if a statement node is also a conditional node).
  • getInstrumentedSourceSection to access the SourceSection associated with the current node.
  • getInstrumentedNode to access the Node corresponding to the current instrumentation event.

Fine-grained expression profiling

Instrumentation agents can profile even fractional events such as language expressions. To this end, an agent needs to be initialized providing two source section filters:

  1. // What source sections are we interested in?
  2. SourceSectionFilter sourceSectionFilter =SourceSectionFilter.newBuilder().tagIs(JSTags.BinaryOperation.class).build();
  3. // What generates input data to track?
  4. SourceSectionFilter inputGeneratingLocations =SourceSectionFilter.newBuilder().tagIs(
  5. StandardTags.ExpressionTag.class).build();
  6. instrumenter.attachExecutionEventFactory(sourceSectionFilter, inputGeneratingLocations, factory);

The first source section filter (sourceSectionFilter, in the example) is a normal filter equivalent to other filters described before, and is used to identify the source code locations to be monitored. The second section filter, inputGeneratingLocations, is used by the agent to specify the intermediate values that should be monitored for a certain source section. Intermediate values correspond to all observable values that are involved in the execution of a monitored code element, and are reported to the instrumentation agent by means of the onInputValue callback. As an example, let us assume an agent needs to profile all operand values provided to sum operations (i.e., +) in JavaScript:

  1. var a =3;
  2. var b =4;
  3. // the '+' expression is profiled
  4. var c = a + b;

By filtering on JavaScript Binary expressions, an instrumentation agent would be able to detect the following runtime events for the above code snippet:

  • onEnter() for the binary expression at line 3.
  • onInputValue() for the first operand of the binary operation at line 3. The value reported by the callback will be 3, that is, the value of the a local variable.
  • onInputValue() for the second operand of the binary operation. The value reported by the callback will be 4, that is, the value of the b local variable.
  • onReturnValue() for the binary expression. The value provided to the callback will be the value returned by the expression after it has completed its evaluation, that is, the value 7.By extending the source section filters to all possible events, an instrumentation agent will observe something equivalent to the following execution trace (in pseudocode):
  1. // First variable declaration
  2. onEnter -VariableWrite
  3. onEnter -NumericLiteral
  4. onReturnValue -NumericLiteral
  5. onInputValue -(3)
  6. onReturnValue -VariableWrite
  7. // Second variable declaration
  8. onEnter -VariableWrite
  9. onEnter -NumericLiteral
  10. onReturnValue -NumericLiteral
  11. onInputValue -(4)
  12. onReturnValue -VariableWrite
  13. // Third variable declaration
  14. onEnter -VariableWrite
  15. onEnter -BinaryOperation
  16. onEnter -VariableRead
  17. onReturnValue -VariableRead
  18. onInputValue -(3)
  19. onEnter -VariableRead
  20. onReturnValue -VariableRead
  21. onInputValue -(4)
  22. onReturnValue -BinaryOperation
  23. onInputValue -(7)
  24. onReturnValue -VariableWrite

The onInputValue method can be used in combination with source section filters to intercept very fine-grained execution events such as intermediate values used by language expressions. The intermediate values that are accessible to the Instrumentation framework greatly depend on the instrumentation support provided by each language. Moreover, languages may provide additional metadata associated with language-specific Tag classes.

Altering the execution flow of an application

The instrumentation capabilities that we have presented so far enable users to observe certain aspects of a running application. In addition to passive monitoring of an application’s behavior, the Instrument API features support for actively altering the behavior of an application at runtime. Such capabilities can be used to write complex instrumentation agents that affect the behavior of a running application to achieve specific runtime semantics. For example, one could alter the semantics of a running application to ensure that certain methods or functions are never executed (e.g., by throwing an exception when they are called).

Instrumentation agents with such capabilities can be implemented by leveraging the onUnwind callback in execution event listeners and factories. As an example, let’s consider the following JavaScript code:

  1. function inc(x){
  2. return x +1
  3. }
  4. var a =10
  5. var b = a;
  6. // Let's call inc() with normal semantics
  7. while(a == b && a <100000){
  8. a = inc(a);
  9. b = b +1;
  10. }
  11. c = a;
  12. // Run inc() and alter it's return type using the instrument
  13. return inc(c)

An instrumentation agent that modifies the return value of inc to always be 42 can be implemented using an ExecutionEventListener, in the following way:

  1. ExecutionEventListener myListener =newExecutionEventListener(){
  2. @Override
  3. publicvoid onReturnValue(EventContext context,VirtualFrame frame,Object result){
  4. String callSrc = context.getInstrumentedSourceSection().getCharacters();
  5. // is this the function call that we want to modify?
  6. if("inc(c)".equals(callSrc)){
  7. CompilerDirectives.transferToInterpreter();
  8. // notify the runtime that we will change the current execution flow
  9. throw context.createUnwind(null);
  10. }
  11. }
  12. @Override
  13. publicObject onUnwind(EventContext context,VirtualFrame frame,Object info){
  14. // just return 42 as the return value for this node
  15. return42;
  16. }
  17. }

The event listener can be executed intercepting all function calls, for example using the following instrument:

  1. @TruffleInstrument.Registration(id ="UniversalAnswer", services =UniversalAnswerInstrument.class)
  2. publicstaticclassUniversalAnswerInstrumentextendsTruffleInstrument{
  3. @Override
  4. protectedvoid onCreate(Env env){
  5. env.registerService(this);
  6. env.getInstrumenter().attachListener(SourceSectionFilter.newBuilder().tagIs(CallTag.class).build(), myListener);
  7. }
  8. }

When enabled, the instrument will execute its onReturnValue callback each time a function call returns. The callback reads the associated source section (using getInstrumentedSourceSection) and looks for a specific source code pattern (the function call inc(c), in this case). As soon as such code pattern is found, the instrument throws a special runtime exception, called UnwindException, that instructs the Instrumentation framework about a change in the current application’s execution flow. The exception is intercepted by the onUnwind callback of the instrumentation agent, which can be used to return any arbitrary value to the original instrumented application. In the example, all calls to inc(c) will return 42 regardless of any application-specific data. A more realistic instrument might access and monitor several aspects of an application, and might not rely on source code locations, but rather on object instances or other application-specific data.