How iOS traverses the module

Source: Internet
Author: User

Way One:
Through the Mach_vm_region system API
Reference code: HTTPS://GITHUB.COM/DAVIDRHODUS/MISC/BLOB/MASTER/IOS-INTERNALS/VMMAP.C

#include <mach/vm_map.h> #include <stdio.h> #include <mach-o/dyld_images.h>/** * VMMAP (1) Clone for OS   X and IOS *-------------------------------* * This was a simple example of using the Mach_vm_region_info APIs in order to * Obtain a process ' (technically, a task ' s) virtual memory address space, in a * manner Akin To/proc/[pid]/maps on Linu  X. * The process is simple-get the task port and then call Mach_vm_region_info until * you ' ve exhausted the address space (in IOS this happens around 0x40000000, * where the commpage is).  On IOS 6, for some peculiar reason the task port was * invalidated after all call, so the quick workaround here solves the Problem * by regetting the port. The actual Mach error code to check for are in the header * files, though the code simply tries regetting.  * * N.b-for This code to work, you must provide the entitlements to allow * task-for-pid to work, else you'll fail with Error 5. The entitlements is in * the output in Chapter 3, bUT for those of Haven ' t bought the book, it would is: *---Cut here <! DOCTYPE plist Public "-//apple//dtd plist 1.0//en" "Http://www.apple.com/DTDs/PropertyList-1.0.dtd" ><plist        Version= "1.0" ><dict> <key>com.apple.springboard.debugapplications</key> <true/> <key>get-task-allow</key> <true/> <key>proc_info-allow</key> < true/> <key>task_for_pid-allow</key> <true/> <key>run-unsigned-code</ke Y> <true/></dict></plist>---Ok, enough:-) * * So-copy the above XML to a file, say, "Ent. XML ", and is sure to run" ldid-sent.xml vmmap "* Before trying to run this. You can download the binary (already thus signed) if you ' re lazy * (and trust me, because you *will* need root on your I Device for this) * as the book clearly states, once the task port, and the world is your oyster. You can * CONtrol the entire virtual memory space, reading and writing it as you. Stay tuned * for the corrupt tool (which'll be is provided soon in binary form) * */int g_pid = 0;     Required in IOS 6 (read below)/* 03/08/13-added List of Mach-o images: */struct dyld_image_info *g_dii = Null;int g_imagecount;//read process memory data unsigned char *readprocessmemory (int pid, mach_vm_address_t addr, mach_msg_type_number_t *size ) {//Helper function to the read process memory (a la Win32 API of same name)//To make it easier for inclusion ELSEWH Ere, it takes a PID, and//Does the task_for_pid by itself. Given that IOS invalidates task ports//After use, it's actually a good idea, since we ' d need to reget anyway task_    T T;        Get tasks in Process Task_for_pid (Mach_task_self (), PID, &t);        mach_msg_type_number_t datacnt = size;    vm_offset_t Readmem;        Use Vm_read, rather than mach_vm_read, since the latter are different/in IOS. Get memory kern_return_t kr = vm_Read (t,//vm_map_t Target_task, Task addr,//mach_vm_address_t address, corresponding addresses in the task                     *size,//mach_vm_size_t size &readmem,//vm_offset_t *data,     size);                mach_msg_type_number_t *datacnt if (KR) {///DANG:                 fprintf (stderr, "Unable to read target task ' s memory @%p-kr 0x%x\n", addr, KR);                return NULL; } return ((unsigned char *) readmem);} Kern_return_t Mach_vm_read (vm_map_t, mach_vm_address_t, mach_vm_size_t, vm_offset_t *, mach_msg_type_number_t *);//        Windfall Search memory void Findlistofbinaries (task_t t, mach_vm_address_t addr, int size) {kern_return_t kr;        mach_msg_type_number_t datacnt = size;        Reads the contents of the specified size on the specified memory address unsigned char *readdata = readprocessmemory (g_pid, addr, &datacnt);    int machsig = 0xfeedface; Checking only 0xfeedfa are a simple "to catch" both 64-bit (FACF) anD 32-bit (face) headers//Machine endianness are automatically taken care of, too.        Determine if macho header if (readdata && memcmp (readdata + 1, (((unsigned char *) &machsig) + 1, 3) = = 0) {        This is a Mach header int i = 0; A MUCH better would is to iterate through the LC and find the name of DYLD//It's would require my Mach        LIB.C (closed source) and really get the same result.        This works because on both IOS and OS X Dyld is at/usr/lib. for (i = 0; I <dataCnt; i++) {//Cycles compare if the memory content is "Lib/dyld" if (memcmp (Readdata+i, "Lib/dyl                D ", 8) = = 0) {unsigned int dyld_all_image_infos_offset;                int imagecount = 0; Copy Import module information memcpy (&dyld_all_image_infos_offset, Readdata+dyld_all_image_infos_offset_offset, sizeof (                 unsigned int));                 struct Dyld_all_image_infos *dyldaii; Safeguard: Should check Dyld_all_image_infos_offset is < size: if (Dyld_all_image_infos_offset > Size) {//This was to be expected, since the dyld_a Ll_image_infos is in a data region//printf ("Offset%x are greater than region size:%x\n", dyld_all_i                    Mage_infos_offset, size);                    datacnt = sizeof (DYLD_ALL_IMAGE_INFOS);                    ReadData = ReadProcessMemory (g_pid, addr + dyld_all_image_infos_offset, &datacnt);                    if (!readdata) {return;}                Dyldaii = (struct Dyld_all_image_infos *) readdata; } else {Dyldaii = (struct Dyld_all_image_infos *) (ReadData +dyld_all_im                Age_infos_offset); } printf ("Version:%d,%d images at offset%p\n", Dyldaii->version, dyldaii->                Infoarraycount, Dyldaii->infoarray); Go to Dyldaii->iNfoarray Address Imagecount = dyldaii->infoarraycount;                Save Import Module Information datacnt = imagecount * sizeof (struct dyld_image_info);                g_dii = (struct Dyld_image_info *) malloc (datacnt);                G_imagecount = Imagecount;                ReadData = ReadProcessMemory (G_pid, Dyldaii->infoarray, &datacnt);                if (!readdata) {return;}                struct Dyld_image_info *dii = (struct dyld_image_info *) readdata;                        We don ' t need I anymore, anyway for (i = 0; i < Imagecount; i++) {                        datacnt = 1024;                        Char *imagename = readprocessmemory (G_pid, Dii[i].imagefilepath, &datacnt);                        if (imageName) G_dii[i].imagefilepath = StrDup (imageName);                        else G_dii[i].imagefilepath = NULL;                    g_dii[i].imageloadaddress = dii[i].imageloadaddress;      }          Break }}}}/* End 03/08/13 */char *behavior_to_text (vm_behavior_t b) {switch (b) {case Vm_behavior_defa        Ult:return ("Default");        Case Vm_behavior_random:return ("RANDOM");        Case Vm_behavior_sequential:return ("Fwd-seq");        Case Vm_behavior_rseqntl:return ("Rev-seq");        Case Vm_behavior_willneed:return ("Will-need");        Case Vm_behavior_dontneed:return ("Will-need");        Case Vm_behavior_free:return ("Free-nowb");        Case Vm_behavior_zero_wired_pages:return ("Zero-wire");        Case Vm_behavior_reusable:return ("reusable");        Case Vm_behavior_reuse:return ("reuse");        Case Vm_behavior_can_reuse:return ("Canreuse");    Default:return ("?"); }}//Memory Attribute Char *protection_bits_to_rwx (vm_prot_t p) {//Previous version of this somehow lost the ' p& ', always Returni  Ng rwx.  static Char returned[4]; Returned[0] = (P &vm_prot_read?)  ' R ': '-'); RETURNED[1] = (P &vm_prot_write?) ' W ' : ‘-‘); RETURNED[2] = (P & vm_prot_execute?)  ' X ': '-'); RETURNED[3] = ' + '; Memory leak here. No Biggy Return (StrDup (returned));}    Current memory State const char *unparse_inheritance (vm_inherit_t i) {switch (i) {case Vm_inherit_share:return "SHARE";    Case Vm_inherit_copy:return "COPY";    Case Vm_inherit_none:return "NONE";    Default:return "???";  }}macosx_debug_regions (task_t task, mach_vm_address_t address, int max) {kern_return_t kret;  mach_vm_address_t prev_address; /* @TODO: warning-potential overflow Here-gotta fix this.  */vm_region_basic_info_data_t Prev_info,info;  mach_vm_size_t size, prev_size;  mach_port_t object_name;  mach_msg_type_number_t count;  Total number of blocks read by the module int nsubregions = 0;  Number of modules traversed int num_printed = 0;  Count = vm_region_basic_info_count_64; Kret = mach_vm_region (Task, &address, &size, Vm_region_basic_info, (vm_region_info_t) &info, &amp  ; count, &object_name); if (Kret! = kern_succesS) {printf ("Mach_vm_region:error%d-%s", Kret, Mach_error_string (Kret));    Return  }//Save the last traversed module information memcpy (&prev_info, &info, sizeof (vm_region_basic_info_data_t));  prev_address = address;  prev_size = size;  Acquired 1 blocks of nsubregions = 1;    for (;;)      {int print = 0;      int done = 0;      Address = prev_address + prev_size; /* Check to see if the address space has wrapped around.    *///Traverse module End if (address = = 0) {print = done = 1; } if (!done) {///Even on IOS, we use vm_region_basic_info_count_64.          This works.          Count = vm_region_basic_info_count_64; Read the first correct module information starting from address, note that this may not be a module header Kret = mach_vm_region (Task, &address, &size, Vm_regi          On_basic_info, (vm_region_info_t) &info, &count, &object_name);    if (kret! = kern_success) {/* IOS 6 workaround-attempt to reget the task port to AvoiD */    /* "(ipc/send) Invalid destination port" (1000003 or something) */Task_for_pid (mach_task_self (), G_pid, &ta        SK);                              Get it again Kret = mach_vm_region (Task, &address, &size, Vm_region_basic_info,        (vm_region_info_t) &info, &count, &object_name); } if (Kret! = kern_success) {fprintf (stderr, "Mach_vm_region failed for address%p-error:%x\n", addres              S, (Kret));    size = 0;              if (address >= 0x4000000) return;            print = done = 1; }}//If the previous memory start address + memory size!      = Current address, description is the new module if (address! = prev_address + prev_size) print = 1; If the memory attributes are different, the description is the new module if ((info.protection! = prev_info.protection) | | (info.max_protection! = prev_info.max_protection) | | (info.inheritance! = prev_info.inheritance) | | (info.shared! = prev_info.reserved) | |        (info.reserved! = prev_info.reserved))  print = 1;    If it is a new module, get its other information if (print) {int print_size;          Char *print_size_unit;          if (num_printed = = 0) printf ("Region"); else printf ("...       ");      Findlistofbinaries (Task, prev_address, prev_size);      /* Quick hack to show size of segment, which GDB does not */print_size = prev_size;      if (Print_size > 1024x768) {print_size/= 1024x768; print_size_unit = "K";}      if (Print_size > 1024x768) {print_size/= 1024x768; print_size_unit = "M";}      if (Print_size > 1024x768) {print_size/= 1024x768; print_size_unit = "G";} /* End Quick hack */printf ("%p-%p [%d%s] (%s/%s;               %s,%s,%s)%s ", (prev_address), (prev_address + prev_size),                           Print_size, Print_size_unit, protection_bits_to_rwx (prev_info.protection),                        PROTECTION_BITS_TO_RWX (prev_info.max_protection),   Unparse_inheritance (prev_info.inheritance), prev_info.shared? "Shared": "Private", prev_info.reserved?          "Reserved": "Not-reserved", Behavior_to_text (Prev_info.behavior));          if (Nsubregions > 1) printf ("(%d sub-regions)", nsubregions);          printf ("\ n");          Save this memory information prev_address = address;          prev_size = size;          memcpy (&prev_info, &info, sizeof (vm_region_basic_info_data_t));          Nsubregions = 1;        num_printed++;          } else {//If it is not a new module, only increase the module size prev_size + = sizes;        nsubregions++;         } if ((Max > 0) && (num_printed >= max) {printf ("Max%d num_printed%d\n", Max, num_printed);    Done = 1;    } if (done) break;    }}void Main (int argc, char **argv) {struct Vm_region_basic_info vmr;    kern_return_t RC;    mach_port_t task;  mach_vm_size_tsize = 8;    vm_region_info_t info = (vm_region_info_t) malloc (10000);    mach_msg_type_number_t Info_count;    mach_port_t object_name;    The initial value is set to 1 mach_vm_address_t addr = 1;    int pid;        The PID if (!argv[1]) {printf ("Usage:%s <pid>\n") for the target process needs to be supplied with parameter 1; exit (1);}    Convert parameter 1 to PID PID = Atoi (Argv[1]); G_pid = pid;    Req for IOS 6//Get task RC for Target process = Task_for_pid (Mach_task_self (), PID, &task);    if (RC) {fprintf (stderr, "Task_for_pid () failed with error%d-%s\n", RC, Mach_error_string (RC)); exit (1);}    printf ("RC%d-task:%d\n", RC, Task);    Macosx_debug_regions (Task, addr, 1000);    int i; for (i = 0; i < G_imagecount; i++) {printf ("Image:%s Loaded @%p\n", G_dii[i].imagefilepath, G_d    ii[i].imageloadaddress); } printf ("done\n");}

Way two:
Via _dyld_getImage* Series API

头文件:dyld.h函数原型://获取当前进程加载的模块数。uint32_t                    _dyld_image_count(void);//获取内存中某个模块的头部指针。const struct mach_header*   _dyld_get_image_header(uint32_t image_index);//获取内存中某个模块的slide值。intptr_t                    _dyld_get_image_vmaddr_slide(uint32_t image_index);// 获取内存中某个模块的名称。const char*                 _dyld_get_image_name(uint32_t image_index);实现:#importint32_t nModNums= _dyld_image_count();const char *pszModName = NULL;intptr_t pModSlide = 0;const struct mach_header* pModHeader = NULL;for (uint32_t i = 0; i < nModNums; i++){pModSlide  = _dyld_get_image_vmaddr_slide(i);pszModName = _dyld_get_image_name(i);pModHeader = _dyld_get_image_header(i);}

How iOS traverses the module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.