iOS memory management and malloc source code interpretation

Source: Internet
Author: User
<span id="Label3"></p>0. iOS Memory Fundamentals<p><p>When it comes to iOS development, we all know the concept of "reference counting" and know about arc and mrr, but this is just memory management of objects on the heap memory. In a session with wwdc, this is actually just the tip of the iceberg of memory Management.</p></p><p><p>In memory management, in fact, iOS and other operating systems in general are similar, the large framework of the basic principle of similarity, small details are innovative and different.</p></p><p><p>Similar to the processes running on other operating systems, the address space of the IOS app process is also divided into code area, data area, stack area, and heap Area. At the beginning of the process, the parts of the Mach-o file are loaded into memory as Needed.</p></p><p><p></p></p><p><p>And for the general iphone, the actual physical memory is around 1G, for the extra-large memory requirements how to do? In fact, this is the same as other operating systems, all by the system kernel to maintain a set of virtual memory System. however, It is important to note that iOS has a slightly different principle of virtual storage system, the most distinct of which is the processing when physical memory is Tense.</p></p><p><p>When physical memory is tight, iOS will clean up the contents of the content that can be loaded by remapping, and for non-renewable data, iOS needs the app process to work with, and sends memory warning to each process to release memory. For not releasing enough memory in time, kill the process directly, necessary and even the foreground running app.</p></p><p><p>As mentioned above, iOS has no swap zone in external memory, no memory page swap out Process.</p></p>1. malloc Fundamentals<p><p>In each area of the iOS app process address space, The most flexible is the heap area, which dynamically allocates memory for the process and is where we often deal with memory.</p></p><p><p>In general, we make [nsobject alloc] calls when new objects are needed, and release the object (arc will do it automatically for you).</p></p><p><p>The calls to these alloc and release methods usually end up going to the Libsystem_malloc.dylib malloc () and the free () function here. Libsystem_malloc.dylib is a memory library outside of the iOS kernel, the memory that our app process needs, first back to the request here, but eventually libsystem_ Malloc.dylib also initiates an application to the iOS system kernel, mapping the actual memory to the address space of the app Process.</p></p><p><p>From the open source of malloc in apple, the principle of malloc is as Follows:</p></p><p><p>malloc memory allocation is based on malloc zone and divides memory allocations by size into nano, tiny, small, large several types, optimal allocation on demand when requested<br>When malloc initializes the default zone for the first call, the default zone is initialized to the nano zone in 64-bit cases, and a scalable zone is initialized as a helper Zone,nano Zone is responsible for the distribution of the Nano size, Scalable Zone is responsible for tiny, small and large memory allocation<br>Each time malloc, according to the incoming size parameter, give priority to the Nano zone for allocation processing, if the size is not in the Nano range, then forwarded to the helper zone Processing.</p></p><p><p><br>(since http://www.tinylab.org/memory-allocation-mystery-%C2%B7-malloc-in-os-x-ios/)</p></p><p><p>The following is a brief explanation of the source of memory allocated on the Nano zone and scalable zone (since the code for Apple Open source is specific to OS x, the specifics may differ from ios, such as address space distribution).</p></p>2. Nano malloc<p><p>In support of 64-bit conditions, malloc prioritizes nano malloc, which is responsible for allocating less than 256B of memory, in units of 16B.</p></p><p><p>The Nano zone allocates memory in the address space range of 0x00006nnnnnnnnnnn (osx 64-bit case), dividing the address space from large to small once into magazine, band, and slot Levels.</p></p> <ul> <ul> <li>Magazine range corresponds to cpu,cpu0 corresponding to mag0,cpu1 corresponding Mag1, and so on;</li> <li>Band range of 2M, continuous memory allocation when the memory is not enough to band to the core request;</li> <li>Slots correspond to the 128K size range in each band, each band is divided into 16 slots, respectively, corresponding to 16B, 32B 、... 256B size, support for their memory allocations</li> </ul> </ul><p><p>Allocation process:</p></p> <ul> <ul> <li>Determine the current CPU corresponding to the mag and the size parameter computed by the slot, to the corresponding metadata linked list of the memory block has been freed up cache, if the check pointer address if there is a problem, no problem directly back;</li> <li>When Nano malloc is first performed, the Nano zone is not cached and directly allocates contiguous address memory directly in the address space of the nano zone range;</li> <li>As the current slot exhaustion in the current band, a new band is requested from the system (each band a fixed size of 2M, which holds 16 128k slots), the base address, the limit address, and the current assigned address are maintained by the meta data structure, and these meta Data is in the form of a two-dimensional array of mag, slot dimensions (mag is the number of processors, slot is 16), and is placed in the Meta_data field of the Nanozone_t.</li> </ul> </ul><p><p>When the app frees memory through free (): malloc library checks the pointer address and, if there is no problem, stores the chunks as a list in the form of a chain. The heads of these lists are placed in the corresponding [mag][slot] element in the Meta_data array.</p></p><p><p>In fact, from the cache to get free memory and free memory will point to this memory area of the pointer to check, if there is a similar address is not aligned, not released/multiple releases, the address and expected mag, slot mismatch, etc. will end with an Error.</p></p><p><p>It's a diagram of a relationship that I've combed out according to my personal understanding, and the key fields of nanozone_t, meta_data_t and other related structures have been drawn out (OSX).</p></p><p><p></p></p><p><p>In addition to allocation and release, when the system memory is tight, the Nano zone needs to return the memory chunk of the cache to the system, mainly through the collection of memory chunks on the free linked list on the meta data that corresponds to each slot.</p></p>3. Brief analysis of memory allocation on scalable zone<p><p>The memory is allocated directly to the scalable zone (hereinafter referred to as szone) for the nano size range or the nano distribution is not Supported. Because the memory allocation on the Szone is more complex than the Nano distribution, the details are numerous, the following is only a brief introduction, interested students can directly read the source Code.</p></p><p><p>The memory allocated on Szone consists of three broad categories of tiny, small, and large, where tiny and small are roughly the same distribution and release process, and the large type is managed in its own way.</p></p><p><p>Tiny and small still follow the principle of Nano distribution, the new memory from the system request and allocation, free after the size in a specific form of cache, for subsequent allocation use. The distribution here is in region, and the band concept in region and nano malloc is very similar, but the difference is that the address space may not be contiguous, and each region has its own bitmap and other descriptive Information. As with the nano, each CPU has a magazine, in addition to the allocation of an index of 1 magazine as a fallback.</p></p><p><p>Here is a schematic.</p></p><p><p></p></p><p><p>In the case of tiny, when assigned:</p></p> <ul> <ul> <li>Determine the magazine index of the processor on which the current thread is located, and find the corresponding magazine Structure.</li> <li>Prioritize whether the last chunk released is exactly equal to the size of the request (both the slot size after alignment), and if it is, return directly.</li> <li>If it is not, it looks for the free cache list of the current request size chunk in the??, if there is a return, and organizes the List.</li> <li>If not, the free list is larger than the current application block, and the closest cache, if any, is returned and the remaining size is placed on the other linked list in the free List. (it is important to note that in general, the free list is divided into 64 slots, the size of the 0-62 mounted chunks is incremented by 16B, and 63 is the place where all the larger memory blocks are Mounted)</li> <li>None of the above can be found at the end of the last region or in the header (if the internal ALSR is supported) to find an idle area Assignment.</li> <li>If still not, all existing region is not available, then remove a usable region from a backup magazine, take it completely over to the current magazine, and then go through the steps Above.</li> <li>If this is not possible, then you can only request a new region in the kernel, mount it to the current magazine, and allocate memory.</li> <li>If no more can not recruit, the system also can not give the memory, the error returns.</li> </ul> </ul><p><p>When Free:</p></p> <ul> <ul> <li>Check that the pointer is pointing to an address for problems.</li> <li>If a memory chunk is not mounted on the last free pointer, it is ok to put it on Last.</li> <li>If there is a last free, replace the memory and attach the previous free memory block to the free list (before the free list is mounted, the chunk can be merged into a larger chunk, if it can be merged into one), based on the region bitmap.</li> <li>If the free bytes exceed certain conditions, the region will be placed in the reserved magazine (-1).</li> <li>If the entire region is empty, it is returned directly to the system kernel, solve Everything.</li> </ul> </ul><p><p>In the case of large, malloc applies and allocates memory in pages, without distinguishing magazine,szone unified maintenance of a hash table to manage the requested Memory. And because the memory area is relatively large, only the total cache of 2G chunks, divided into 16 elements, each maximum is 128M. Large related structure is relatively simple, do not deliberately draw.</p></p><p><p>In summary, iOS memory management and malloc library source collation to This. If you find that the analysis has mistakes or incomplete description, please feel free to say, Welcome to Exchange.</p></p><p><p>iOS memory management and malloc source code interpretation</p></p></span>

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.