search
HomeBackend DevelopmentPHP TutorialA brief discussion of PHP source code 31: Basics of the heap layer in the PHP memory pool

This article mainly introduces about PHP source code 31: The foundation of the heap layer in the PHP memory pool, which has a certain reference value. Now I share it with you. Friends in need can refer to it

A brief discussion on PHP source code 31: The basics of the heap layer in the PHP memory pool

[Overview]
PHP’s memory manager is hierarchical . This manager has three layers: storage layer, heap layer and emalloc/efree layer. The storage layer is introduced in PHP source code reading notes 30: Storage layer in PHP memory pool. The storage layer actually applies for memory to the system through functions such as malloc() and mmap(), and releases the requested memory through the free() function. Memory. The storage layer usually applies for relatively large memory blocks. The large memory applied here does not mean the memory required by the storage layer structure. It is just that when the heap layer calls the allocation method of the storage layer, the memory it applies for in the segment format is relatively large. , the role of the storage layer is to make the memory allocation method transparent to the heap layer.
Above the storage layer is the heap layer we want to learn about today. The heap layer is a scheduling layer that interacts with the emalloc/efree layer above to split the large blocks of memory applied for through the storage layer and provide them on demand. There is a set of memory scheduling strategies in the heap layer, which is the core area of ​​the entire PHP memory allocation management.

All the following sharing is based on the situation that ZEND_DEBUG has not been opened.
First look at the structures involved in the heap layer:
[Structure]

 /* mm block type */typedef struct _zend_mm_block_info {
size_t _size;/* block的大小*/
size_t _prev;/* 计算前一个块有用到*/} zend_mm_block_info; 
 typedef struct _zend_mm_block {
zend_mm_block_info info;} zend_mm_block; typedef struct _zend_mm_small_free_block {/* 双向链表 */
zend_mm_block_info info;
struct _zend_mm_free_block *prev_free_block;/* 前一个块 */
struct _zend_mm_free_block *next_free_block;/* 后一个块 */} zend_mm_small_free_block;/* 小的空闲块*/ typedef struct _zend_mm_free_block {/* 双向链表 + 树结构 */
zend_mm_block_info info;
struct _zend_mm_free_block *prev_free_block;/* 前一个块 */
struct _zend_mm_free_block *next_free_block;/* 后一个块 */ struct _zend_mm_free_block **parent;/* 父结点 */
struct _zend_mm_free_block *child[2];/* 两个子结点*/} zend_mm_free_block; 
 
 struct _zend_mm_heap {
int                 use_zend_alloc;/* 是否使用zend内存管理器 */
void               *(*_malloc)(size_t);/* 内存分配函数*/
void                (*_free)(void*);/* 内存释放函数*/
void               *(*_realloc)(void*, size_t);
size_t              free_bitmap;/* 小块空闲内存标识 */
size_t              large_free_bitmap;  /* 大块空闲内存标识*/
size_t              block_size;/* 一次内存分配的段大小,即ZEND_MM_SEG_SIZE指定的大小,默认为ZEND_MM_SEG_SIZE   (256 * 1024)*/
size_t              compact_size;/* 压缩操作边界值,为ZEND_MM_COMPACT指定大小,默认为 2 * 1024 * 1024*/
zend_mm_segment    *segments_list;/* 段指针列表 */
zend_mm_storage    *storage;/* 所调用的存储层 */
size_t              real_size;/* 堆的真实大小 */
size_t              real_peak;/* 堆真实大小的峰值 */
size_t              limit;/* 堆的内存边界 */
size_t              size;/* 堆大小 */
size_t              peak;/* 堆大小的峰值*/
size_t              reserve_size;/* 备用堆大小*/
void               *reserve;/* 备用堆 */
int                 overflow;/* 内存溢出数*/
int                 internal;#if ZEND_MM_CACHE
unsigned int        cached;/* 已缓存大小 */
zend_mm_free_block *cache[ZEND_MM_NUM_BUCKETS];/* 缓存数组/
#endif
zend_mm_free_block *free_buckets[ZEND_MM_NUM_BUCKETS*2];/* 小块空闲内存数组 */
zend_mm_free_block *large_free_buckets[ZEND_MM_NUM_BUCKETS];/* 大块空闲内存数组*/
zend_mm_free_block *rest_buckets[2];/* 剩余内存数组 */ };

For the memory operation function in the heap structure, if use_zend_alloc is no, malloc-type memory allocation is used, this At this time, all operations do not go through the memory management in the heap layer, and directly use functions such as malloc.

The default size of compact_size is 2 * 1024 * 1024 (2M). If the variable ZEND_MM_COMPACT is set, the size is specified. If the peak memory exceeds this value, the compact function of storage will be called, just this function The current implementation is empty and may be added in subsequent versions.

