size_impact_analysis_of_functions_in_elf.py

mail@pastecode.io avatar
unknown
python
a month ago
1.4 kB
3
Indexable
Never
#!/usr/bin/env python3
import sys
import r2pipe

# Initialize r2pipe
r2 = r2pipe.open(sys.argv[1])
r2.cmd('aaa')

# Get the functions
funcs = r2.cmdj('aflj')

# Create necessary mappings
func_sizes = {f['name']: f['size'] for f in funcs}
addr_to_name = {f['offset']: f['name'] for f in funcs}

def compute_total_size(func_name, counted_funcs):
    if func_name in counted_funcs:
        return 0

    counted_funcs.add(func_name)

    size = func_sizes[func_name]
    for callee in func_to_callees.get(func_name, []):
        callee_size = compute_total_size(callee, counted_funcs)
        size += callee_size

    return size

# A map from a function to its list of unique callees
func_to_callees = {}
for func in funcs:
    func_name = func['name']
    unique_callees = set()
    for callee in func.get('callrefs', []):
        if callee['type'] == 'CALL' or True:
            callee_name = addr_to_name.get(callee['addr'])
            if callee_name:
                unique_callees.add(callee_name)
    func_to_callees[func_name] = list(unique_callees)

# Compute and update sizes
for func in funcs:
    counted_funcs = set()
    func['size'] = compute_total_size(func['name'], counted_funcs)

# Print the results
for func in sorted(funcs, key=lambda f: f['size'], reverse=False):
    print(f"{func['name']}: {func['size']} bytes")

# Close r2pipe
r2.quit()
Leave a Comment