mach_vm_region_recurse, mapping memory and shared

2020-06-04 16:01发布

问题:

I'm using vm_region_recurse_64 to map out the memory for a given process, vmmap style.

Trying to get a complete list of shared libraries loaded by the application by examining each library's Mach-O header in memory, however, vm_region_recurse seems to disagree with the vmmap command line tool about specifically where some of the specific memory sections begin and end.

This becomes especially true in the 90000000-a0000000 system submap where most of the os shared libraries are loaded.

And now I'm kind of stumped. I can list memory segments, tell generally what type they are, and read from them with vm_read. But listing them and getting correct and specific region info is proving difficult.

How does vmmap get listings of the specific locations at which libraries are loaded? My method seems to be ineffective.

Edit: here's the basic code I'm using. It returns a memory map similar to but not identical to vmmap's. Doesn't have memory regions of specific libraries.

kern_return_t krc = KERN_SUCCESS;
vm_address_t address = 0;
vm_size_t size = 0;
uint32_t depth = 1;
while (1) {
    struct vm_region_submap_info_64 info;
    mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
    krc = vm_region_recurse_64(port, &address, &size, &depth, (vm_region_info_64_t)&info, &count);
    if (krc == KERN_INVALID_ADDRESS){
        break;
    }
    if (info.is_submap){
        depth++;
    }
    else {
        //do stuff
        printf ("Found region: %08x to %08x\n", (uint32_t)address, (uint32_t)address+size);
        address += size;
    }
}

回答1:

vmmap calls mach_vm_region_recurse() to list the memory regions.

In order to see the contents of submaps like the dyld shared cache at 0x90000000..0xa0000000, you'll need to look for regions with is_submap set, and then call mach_vm_region_recurse() again with the same address and a deeper nesting_depth.



回答2:

vmmap(1) actually gets a listing of the Mach-O images loaded in the process, by inspecting DYLD tables left in the target address space.