Working with Variables

Everything concerning variables of a function is managed through the function’s variable_manager which is a VariableManagerModel data model.

Data model or structure for variables - VariableManagerModel VariableModel SSAVariableModel

4. get variables defined or used at a specific step

Getting variables used at a specific step/instruction.

fn = api.get_function_by_id(fid="/example/src/01_print_pointer_value.cc:main#1")

step_index = 1
print(f"{fn.steps[step_index].decompile()}")

# output
"""
p = &c;
"""

for var in fn.variable_manager.used_at_step(step_index):
    print(f"variables_used_at_step = {var.name}")

# output
"""
variables_used_at_step = p
"""

Getting variables defined at a specific step/instruction.

fn = api.get_function_by_id(fid="/example/src/01_print_pointer_value.cc:main#1")

step_index = 1
print(f"{fn.steps[step_index].decompile()}")

# output
"""
p = &c;
"""

for var in fn.variable_manager.defined_at_step(step_index):
    print(f"variables_defined_at_step = {var.name}")

# output
"""
variables_defined_at_step = c
"""

Getting variables, whether defined or used, at a specific step/instruction.

fn = api.get_function_by_id(fid="/example/src/01_print_pointer_value.cc:main#1")

step_index = 1
print(f"{fn.steps[step_index].decompile()}")

# output
"""
p = &c;
"""

for var in fn.variable_manager.used_or_defined_at_step(step_index):
    print(f"variables_used_or_defined_at_step = {var.name}")

# output
"""
variables_used_or_defined_at_step = p
variables_used_or_defined_at_step = c
"""

5. get specific variable object by name

Getting a variable by name.

varname = "$T1"
var = fn.variable_manager.get(varname)
print(var)

# output
vid='/example/src/01_print_pointer_value.cc:main:$T1' name='$T1' vartype=<VarType.TMP_VARIABLE: 'TMP_VARIABLE'> unique_ssa_variables={'$T1_1': SSAVariableModel(ssa_name='$T1_1', ssa_version=1, variable_name='$T1', variable_defined_at_steps=[2], variable_used_at_steps=[3], variable_used_in_callsites=['printf_3'], record_attributes_defined_at_steps={}, ..[redacted]...

6. searching variables globally across all functions

Search for variables globally using filter_by_name, filter_by_filepath, filter_by_type_decl, is_local_var, is_tmp and is_farg. You can combine these filters in any way to tailor your search.

for fn, var in api.search_variables(filter_by_name="argc"):
    print(f"fid={fn.fid}, varname={var.name}")

"""
fid=/example/src/16_buffer_overflow.cc:main#1, varname=argc
fid=/example/src/16_uninitializede_var_use.cc:main#1, varname=argc
"""

7. searching variables within a single function

We can also search for variables within a function.

for var in fn.variable_manager.search(name="argc"):
    print(f"varname={var.name}")

"""
varname=argc
"""

6. get total variables

Get total number of variables in database.

print("total_variables =", api.get_total_variables())

# output
"""
total_variables = 1286646
"""