Mach-O header analysis and editing

1.16.4 · active · verified Sat Apr 11

macholib is a Python library used for analyzing and editing Mach-O headers, the executable format employed by macOS. It functions primarily as a dependency analysis tool, capable of rewriting dylib references within Mach-O headers to be @executable_path relative. The library is pure Python, platform, and endian-independent, currently at version 1.16.4, with active development and regular releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a Mach-O binary using `macholib.MachO` and then iterate through its linked libraries, attempting to resolve their paths using `macholib.dyld.dyld_find`. It prints the architecture and dependencies of a specified Mach-O file.

import os
from macholib.MachO import MachO
from macholib import dyld

def get_macho_dependencies(filepath):
    try:
        macho = MachO(filepath)
        print(f"Analyzing: {filepath}")
        for header in macho.headers:
            print(f"  Architecture: {header.architecture()}")
            for idx, name, other in header.walk_libraries():
                resolved_name = dyld.dyld_find(name, executable_path=filepath)
                print(f"    Depends on: {name} (Resolved: {resolved_name})")
    except Exception as e:
        print(f"Error processing {filepath}: {e}")

# Example usage with a common macOS binary
# Ensure the file exists, e.g., '/usr/bin/ls'
system_binary = os.environ.get('MACHO_BINARY_PATH', '/usr/bin/ls')
if os.path.exists(system_binary):
    get_macho_dependencies(system_binary)
else:
    print(f"Skipping quickstart: {system_binary} not found. Set MACHO_BINARY_PATH to a valid Mach-O file.")

view raw JSON →