reserve_size is the size of the reserve heap, by default it is ZEND_MM_RESERVE_SIZE, its size is (8*1024)
*reserve is the reserve heap, its size is reserve_size, it is used to report errors when memory overflows .

[About USE_ZEND_ALLOC]
The environment variable USE_ZEND_ALLOC can be used to allow selection of malloc or emalloc memory allocation at runtime. Using malloc-type memory allocation will allow external debuggers to observe memory usage, while emalloc allocation will use the Zend memory manager abstraction, requiring internal debugging.
[zend_startup() -> start_memory_manager() -> alloc_globals_ctor()]

static void alloc_globals_ctor(zend_alloc_globals *alloc_globals TSRMLS_DC){
char *tmp;
alloc_globals->mm_heap = zend_mm_startup(); 
tmp = getenv("USE_ZEND_ALLOC");
if (tmp) {
alloc_globals->mm_heap->use_zend_alloc = zend_atoi(tmp, 0);
if (!alloc_globals->mm_heap->use_zend_alloc) {/* 如果不使用zend的内存管理器,同直接使用malloc函数*/
alloc_globals->mm_heap->_malloc = malloc;
alloc_globals->mm_heap->_free = free;
alloc_globals->mm_heap->_realloc = realloc;
}
}}

[Initialization]

[zend_mm_startup()]
Initialize the allocation plan of the storage layer , initialize the segment size, compression boundary value, and call zend_mm_startup_ex() to initialize the heap layer.

[zend_mm_startup() -> zend_mm_startup_ex()]
[Memory Alignment]
Memory alignment is used in PHP’s memory allocation. The memory alignment calculation obviously has two goals: one is to reduce The number of CPU memory accesses; the second is to keep the storage space efficient enough.

 # define ZEND_MM_ALIGNMENT 8 #define ZEND_MM_ALIGNMENT_MASK ~(ZEND_MM_ALIGNMENT-1) 
 #define ZEND_MM_ALIGNED_SIZE(size)(((size) + ZEND_MM_ALIGNMENT - 1) & ZEND_MM_ALIGNMENT_MASK) 
 #define ZEND_MM_ALIGNED_HEADER_SIZEZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_block))
 #define ZEND_MM_ALIGNED_FREE_HEADER_SIZEZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_small_free_block))

PHP uses memory alignment in the memory of allocated blocks. If the lower three digits of the required memory size are not 0 (not divisible by 8), add 7 to the lower digits. And ~7 performs an AND operation, that is, for memory sizes that are not an integer multiple of 8, the memory size is completed to be divisible by 8.
On win32 machines, the numerical sizes corresponding to some macros are:
ZEND_MM_MIN_SIZE=8
ZEND_MM_MAX_SMALL_SIZE=272
ZEND_MM_ALIGNED_HEADER_SIZE=8
ZEND_MM_ALIGNED_FREE_HEADER_SIZE=16
ZEND_MM_MIN_ALLOC_BLOCK_SIZE=8
ZEND_MM_ALIGNED_MIN_HEADER_SIZE =16
ZEND_MM_ALIGNED_SEGMENT_SIZE=8

If you want to allocate a block with a size of 9 bytes, the actual allocated size is ZEND_MM_ALIGNED_SIZE(9 8)=24

[of the block Positioning】
The two right digits of the allocated memory are used to mark the type of memory.
The definition of its size is #define ZEND_MM_TYPE_MASK ZEND_MM_LONG_CONST(0×3)

The code shown below is the positioning of the block

 #define ZEND_MM_NEXT_BLOCK(b)ZEND_MM_BLOCK_AT(b, ZEND_MM_BLOCK_SIZE(b))
 #define ZEND_MM_PREV_BLOCK(b)ZEND_MM_BLOCK_AT(b, -(int)((b)->info._prev & ~ZEND_MM_TYPE_MASK)) 
 #define ZEND_MM_BLOCK_AT(blk, offset)((zend_mm_block *) (((char *) (blk))+(offset)))
 #define ZEND_MM_BLOCK_SIZE(b)((b)->info._size & ~ZEND_MM_TYPE_MASK)#define ZEND_MM_TYPE_MASKZEND_MM_LONG_CONST(0x3)

The next element of the current block is the current block The head position plus the length of the entire block (minus the length of the type).
The previous element of the current block is the head position of the current block minus the length of the previous block (removing the length of the type).
Regarding the length of the previous block, it is set to the result of the OR operation of the size of the current block and the block type during the initialization of the block.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

A brief discussion of PHP source code 30: The storage layer in the PHP memory pool

A brief discussion of PHP Source code twenty-nine: About the inheritance of interfaces

## A brief discussion of PHP source code twenty-eight: About the class structure and inheritance

The above is the detailed content of A brief discussion of PHP source code 31: Basics of the heap layer in the PHP memory pool. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.