### Open an IR and draw the CFG to a PNG (show-cfg.lisp) Source: https://grammatech.github.io/gtirb/show-cfg_8lisp-example.html Use this Common Lisp example to open a GTIRB IR file and write its control-flow graph to a DOT file. It requires the gtirb and gtirb/dot packages (installed via quicklisp) and a GTIRB file produced by ddisasm. After evaluating the file, process the resulting DOT file with Graphviz to generate a PNG. ```lisp ;;;; show-cfg.lisp --- An example program which opens an IR and draws the CFG ;;; ;;; To run this example, do the following. ;;; ;;; 1. Install the gtirb and gtirb/dot packages with quicklisp ;;; ;;; (ql:quickload :gtirb/dot) ;;; ;;; 2. Run ddisasm to disassemble a binary to GTIRB. ;;; ;;; $ echo 'main(){puts("hello world");}'|gcc -x c - -o /tmp/hello ;;; $ ddisasm /tmp/hello --ir /tmp/hello.gtirb ;;; ;;; 3. Evaluate this file. ;;; ;;; 4. Process the resultant dot file into a png ;;; ;;; $ cat /tmp/hello.dot|dot -Tpng > /tmp/hello.png ;;; (in-package :gtirb/dot) (to-dot-file (read-gtirb "/tmp/hello.gtirb") "/tmp/hello.dot") ``` -------------------------------- ### Install pre-commit hook Source: https://grammatech.github.io/gtirb/md__c_o_n_t_r_i_b_u_t_i_n_g.html Install the formatters as a pre-commit hook. Run this in the gtirb root directory. ```bash pre-commit install ``` -------------------------------- ### Install Python Protobuf Library Source: https://grammatech.github.io/gtirb/md__p_r_o_t_o_b_u_f.html Install the required Python library for Protocol Buffers using pip. ```bash $ pip install protobuf ``` -------------------------------- ### Install GTIRB binaries on Ubuntu20 (focal) Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Commands to install GTIRB binaries from the GTIRB focal repository. Adds the GTIRB repository and installs the packages. ```bash sudo apt-get install software-properties-common echo "deb [trusted=yes] https://grammatech.github.io/gtirb/pkgs/focal ./" | sudo tee -a /etc/apt/sources.list.d/gtirb.list sudo apt-get update sudo apt-get install libgtirb-dev gtirb-pprinter ddisasm ``` -------------------------------- ### Install GTIRB binaries on Ubuntu16 (xenial) Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Commands to install GTIRB binaries from the GTIRB xenial repository. Requires adding the protobuf and boost PPAs, and the GTIRB repository. Uses --allow-unauthenticated for the install. ```bash sudo apt-get install software-properties-common sudo add-apt-repository ppa:maarten-fonville/protobuf sudo add-apt-repository ppa:mhier/libboost-latest echo "deb https://grammatech.github.io/gtirb/pkgs/xenial ./" | sudo tee -a /etc/apt/sources.list.d/gtirb.list sudo apt-get update sudo apt-get install --allow-unauthenticated libgtirb-dev gtirb-pprinter ddisasm ``` -------------------------------- ### Install GTIRB tools via APT Source: https://grammatech.github.io/gtirb/index.html Update the package database and install the core GTIRB tools. ```bash sudo apt-get update sudo apt-get install gtirb-pprinter ddisasm ``` -------------------------------- ### Install Python documentation dependencies Source: https://grammatech.github.io/gtirb/md__c_o_n_t_r_i_b_u_t_i_n_g.html Command to install Sphinx and sphinx-autodoc-typehints via pip3. ```bash pip3 install sphinx sphinx-autodoc-typehints ``` -------------------------------- ### Install pre-commit with pip3 Source: https://grammatech.github.io/gtirb/md__c_o_n_t_r_i_b_u_t_i_n_g.html Install the pre-commit tool with pip if it is not already installed on your system. ```bash pip3 install pre-commit ``` -------------------------------- ### Install GTIRB dependencies with vcpkg Source: https://grammatech.github.io/gtirb/cpp/index.html Use vcpkg to install the required protobuf and boost dependencies on Windows. ```bash vcpkg.exe install --triplet x64-windows protobuf boost ``` -------------------------------- ### Install GTIRB binaries on Ubuntu18 (bionic) Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Commands to install GTIRB binaries from the GTIRB bionic repository. Adds the boost PPA and the GTIRB repository, then installs the packages. ```bash sudo apt-get install software-properties-common sudo add-apt-repository ppa:mhier/libboost-latest echo "deb [trusted=yes] https://grammatech.github.io/gtirb/pkgs/bionic ./" | sudo tee -a /etc/apt/sources.list.d/gtirb.list sudo apt-get update sudo apt-get install libgtirb-dev gtirb-pprinter ddisasm ``` -------------------------------- ### Install GTIRB packages on Arch Linux with yay Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Installs pre-built pacman packages for GTIRB, gtirb-pprinter, and ddisasm using the AUR helper yay. ```bash yay -Sy gtirb-git gtirb-pprinter-git ddisasm-git ``` -------------------------------- ### Install Python API dependencies Source: https://grammatech.github.io/gtirb/md__c_o_n_t_r_i_b_u_t_i_n_g.html Commands to install the dependencies for the GTIRB Python API from the build directory. ```bash cd /build/python python3 setup.py egg_info pip3 install -r gtirb.egg-info/requires.txt ``` -------------------------------- ### Lisp: cfg-paths example - print all paths between two blocks Source: https://grammatech.github.io/gtirb/cfg-paths_8lisp-example.html Defines a package and function to read a GTIRB file and return all paths in its control flow graph between two basic block addresses. Requires the :gt, :gtirb, and :graph libraries; the :graph library may need to be installed from source for the all-paths function. The function uses read-gtirb, at-address, and cfg to find blocks and compute paths. ```lisp ;;;; cfg-paths.lisp --- Print the shortest path between two blocks ;;; ;;; To run this example, do the following. ;;; ;;; 1. Install all required packages with quicklisp. ;;; ;;; NOTE: you might need to install the :graph library from source ;;; as the `all-paths' function isn't in the quicklisp ;;; version at the time of writing of this example. ;;; ;;; (mapcar #'ql:quickload '(:gt :gtirb :graph) ;;; ;;; 2. Run ddisasm to disassemble a binary to GTIRB. ;;; ;;; $ echo 'main(){puts("hello world");}'|gcc -x c - -o /tmp/hello ;;; $ ddisasm /tmp/hello --ir /tmp/hello.gtirb ;;; ;;; 3. Evaluate this file using the path of the GTIRB file produced by ;;; ddisasm and the addresses of two basic blocks. ;;; (defpackage :cfg-paths (:use :gt :gtirb :graph) (:shadow :symbol :size :copy)) (in-package :cfg-paths) (defun cfg-paths (path from to) "Return all paths in the cfg of the GTIRB file from FROM to TO. FROM and TO are the addresses of the start of blocks." (let ((ir (read-gtirb path))) (flet ((block-uuid-at (address) (uuid (find-if (lambda (it) (typep it 'code-block)) (at-address ir address))))) (all-paths (cfg ir) (block-uuid-at from) (block-uuid-at to))))) ``` -------------------------------- ### Install stable GTIRB Python API Source: https://grammatech.github.io/gtirb/index.html Install the latest stable version of the GTIRB Python API from PyPI. ```bash pip install gtirb ``` -------------------------------- ### Install unstable GTIRB Python API Source: https://grammatech.github.io/gtirb/index.html Install the latest unstable version of the GTIRB Python API from a prebuilt wheel. ```bash pip install https://download.grammatech.com/gtirb/files/python/gtirb-0.dev-py3-none-any.whl ``` -------------------------------- ### C++ auto usage examples Source: https://grammatech.github.io/gtirb/md__c_o_n_t_r_i_b_u_t_i_n_g.html Examples of using auto with explicit type qualifiers, pointers, and references as required by the C++ code guidelines. ```cpp const auto *Ptr = dynamic_cast(SomePtr); auto Val = static_cast(SomeValue); for (auto Iter = SomeContainer.begin(), End = SomeContainer.end(); Iter != End; ++Iter) {} ``` -------------------------------- ### getIsa() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Module.html Get the ISA of the instructions in this Module. ```APIDOC ## getIsa() ### Description Get the ISA of the instructions in this Module. ### Returns The module `Module.ISA`. ``` -------------------------------- ### Example usage of Symbol::visit with a custom visitor Source: https://grammatech.github.io/gtirb/cpp/classgtirb_1_1_symbol.html Shows how to use Symbol::visit with a visitor struct that overloads operator() for CfgNode* and DataBlock*. The example creates symbols with different referents and demonstrates that visit calls the appropriate overload or no overload when the referent is absent. ```cpp struct Visitor { int operator()(CfgNode*) { return 0; } long operator()(DataBlock*) { return 1; } }; Context Ctx; Symbol* SymB = Symbol::Create(Ctx, Block::Create(Ctx), ""); Symbol* SymD = Symbol::Create(Ctx, DataBlock::Create(Ctx), ""); Symbol* SymX = Symbol::Create(Ctx, Addr(42), ""); Symbol* SymN = Symbol::Create(Ctx); SymB->visit(Visitor{}); // Will call Visitor::operator()(CfgNode*); SymD->visit(Visitor{}); // Will call Visitor::operator()(DataBlock*); SymX->visit(Visitor{}); // Will not call any overload SymN->visit(Visitor{}); // Will not call any overload ``` -------------------------------- ### GTIRB API Walkthrough: Full Example Source: https://grammatech.github.io/gtirb/api-walkthrough_8cpp-example.html Complete C++ example demonstrating GTIRB API usage: registering AuxData schemas, creating IR objects, adding data and code blocks, populating the CFG, using symbolic expressions, adding auxiliary data, and querying symbols. ```cpp #include #include #include #include using namespace gtirb; int main() { // BEGIN // // ### Initialization for AuxData usage // // To make use of the auxiliary data mechanism, each schema that is // intended to be used must be registered with the API before doing // anything else with GTIRB. Typically, this is easiest to do as one // of the first steps in main(). AuxDataContainer::registerAuxDataType(); // // ### Populating the IR // // GTIRB representation objects have class `gtirb::IR`, and are created within // a context object (`gtirb::Context`). Freeing the context will also destroy // all the objects within it. Context C; auto* Ir = IR::Create(C); // Every IR holds a set of modules (`gtirb::Module`). auto* M = Module::Create(C, "example"); Ir->addModule(M); // Could also have written: auto* M = Ir->addModule(C); // Every module holds a set of sections (`gtirb::Section`). auto* S = Section::Create(C, ".text"); M->addSection(S); // Could also have written: auto* S = M->addSection(C, ".text"); // Every section has a set of byte intervals (`gtirb::ByteInterval`). auto* BI = ByteInterval::Create(C, Addr(2048), 466); S->addByteInterval(BI); // Could also have written: auto* BI = S->addByteInterval(C, Addr(2048), 466); // Create some data objects. These only define the layout and do not directly // store any data. auto* D1 = DataBlock::Create(C, 6); BI->addBlock(0, D1); auto* D2 = DataBlock::Create(C, 2); BI->addBlock(6, D2); // The actual data is stored in the blocks' byte interval: std::array Bytes{1, 0, 2, 0, 115, 116, 114, 108}; BI->insertBytes(const_cast(BI)->bytes_begin(), Bytes.begin(), Bytes.end()); // Symbols (`gtirb::Symbol`) associate a name with a block in the IR, such as // code blocks, data blocks, or proxy blocks. They can optionally store an // address instead. [[maybe_unused]] auto* Sym1 = M->addSymbol(Symbol::Create(C, D1, "data1")); [[maybe_unused]] auto* Sym2 = M->addSymbol(Symbol::Create(C, D2, "data2")); // GTIRB can store multiple symbols with the same address or referent. M->addSymbol(Symbol::Create(C, D2, "duplicateReferent")); M->addSymbol(Symbol::Create(C, Addr(2048), "duplicateName")); M->addSymbol(Symbol::Create(C, Addr(4096), "duplicateName")); // Basic blocks are stored as `gtirb::CodeBlock`s. Like data blocks, code // blocks reference data in a byte interval but do not directly hold any data // themselves. GTIRB does not directly represent instructions. auto* B1 = CodeBlock::Create(C, 4); BI->addBlock(12, B1); auto* B2 = CodeBlock::Create(C, 6); BI->addBlock(16, B2); // GTIRB has an interprocedural control flow graph (`gtirb::CFG`) to track // relations between code blocks. The `CFG` can be populated with edges to // denote control flow. auto& Cfg = Ir->getCFG(); auto E = *addEdge(B1, B2, Cfg); // Edges can have labels, indicating the type of control flow: Cfg[E] = std::make_tuple(ConditionalEdge::OnFalse, DirectEdge::IsDirect, EdgeType::Fallthrough); // Symbolic expressions indicate that the value of a range of bytes depends on // the value of a symbol. BI->addSymbolicExpression(14, SymAddrConst{0, Sym1}); // Finally, auxiliary data can be used to store additional information at the // IR and module level. A `gtirb::AuxData` object can store integers, strings, // GTIRB types such as `gtirb::Addr` and `gtirb::UUID`, and various containers // over these types. There are predefined AuxData schema for you to use, but // you can also use your own custom AuxData schema. Here is use of a // predefined schema, `gtirb::schema::Types`: M->addAuxData( {{D1->getUUID(), "string"}, {D2->getUUID(), "uleb128"}}); // // ### Querying the IR // // Symbols can be looked up by address or name. Any number of symbols can // share an address or name, so be prepared to deal with multiple results. for (const auto& Sym : M->findSymbols(Addr(2054))) { [[maybe_unused]] const auto& _ = Sym; assert(Sym.getAddress() == Addr(2054)); assert(Sym.getName() == "data2" || Sym.getName() == "duplicateReferent"); assert(Sym.getReferent() == nullptr || Sym.getReferent() == D2); } } ``` -------------------------------- ### Build Documentation with CMake Source: https://grammatech.github.io/gtirb/md__c_o_n_t_r_i_b_u_t_i_n_g.html Commands to create a build directory and generate documentation using CMake. ```bash mkdir build cd build ``` ```bash build> cmake [] build> cmake --build . --target doc ``` -------------------------------- ### Module constructor with full parameters Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Module.html Creates a Module with all properties: binary path, preferred address, rebase delta, file format, ISA, name, sections, symbols, proxy blocks, and entry point. The entry point may be null. ```java public Module​(java.lang.String binaryPath, long preferredAddr, long rebaseDelta, Module.FileFormat fileFormat, Module.ISA isa, java.lang.String name, java.util.List
sections, java.util.List symbols, java.util.List proxyBlocks, CodeBlock entryPoint) ``` -------------------------------- ### Install Keystone from source Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Clones and builds Keystone from source, required for the Common Lisp and C++ APIs. Uses make-share.sh to build shared libraries. ```bash git clone https://github.com/keystone-engine/keystone.git cd keystone mkdir build cd build ../make-share.sh make install ``` -------------------------------- ### Parse type name examples in _parse_type doctest Source: https://grammatech.github.io/gtirb/python/_modules/gtirb/serialization.html Doctest examples showing how _parse_type parses encoded aux_data type names into SubtypeTree tuples. Each example shows the input type string and the resulting parse tree. ```python _parse_type('foo') ('foo', ()) ``` ```python _parse_type('foo') ('foo', (('bar',()),)) ``` ```python _parse_type('foo>') ('foo', (('bar', (('baz', ()),)),)) ``` -------------------------------- ### IR.__init__ Source: https://grammatech.github.io/gtirb/python/gtirb.ir.html Initializes an IR instance with modules, auxiliary data, control flow graph, version, and UUID. ```APIDOC ## IR.__init__ ### Description Creates a new IR instance. ### Method __init__ ### Parameters - **modules** (Iterable[Module]) - Optional - A list of Modules contained in the IR. - **cfg** (Iterable[Edge]) - Optional - A set of Edges representing the IR's control flow graph. Defaults to empty. - **aux_data** (Mapping[str, AuxData] or Iterable[Tuple[str, AuxData]]) - Optional - Initial auxiliary data. Defaults to empty. - **version** (int) - Optional - The Protobuf version of this IR. Defaults to 4. - **uuid** (Optional[UUID]) - Optional - The UUID of this IR, or None to generate a new one. Defaults to None. ### Request Example ```python ir = IR(modules=[], aux_data={}, cfg={}, version=4, uuid=None) ``` ``` -------------------------------- ### List CMake customization options Source: https://grammatech.github.io/gtirb/index.html Run this command within the build directory to view available configuration flags. ```bash cmake -LH ``` -------------------------------- ### Load GTIRB in Python Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Initialize the GTIRB environment and load the binary representation in Python. ```python from gtirb import * import gtirb_functions import gtirb_capstone ir = IR.load_protobuf("ls.gtirb") ``` -------------------------------- ### Install GTIRB Python packages Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Installs the GTIRB Python packages using pip3. Requires Python 3. ```bash pip3 install gtirb gtirb-functions gtirb-capstone ``` -------------------------------- ### Update sources.list for APT Source: https://grammatech.github.io/gtirb/index.html Add the GTIRB repository to your sources.list file. ```bash echo "deb [arch=amd64] https://download.grammatech.com/gtirb/files/apt-repo [distribution] [component]"| sudo tee -a /etc/apt/sources.list ``` -------------------------------- ### Find data blocks that start at an address Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/ByteInterval.html Returns a list of DataBlock objects that start exactly at the given address. ```java public java.util.List findDataBlocksAt(long address) ``` -------------------------------- ### Find code blocks that start at an address Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/ByteInterval.html Returns a list of CodeBlock objects that start exactly at the given address. ```java public java.util.List findCodeBlocksAt(long address) ``` -------------------------------- ### Add GrammaTech APT key Source: https://grammatech.github.io/gtirb/index.html Add the GrammaTech APT key to your system to allow installation from the repository. ```bash wget -O - https://download.grammatech.com/gtirb/files/apt-repo/conf/apt.gpg.key | apt-key add - ``` -------------------------------- ### Module.__init__ Source: https://grammatech.github.io/gtirb/python/gtirb.html Constructs a new Module object with the specified parameters. This initializes the module with auxiliary data, binary path, ISA, byte order, file format, name, preferred address, proxies, rebase delta, sections, symbols, entry point, UUID, and IR. ```APIDOC ## Module.__init__ ### Description Constructs a new Module object with the specified parameters. ### Parameters - **aux_data** (typing.Union[typing.Mapping[str, gtirb.auxdata.AuxData], typing.Iterable[typing.Tuple[str, gtirb.auxdata.AuxData]]]) - Optional - The initial auxiliary data to be associated with the object, as a mapping from names to gtirb.AuxData, defaults to an empty dict. - **binary_path** (str) - Optional - The path to the loadable binary object represented by this module. - **isa** (gtirb.module.Module.ISA) - Optional - The ISA of the binary. - **byte_order** (gtirb.module.Module.ByteOrder) - Optional - The endianness of the binary. - **file_format** (gtirb.module.Module.FileFormat) - Optional - The file format of the binary. - **name** (str) - Optional - The name given to the binary. - **preferred_addr** (int) - Optional - The preferred loading address of the binary. - **proxies** (typing.Iterable[gtirb.block.ProxyBlock]) - Optional - A set containing all the gtirb.ProxyBlocks in the binary. - **rebase_delta** (int) - Optional - The rebase delta of the binary. - **sections** (typing.Iterable[gtirb.section.Section]) - Optional - A set containing all the gtirb.Sections in the binary. - **symbols** (typing.Iterable[gtirb.symbol.Symbol]) - Optional - A set containing all the gtirb.Symbols in the binary. - **entry_point** (typing.Optional[gtirb.block.CodeBlock]) - Optional - A CodeBlock representing where control flow of this module begins at, or None if not present. - **uuid** (typing.Optional[uuid.UUID]) - Optional - The UUID of this Module, or None if a new UUID needs generated via uuid.uuid4(). Defaults to None. - **ir** (typing.Optional[gtirb.ir.IR]) - Optional - The IR this module belongs to. ### Return Type None ``` -------------------------------- ### ByteBlock.__init__ Source: https://grammatech.github.io/gtirb/python/gtirb.html Initializes a ByteBlock with size, offset, UUID, and byte interval. ```APIDOC ## ByteBlock.__init__ ### Description Initializes a ByteBlock with the given size, offset, UUID, and byte interval. ### Parameters - **size** (int) - Optional - The size of the block in bytes. Defaults to 0. - **offset** (int) - Optional - The offset from the beginning of the byte interval to which this block belongs. Defaults to 0. - **uuid** (uuid.UUID) - Optional - The UUID of this ByteBlock, or None if a new UUID needs generated. - **byte_interval** (ByteInterval) - Optional - The byte interval to which this block belongs. ### Returns None ``` -------------------------------- ### AuxData.data (property) Source: https://grammatech.github.io/gtirb/python/_modules/gtirb/auxdata.html Gets or sets the value stored in this AuxData. When getting, if the data is lazily loaded, it will be deserialized on first access. ```APIDOC ## AuxData.data (property) ### Description Gets or sets the value stored in this AuxData. When getting, if the data is lazily loaded, it will be deserialized on first access. ### Method Property getter/setter ### Parameters - **value** (object) - Required (for setter) - The new value to store in this AuxData. ### Request Example ```python # Getter value = aux_data.data # Setter aux_data.data = new_value ``` ### Response - **data** (Any) - The value stored in this AuxData. ``` -------------------------------- ### Build and run stack-stamp with C++ Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Build the C++ stack-stamp tool with CMake and run it on a GTIRB file, specifying input and output files. ```bash mkdir build cmake -Bbuild make -Cbuild ./build/bin/gtirb-stack-stamp -i /tmp/ls.gtirb -o /tmp/ls-ss.gtirb ``` -------------------------------- ### Build and run stack-stamp with Common Lisp Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Load the Common Lisp stack-stamp library, build a standalone executable, and run it on a GTIRB file. ```bash sbcl --eval '(ql:quickload :gtirb-stack-stamp)' --eval '(asdf:make :gtirb-stack-stamp :type :program :monolithic t)' ./stack-stamp -g /tmp/ls-ss.gtirb -b /tmp/ls-ss ``` -------------------------------- ### Find data blocks whose start is within an address range Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/ByteInterval.html Returns a list of DataBlock objects that start within the provided inclusive-exclusive address range. ```java public java.util.List findDataBlocksAt(long startAddress, long endAddress) ``` -------------------------------- ### Module(String, long, long, Module.FileFormat, Module.ISA, String, List
, List, List, CodeBlock) Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/class-use/Module.FileFormat.html Constructs a Module with the specified binary path, preferred address, rebase delta, file format, ISA, name, sections, symbols, proxy blocks, and entry point. This constructor allows full initialization of the module. ```APIDOC ## Module(String binaryPath, long preferredAddr, long rebaseDelta, Module.FileFormat fileFormat, Module.ISA isa, String name, List
sections, List symbols, List proxyBlocks, CodeBlock entryPoint) ### Description Class Constructor. ### Method `Module(String binaryPath, long preferredAddr, long rebaseDelta, Module.FileFormat fileFormat, Module.ISA isa, String name, List
sections, List symbols, List proxyBlocks, CodeBlock entryPoint)` ### Parameters - **binaryPath** (String) - Required - The path to the binary file. - **preferredAddr** (long) - Required - The preferred address of the module. - **rebaseDelta** (long) - Required - The rebase delta. - **fileFormat** (Module.FileFormat) - Required - The file format of the binary. - **isa** (Module.ISA) - Required - The instruction set architecture. - **name** (String) - Required - The name of the module. - **sections** (List
) - Required - The list of sections. - **symbols** (List) - Required - The list of symbols. - **proxyBlocks** (List) - Required - The list of proxy blocks. - **entryPoint** (CodeBlock) - Required - The entry point code block. ``` -------------------------------- ### Find code blocks whose start is within an address range Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/ByteInterval.html Returns a list of CodeBlock objects that start within the inclusive-exclusive range from startAddress to endAddress. ```java public java.util.List findCodeBlocksAt(long startAddress, long endAddress) ``` -------------------------------- ### getItemsAtStartIndexRange Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/TreeListUtils.html Generic method for retrieving items that start at a given address range. Takes start and end indices and a tree, and returns a list of matching items. ```APIDOC ## getItemsAtStartIndexRange ### Description Generic method for retrieving items that start at a given address range. ### Method getItemsAtStartIndexRange ### Signature `public static java.util.List getItemsAtStartIndexRange(long startIndex, long endIndex, java.util.TreeMap> tree)` ### Parameters - **startIndex** (long) - Required - The start of the address range to be matched. - **endIndex** (long) - Required - The end of the address range. - **tree** (java.util.TreeMap>) - Required - The tree to be matched in. ### Returns A list of matching items. ``` -------------------------------- ### Install GTIRB Common Lisp packages with quicklisp Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Loads the GTIRB Common Lisp packages using quicklisp's ql:quickload. ```common-lisp (ql:quickload '(:gtirb :gtirb-functions :gtirb-capstone)) ``` -------------------------------- ### getHeader() - PeResourceEntry Source: https://grammatech.github.io/gtirb/java/index-all.html Gets the header. ```APIDOC ## getHeader() ### Description Get the header. ### Method GET ### Endpoint com.grammatech.gtirb.PeResourceEntry#getHeader() ### Parameters None ### Response Returns the header. ``` -------------------------------- ### Module(binaryPath, preferredAddr, rebaseDelta, fileFormat, isa, name, sections, symbols, proxyBlocks, entryPoint) Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Module.html Class Constructor. Creates a new Module with the specified properties. ```APIDOC ## Module(binaryPath, preferredAddr, rebaseDelta, fileFormat, isa, name, sections, symbols, proxyBlocks, entryPoint) ### Description Class Constructor. Creates a new Module with the specified properties. ### Parameters - **binaryPath** (java.lang.String) - Required - The binary path of this Module. - **preferredAddr** (long) - Required - The preferred address of this Module. - **rebaseDelta** (long) - Required - The rebase delta of this Module. - **fileFormat** (Module.FileFormat) - Required - The file format of this Module. - **isa** (Module.ISA) - Required - The ISA of this Module. - **name** (java.lang.String) - Required - The name of this Module. - **sections** (java.util.List
) - Required - A list of Sections belonging to this Module. - **symbols** (java.util.List) - Required - A list of Symbols belonging to this Module. - **proxyBlocks** (java.util.List) - Required - A list of ProxyBlocks belonging to this Module. - **entryPoint** (CodeBlock) - Required - The entry point of this module or null. ### Returns No return value. ``` -------------------------------- ### getSymbols() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Module.html Get the symbols of this Module. ```APIDOC ## getSymbols() ### Description Get the symbols of this Module. ### Returns An unmodifiable `Symbol` list of all the symbols in this `Module`. ``` -------------------------------- ### Load GTIRB in Common Lisp Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Initialize the GTIRB environment and load the binary representation in Common Lisp. ```lisp (mapcar #'use-package '(:gtirb :gtirb-capstone :gtirb-functions)) (defparameter *ir* (read-gtirb "ls.gtirb")) ``` -------------------------------- ### getSections() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Module.html Get the sections of this Module. ```APIDOC ## getSections() ### Description Get the sections of this Module. ### Returns An unmodifiable `Section` list of all the sections in this `Module`. ``` -------------------------------- ### Correct linking order example Source: https://grammatech.github.io/gtirb/md__f_a_q.html Place the -lgtirb flag after the source file to ensure the linker correctly resolves symbols. ```bash g++ --std=c++17 my_gtirb_program.cpp -lgtirb ``` -------------------------------- ### getName() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Module.html Get the name of this Module. ```APIDOC ## getName() ### Description Get the name of this Module. ### Returns The module name. ``` -------------------------------- ### findDataBlocksAt single address Source: https://grammatech.github.io/gtirb/cpp/_byte_interval_8hpp_source.html Finds data blocks at a single address. Returns an empty range if the address is before the byte interval's start or if the interval has no address. Otherwise delegates to findDataBlocksAtOffset with the offset relative to the interval start. ```cpp const_data_block_range findDataBlocksAt(Addr A) const { if (!Address || A < *Address) { // Return an empty range without default-constructing the iterators. return findDataBlocksAtOffset(0, 0); } return findDataBlocksAtOffset(A - *Address); } ``` -------------------------------- ### static CodeBlock * Create(Context &C) Source: https://grammatech.github.io/gtirb/cpp/classgtirb_1_1_code_block.html Creates an uninitialized CodeBlock object in the given context. ```APIDOC ## static CodeBlock * Create(Context &C) ### Description Creates an uninitialized CodeBlock object. ### Parameters - **C** (Context&) - The context in which to create the object. ### Returns A pointer to the newly created CodeBlock object. ``` -------------------------------- ### getIndex() - TreeListItem Source: https://grammatech.github.io/gtirb/java/index-all.html Gets the item index. ```APIDOC ## getIndex() ### Description Get the item index. ### Method GET ### Endpoint com.grammatech.gtirb.TreeListItem#getIndex() ### Parameters None ### Response Returns the item index. ``` -------------------------------- ### Module Constructor Source: https://grammatech.github.io/gtirb/python/gtirb.module.html Creates a new Module instance with the specified parameters for auxiliary data, binary path, ISA, byte order, file format, name, preferred address, proxies, rebase delta, sections, symbols, entry point, UUID, and IR. ```APIDOC ## Module Constructor ### Description Creates a new Module instance with the specified parameters. ### Parameters - **aux_data** (typing.Union[typing.Mapping[str, gtirb.auxdata.AuxData], typing.Iterable[typing.Tuple[str, gtirb.auxdata.AuxData]]]) - Optional - The initial auxiliary data to be associated with the object, as a mapping from names to gtirb.AuxData, defaults to an empty dict. - **binary_path** (str) - Optional - The path to the loadable binary object represented by this module. - **isa** (gtirb.module.Module.ISA) - Optional - The ISA of the binary. - **byte_order** (gtirb.module.Module.ByteOrder) - Optional - The endianness of the binary. - **file_format** (gtirb.module.Module.FileFormat) - Optional - The file format of the binary. - **name** (str) - Optional - The name given to the binary. - **preferred_addr** (int) - Optional - The preferred loading address of the binary. - **proxies** (typing.Iterable[gtirb.block.ProxyBlock]) - Optional - A set containing all the gtirb.ProxyBlocks in the binary. - **rebase_delta** (int) - Optional - The rebase delta of the binary. - **sections** (typing.Iterable[gtirb.section.Section]) - Optional - A set containing all the gtirb.Sections in the binary. - **symbols** (typing.Iterable[gtirb.symbol.Symbol]) - Optional - A set containing all the gtirb.Symbols in the binary. - **entry_point** (typing.Optional[gtirb.block.CodeBlock]) - Optional - A CodeBlock representing where control flow of this module begins at, or None if not present. - **uuid** (typing.Optional[uuid.UUID]) - Optional - The UUID of this Module, or None if a new UUID needs generated via uuid.uuid4(). Defaults to None. - **ir** (typing.Optional[gtirb.ir.IR]) - Optional - The IR this module belongs to. ``` -------------------------------- ### getFuncName() - PeImportEntry Source: https://grammatech.github.io/gtirb/java/index-all.html Gets the function name. ```APIDOC ## getFuncName() ### Description Get the function name. ### Method GET ### Endpoint com.grammatech.gtirb.PeImportEntry#getFuncName() ### Parameters None ### Response Returns the function name. ``` -------------------------------- ### getFields() - TypeTableEntry.StructType Source: https://grammatech.github.io/gtirb/java/index-all.html Gets the fields of the struct. ```APIDOC ## getFields() ### Description Get the fields of the struct. ### Method GET ### Endpoint com.grammatech.gtirb.TypeTableEntry.StructType#getFields() ### Parameters None ### Response Returns the fields of the struct. ``` -------------------------------- ### CFG.__init__ Source: https://grammatech.github.io/gtirb/python/gtirb.html Initializes a CFG object with an optional set of edges. ```APIDOC ## CFG.__init__ ### Description Initializes a CFG object. ### Method `__init__(edges=None)` ### Parameters - **edges** (optional) - Initial edges for the CFG. ``` -------------------------------- ### Load IR from Protobuf Source: https://grammatech.github.io/gtirb/python/gtirb.ir.html Use the load_protobuf method to initialize an IR instance from a GTIRB file. ```python >>> ir = IR.load_protobuf('filename.gtirb') ``` -------------------------------- ### getBinding() - ElfSymbolInfoTuple Source: https://grammatech.github.io/gtirb/java/index-all.html Gets the binding type. ```APIDOC ## getBinding() ### Description Get the binding type. ### Method GET ### Endpoint com.grammatech.gtirb.ElfSymbolInfoTuple#getBinding() ### Parameters None ### Response Returns the binding type. ``` -------------------------------- ### getBinaryName() - ProbFuncName Source: https://grammatech.github.io/gtirb/java/index-all.html Gets the binary-level name. ```APIDOC ## getBinaryName() ### Description Get the binary-level name. ### Method GET ### Endpoint com.grammatech.gtirb.ProbFuncName#getBinaryName() ### Parameters None ### Response Returns the binary-level name. ``` -------------------------------- ### gtirb.serialization.Serialization.__init__ Source: https://grammatech.github.io/gtirb/python/gtirb.serialization.html Initialize with the built-in gtirb.serialization.Codec subclasses. ```APIDOC ## gtirb.serialization.Serialization.__init__ ### Description Initialize with the built-in gtirb.serialization.Codec subclasses. ### Method __init__ ### Parameters None ### Return Type None ``` -------------------------------- ### Visualize GTIRB CFG with show-cfg.py Source: https://grammatech.github.io/gtirb/show-cfg_8py-example.html This script loads a GTIRB IR from a file, iterates through the CFG edges, and uses NetworkX to draw the graph. ProxyBlocks are represented by their UUIDs, while standard blocks are represented by their addresses. ```python #!/usr/bin/python # # An example program which opens an IR and draws the CFG to the screen. # # To run this example, do the following. # # 1. Install the gtirb package from Pypi. # # 2. Run ddisasm to disassemble a binary to GTIRB. # # $ echo 'main(){puts("hello world");}'|gcc -x c - -o /tmp/hello # $ ddisasm /tmp/hello --ir /tmp/hello.gtirb # # 3. Execute the following command to run the program on the # serialized GTIRB data. # # $ ./doc/examples/show-cfg.py /tmp/hello.gtirb import sys import matplotlib.pyplot as plt import networkx as nx import gtirb if len(sys.argv) < 2: print(f"Usage: {sys.argv[0]} /path/to/file.gtirb") quit(1) ir = gtirb.ir.IR.load_protobuf(sys.argv[1]) G = nx.DiGraph() for edge in ir.cfg: if isinstance(edge.target, gtirb.block.ProxyBlock): # Represent ProxyBlocks (which don't have an address) with their UUID. G.add_edge(edge.source.address, edge.target.uuid) else: G.add_edge(edge.source.address, edge.target.address) nx.draw(G, with_labels=True) plt.show() ``` -------------------------------- ### ByteInterval.getSection() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/class-use/Section.html Gets the section this ByteInterval belongs to. ```APIDOC ## ByteInterval.getSection() ### Description Gets the section this ByteInterval belongs to. ### Method getSection ### Returns - **java.util.Optional
** - The section, if present. ``` -------------------------------- ### aux_data_begin() Source: https://grammatech.github.io/gtirb/cpp/classgtirb_1_1_aux_data_container.html Returns a constant iterator to the first AuxData in the container. ```APIDOC ## aux_data_begin() ### Description Return a constant iterator to the first AuxData. ### Returns const_aux_data_iterator ``` -------------------------------- ### ProxyBlock.__init__ Source: https://grammatech.github.io/gtirb/python/gtirb.block.html Constructor for ProxyBlock, a placeholder for CFG edges. Initializes with UUID and module. ```APIDOC ## ProxyBlock.__init__ ### Description Constructor for ProxyBlock, a placeholder for CFG edges. ### Parameters - **uuid** (typing.Optional[uuid.UUID]) - Optional - The UUID of this Node, or None if a new UUID needs generated via uuid.uuid4(). Defaults to None. - **module** (typing.Optional[gtirb.module.Module]) - Optional - The module this block belongs to. ``` -------------------------------- ### getIr() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Module.html Get the `IR` this Module belongs to. ```APIDOC ## getIr() ### Description Get the `IR` this Module belongs to. ### Returns An Optional that contains the IR this module belongs to, or empty if it does not belong to an IR. ``` -------------------------------- ### findByteIntervalsAt Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Section.html Get all ByteIntervals that begin at an address. ```APIDOC ## findByteIntervalsAt ### Description Get all ByteIntervals that begin at an address. ### Method findByteIntervalsAt ### Parameters - `address` (long) - Required - The address to look for. ### Returns A list of ByteIntervals that that start at this address, or null if none. ``` -------------------------------- ### Create() [2/4] Source: https://grammatech.github.io/gtirb/cpp/classgtirb_1_1_symbol.html Creates a Symbol object with an address, name, and optional AtEnd flag. ```APIDOC ## Create() [2/4] ### Description Creates a Symbol object with an address, name, and optional AtEnd flag. ### Method Create ### Signature static Symbol* gtirb::Symbol::Create(Context& _C_, Addr _X_, const std::string& _Name_, bool _AtEnd_ = false) ### Parameters - **C** (Context&) - Required - The Context in which this object will be held. - **X** (Addr) - Required - The address of the symbol. - **Name** (const std::string&) - Required - The name of the symbol. - **AtEnd** (bool) - Optional - If true, this symbol points to the end of its referent, rather than at the beginning. Defaults to false. ### Returns The newly created object. ``` -------------------------------- ### Module constructor for minimal module Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Module.html Creates a Module with no sections, symbols, or proxy blocks. Takes binary path, preferred address, rebase delta, file format, ISA, and name. ```java public Module​(java.lang.String binaryPath, long preferredAddr, long rebaseDelta, Module.FileFormat fileFormat, Module.ISA isa, java.lang.String name) ``` -------------------------------- ### findByteIntervalsOn Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Section.html Get all ByteIntervals containing an address. ```APIDOC ## findByteIntervalsOn ### Description Get all ByteIntervals containing an address. ### Method findByteIntervalsOn ### Parameters - `address` (long) - Required - The address to look for. ### Returns A list of ByteIntervals that intersect this address, or empty list if none. ``` -------------------------------- ### getIndex Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Section.html Get the index to manage this Section with. ```APIDOC ## getIndex ### Description Get the index to manage this Section with. This index is used for storing and retrieving the Section, as required by the TreeListItem interface. Sections are ordered by address, so this method just returns the address. ### Method getIndex ### Returns The ByteInterval index, which is it's address. ``` -------------------------------- ### Calculate CFG paths with Python Source: https://grammatech.github.io/gtirb/cfg-paths_8py-example.html This script loads a GTIRB file, maps the CFG to a NetworkX directed graph, and prints all simple paths between two provided addresses. It handles ProxyBlocks by using their UUIDs since they lack explicit addresses. ```python #!/usr/bin/python # # An example program which opens an IR and prints all paths between # two blocks. # # To run this example, do the following. # # 1. Install the gtirb package from Pypi. # # 2. Run ddisasm to disassemble a binary to GTIRB. # # $ echo 'main(){puts("hello world");}'|gcc -x c - -o /tmp/hello # $ ddisasm /tmp/hello --ir /tmp/hello.gtirb # # 3. Execute the following command to run the program on the # serialized GTIRB data. # # $ ./doc/examples/cfg-paths.py /tmp/hello.gtirb import sys import networkx as nx import gtirb if len(sys.argv) < 4: print(f"Usage: {sys.argv[0]} /path/to/file.gtirb source target") quit(1) ir = gtirb.ir.IR.load_protobuf(sys.argv[1]) G = nx.DiGraph() for edge in ir.cfg: if isinstance(edge.target, gtirb.block.ProxyBlock): # Represent ProxyBlocks (which don't have an address) with their UUID. G.add_edge(edge.source.address, edge.target.uuid) else: G.add_edge(edge.source.address, edge.target.address) for path in nx.all_simple_paths(G, int(sys.argv[2]), int(sys.argv[3])): print(path) ``` -------------------------------- ### Load GTIRB in C++ Source: https://grammatech.github.io/gtirb/md_stack-stamp.html Initialize the GTIRB context and load the binary representation in C++. ```cpp #include gtirb::Context Ctx; std::ifstream File("ls.gtirb"); gtirb::IR* Ir = *gtirb::IR::load(Ctx, File); ``` -------------------------------- ### getSectionFlags Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Section.html Get the flags applying to this Section. ```APIDOC ## getSectionFlags ### Description Get the flags applying to this Section. ### Method getSectionFlags ### Returns An unmodifiable `Section.SectionFlag` set of all the section flags of this `Section`. ``` -------------------------------- ### getVersion() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/IR.html Get the protobuf version of this IR. ```APIDOC ## getVersion() ### Description Get the protobuf version of this IR. ### Method Instance method ### Signature `public int getVersion()` ### Returns - **int** - The protobuf version. ``` -------------------------------- ### Node.__init__(uuid=None) Source: https://grammatech.github.io/gtirb/python/gtirb.node.html Initializes a new Node instance. If a UUID is not provided, a new one is generated using uuid.uuid4(). ```APIDOC ## Node.__init__(uuid=None) ### Description Initializes a new Node instance. If a UUID is not provided, a new one is generated using uuid.uuid4(). ### Method Constructor ### Parameters - **uuid** (typing.Optional[uuid.UUID]) - Optional - The UUID of this Node, or None if a new UUID needs generated via uuid.uuid4(). Defaults to None. ### Returns None ``` -------------------------------- ### symbols_begin() const Source: https://grammatech.github.io/gtirb/cpp/classgtirb_1_1_module.html Returns a constant iterator to the first Symbol in the module. ```APIDOC ## symbols_begin() const ### Description Return a constant iterator to the first Symbol in the module. ### Method Function ### Signature const_symbol_iterator symbols_begin() const ### Parameters None ### Returns - **const_symbol_iterator** - Constant iterator to the first Symbol. ``` -------------------------------- ### getCfg() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/IR.html Get the CFG belonging to this IR. ```APIDOC ## getCfg() ### Description Get the CFG belonging to this IR. ### Method Instance method ### Signature `public CFG getCfg()` ### Returns - **CFG** - The CFG belonging to this IR. ``` -------------------------------- ### getName() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/AuxDataContainer.AuxData.html Get the name of the AuxDataContainer.AuxData instance. ```APIDOC ## getName() ### Description Get the `AuxDataContainer.AuxData` name. ### Method `public java.lang.String getName()` ### Returns - **String** - the name. ``` -------------------------------- ### Iterating over Module.ISA constants with values() Source: https://grammatech.github.io/gtirb/java/com/grammatech/gtirb/Module.ISA.html Shows how to iterate over all Module.ISA constants using the values() method and print each one. ```java for (Module.ISA c : Module.ISA.values()) System.out.println(c); ```