Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

In angr, how to map and initialize a readonly memory region

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o4-mini-2025-04-16’s answer.
  1. User

    In angr, how to map and initialize a readonly memory region

  2. Gemini Assistant

    In Angr, to map and initialize a read-only memory region, you generally follow these steps:

    1. Map the region with temporary write permissions: You need write permissions initially to store the data into the memory.
    2. Store the initial data: Use state.memory.store() to write your desired content to the newly mapped region.
    3. Change the permissions to read-only: After initialization, use state.memory.set_permissions() to remove the write permission, making the region read-only.

    Here's a detailed example:

    import angr
    import claripy
    
    # 1. Create a Project and an initial State
    # We use a simple binary like /bin/true to get a basic environment.
    p = angr.Project('/bin/true', auto_load_libs=False)
    state = p.factory.entry_state()
    
    # 2. Define the region details and content
    RO_DATA_ADDR = 0x70000000  # Choose a high address unlikely to conflict
    RO_DATA_SIZE = 0x1000       # A common page size (4KB)
    RO_DATA_CONTENT = b"Hello, Angr! This is my super secret read-only data."
    RO_DATA_CONTENT += b"\x00" * (RO_DATA_SIZE - len(RO_DATA_CONTENT)) # Pad with null bytes to fill the page
    
    print(f"Preparing to map a read-only region at 0x{RO_DATA_ADDR:x} (size: 0x{RO_DATA_SIZE:x})...")
    
    # 3. Map the region with temporary write permissions (Read | Write)
    # We need 'w' permission initially to be able to store data.
    print(f"Mapping region with R|W permissions at 0x{RO_DATA_ADDR:x}...")
    state.memory.map_region(RO_DATA_ADDR, RO_DATA_SIZE,
                            state.memory.permissions.r | state.memory.permissions.w)
    
    # 4. Initialize the data
    print(f"Storing data at 0x{RO_DATA_ADDR:x}...")
    state.memory.store(RO_DATA_ADDR, RO_DATA_CONTENT)
    
    # 5. Set the region to read-only (Read only)
    # Now, we remove the write permission.
    print(f"Setting permissions to R (read-only) for region at 0x{RO_DATA_ADDR:x}...")
    state.memory.set_permissions(RO_DATA_ADDR, RO_DATA_SIZE, state.memory.permissions.r)
    
    print("\n--- Verification ---")
    
    # 6. Verify by trying to read the data (should succeed)
    print("Attempting to read from the read-only region...")
    try:
        read_data = state.memory.load(RO_DATA_ADDR, len(RO_DATA_CONTENT))
        # Evaluate the symbolic data to concrete bytes
        concrete_read_data = state.solver.eval(read_data, cast_to=bytes)
        print(f"Successfully read data: {concrete_read_data}")
        assert concrete_read_data == RO_DATA_CONTENT
        print("Read data matches original content.")
    except Exception as e:
        print(f"ERROR: Failed to read data: {e}")
    
    
    # 7. Verify by trying to write to the read-only region (should fail with SimSegfaultError)
    print("\nAttempting to write to the read-only region (should cause a segfault)...")
    try:
        # Try to store a small value at an offset
        state.memory.store(RO_DATA_ADDR + 4, claripy.BVV(0xDEADBEEF, 32))
        print("ERROR: Successfully wrote to read-only memory. This shouldn't happen!")
    except angr.errors.SimSegfaultError as e:
        print(f"SUCCESS: Caught expected SimSegfaultError when writing: {e}")
    except Exception as e:
        print(f"ERROR: Caught an unexpected exception: {type(e).__name__}: {e}")
    
    print("\n--- All checks complete ---")
    

    Explanation:

    1. angr.Project('/bin/true', auto_load_libs=False): We create a minimal Angr project. The specific binary doesn't matter much for this example, but Angr requires one to set up its initial environment. auto_load_libs=False prevents Angr from loading shared libraries, making the setup faster and cleaner for simple memory operations.
    2. state = p.factory.entry_state(): We get an initial program state. All memory operations happen on this state object.
    3. RO_DATA_ADDR, RO_DATA_SIZE, RO_DATA_CONTENT: These define the characteristics of our read-only region.
      • RO_DATA_ADDR: It's good practice to choose a high address (e.g., in the 0x70000000 range) to avoid conflicts with common program segments (text, data, stack, heap).
      • RO_DATA_SIZE: Typically a multiple of a page size (4KB or 0x1000 on most systems).
      • RO_DATA_CONTENT: The actual bytes you want to store. We pad it with null bytes (\x00) to ensure it fills the entire RO_DATA_SIZE for clean mapping.
    4. state.memory.map_region(addr, length, permissions): This is the core method for mapping memory.
      • addr: The starting address of the region.
      • length: The size of the region in bytes.
      • permissions: This is a bitmask of permissions. Angr provides constants in state.memory.permissions:
        • r: Read permission
        • w: Write permission
        • x: Execute permission
        • We initially use state.memory.permissions.r | state.memory.permissions.w (read OR write) to allow writing.
    5. state.memory.store(addr, data): This writes data (which should be a bytes object or a claripy.BVV for concrete data) starting at addr. This operation requires write permissions for the target memory.
    6. state.memory.set_permissions(addr, length, permissions): This is crucial for changing the permissions of an already mapped region. After storing the data, we call this with state.memory.permissions.r to revoke the write permission, making the region read-only.
    7. Verification:
      • We attempt to load the data, which should succeed if the region is readable.
      • We then attempt to store data into the read-only region. This should raise an angr.errors.SimSegfaultError, indicating that the write operation was denied due to insufficient permissions. This confirms the region is indeed read-only.

    This approach provides a robust way to manage memory permissions in Angr, allowing you to simulate protected memory regions accurately.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.