GrammaTech / gtirb-rewriting

Python API for rewriting GTIRB files
GNU General Public License v3.0
16 stars 3 forks source link

Can I recognize a specific function and add some code? #12

Closed penq123 closed 8 months ago

penq123 commented 9 months ago

Can I recognize a specific function and add some code? For example, recognize a function called test() and add some instructions?How do I do that?

jranieri-grammatech commented 9 months ago

Assuming the binary has symbols and ddisasm performed function inference (the default), that's pretty straightforward. Here's an entirely untested program that I think should be close to what you're after.

from gtirb_rewriting import (
    Pass,
    patch_constraints,
    Patch,
    SingleBlockScope,
    BlockPosition,
)
import gtirb_rewriting.driver

class NopTest(Pass):
    def begin_module(self, module, functions, context):
        func = next(func for func in functions if func.get_name() == "test")
        for block in func.get_entry_blocks():
            context.register_insert(
                SingleBlockScope(block, BlockPosition.ENTRY),
                Patch.from_function(self.nop_patch),
            )

    @patch_constraints()
    def nop_patch(self, insertion_context):
        return "nop"

if __name__ == "__main__":
    gtirb_rewriting.driver.main(NopTest)