search
HomeBackend DevelopmentPHP TutorialPHP Kernel Research: HASH Table and Variables_PHP Tutorial

PHP Kernel Research: HASH Table and Variables_PHP Tutorial

Jul 14, 2016 am 10:08 AM
hashphpKernelvariableandexistAttributesconstantdataResearchkindsurface

PHP HASH table

In PHP, all data, regardless of variables, constants, classes, and attributes, are implemented using Hash tables.
First let’s talk about the HASH table
typedef struct bucket {
ulong h;
uint nKeyLength; //key length
void *pData; //Pointer to the data saved by Bucke
void *pDataPtr; //Pointer data
struct bucket *pListNext; //Next element pointer
struct bucket *pListLast; //Previous element pointer
struct bucket *pNext;
struct bucket *pLast;
char arKey[1]; /* Must be last element */
} Bucket;
typedef struct _hashtable {
uint nTableSize;//Size of HashTable
uint nTableMask;//Equal to nTableSize-1
uint nNumOfElements;//Number of objects
ulong nNextFreeElement;//Points to the next empty element position nTableSize+1
Bucket *pInternalPointer; /* Used for element traversal *///Save the current traversed pointer
Bucket *pListHead;//Head element pointer
Bucket *pListTail;//Tail element pointer
Bucket **arBuckets;//Storage hash array data
dtor_func_t pDestructor;//Similar to the destructor
zend_bool persistent;//Which method to use to allocate memory space? PHP manages memory uniformly or uses ordinary malloc
unsigned char nApplyCount;//The number of times the current hash bucket has been accessed, whether the data has been traversed to prevent infinite recursive loops
zend_bool bApplyProtection;
#if ZEND_DEBUG
int inconsistent;
#endif
} HashTable;
Let’s combine it with the HASH table initialization function
ZEND_API int _zend_hash_init(HashTable *ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)
{
uint i = 3;
Bucket **tmp;
SET_INCONSISTENT(HT_OK);
if (nSize >= 0x80000000) { //If the HASH table size is greater than 0x8, it is initialized to 0x8
/* prevent overflow */
ht->nTableSize = 0x80000000;
} else {
while ((1U nTableSize = 1 }
//In order to improve calculation efficiency, the system will automatically adjust nTableSize to the smallest integer power of 2 that is not less than nTableSize. In other words, if you specify an nTableSize that is not an integer power of 2 when initializing HashTable, the system will automatically adjust the value of nTableSize
ht->nTableMask = ht->nTableSize - 1;
ht->pDestructor = pDestructor;//A function pointer, called when HashTable is added, deleted, or modified
ht->arBuckets = NULL;
ht->pListHead = NULL;
ht->pListTail = NULL;
ht->nNumOfElements = 0;
ht->nNextFreeElement = 0;
ht->pInternalPointer = NULL;
ht->persistent = persistent;//If persistent is TRUE, use the operating system's own memory allocation function to allocate memory for the Bucket, otherwise use PHP's memory allocation function
ht->nApplyCount = 0;
ht->bApplyProtection = 1;
/* Uses ecalloc() so that Bucket* == NULL */
if (persistent) { //The operating system allocates memory through its own memory allocation method. After calloc allocates memory, it is automatically initialized to 0
tmp = (Bucket **) calloc(ht->nTableSize, sizeof(Bucket *));
if (!tmp) {
return FAILURE;
}
ht->arBuckets = tmp;
} else {//Use PHP’s memory management mechanism to allocate memory
tmp = (Bucket **) ecalloc_rel(ht->nTableSize, sizeof(Bucket *));
if (tmp) {
ht->arBuckets = tmp;
}
}
//Automatically apply for a piece of memory for arBuckets, the memory size is equal to nTableSize
return SUCCESS;
}
When reading the source code, you will often see macros such as EG, PG, and CG
CG is the abbreviation of compile_global
EG is the abbreviation of excutor_global
G means global variable
Let’s take the EG macro as an example
#ifdef ZTS
# define EG(v) TSRMG(executor_globals_id, zend_executor_globals *, v)
#else
# define EG(v) (executor_globals.v)
extern ZEND_API zend_executor_globals executor_globals;
#endif
It’s very simple, just a macro to get global variables
Then let’s take a look at the zend_executor_globals structure
Defined in /Zend/zend.h
typedef struct _zend_executor_globals zend_executor_globals;
is an alias for _zend_executor_globals
Found it in the same file
All local variables, global variables, functions, and hash tables of classes in PHP are defined here
struct _zend_executor_globals {
zval **return_value_ptr_ptr;
zval uninitialized_zval;
zval *uninitialized_zval_ptr;
zval error_zval;
zval *error_zval_ptr;
zend_ptr_stack arg_types_stack;
/* symbol table cache */
HashTable *symtable_cache[SYMTABLE_CACHE_SIZE];
HashTable **symtable_cache_limit;
HashTable **symtable_cache_ptr;
zend_op **opline_ptr;
HashTable *active_symbol_table; //Local variables
HashTable symbol_table; /* main symbol table */ //Global variables
HashTable included_files; /* files already included */ //include files
JMP_BUF *bailout;
int error_reporting;
int orig_error_reporting;
int exit_status;
zend_op_array *active_op_array;
HashTable *function_table; /* function symbol table */ //Function table
HashTable *class_table; /* class table */ //Class table
HashTable *zend_constants; /* constants table */ //Constant table
zend_class_entry *scope;
zend_class_entry *called_scope; /* Scope of the calling class */
zval *This;
long precision;
int ticks_count;
zend_bool in_execution;
HashTable *in_autoload;
zend_function *autoload_func;
zend_bool full_tables_cleanup;
/* for extended information support */
zend_bool no_extensions;
#ifdef ZEND_WIN32
zend_bool timed_out;
OSVERSIONINFOEX windows_version_info;
#endif
HashTable regular_list;
HashTable persistent_list;
zend_vm_stack argument_stack;
int user_error_handler_error_reporting;
zval *user_error_handler;
zval *user_exception_handler;
zend_stack user_error_handlers_error_reporting;
zend_ptr_stack user_error_handlers;
zend_ptr_stack user_exception_handlers;
zend_error_handling_t error_handling; 
zend_class_entry *exception_class; 
  
/* timeout support */ 
int timeout_seconds; 
  
int lambda_count; 
  
HashTable *ini_directives; 
HashTable *modified_ini_directives; 
  
zend_objects_store objects_store; 
zval *exception, *prev_exception; 
zend_op *opline_before_exception; 
zend_op exception_op[3]; 
  
struct _zend_execute_data *current_execute_data; 
  
struct _zend_module_entry *current_module; 
  
zend_property_info std_property_info; 
  
zend_bool active; 
  
void *saved_fpu_cw; 
  
void *reserved[ZEND_MAX_RESERVED_RESOURCES]; 
}; 
 
 
 
这里先简单看看,以后用到的时候再细说,
 
PHP里最基本的单元 变量:
在PHP里 定义一个变量 再简单不过了
$a=1; 
?> 
 
但是在内核中 它是用一个 zval结构体实现的
如上面定义变量 在内核中则执行了下面这些代码
 
 
 
zval *val; 
MAKE_STD_ZVAL(val);  //申请一块内存 
ZVAL_STRING(val,"hello",1);//用ZVAL_STRING设置它的值为 "hello" 
ZEND_SET_SYMBOL(EG(active_symbol_table),"a",val));//将  val指针加入到符号表里面去 
宏 MAKE_STD_ZVAL 定义如下
 
 
 
#define MAKE_STD_ZVAL(zv)                                 
ALLOC_ZVAL(zv);  //它归根到底等于 (p) = (type *) emalloc(sizeof(type)) 
INIT_PZVAL(zv); 
INIT_PZVAL定义在
 
 
 
#define INIT_PZVAL(z)           看得出它是初始化参数 
(z)->refcount__gc = 1;   
(z)->is_ref__gc = 0; 
那么 zval到底是什么呢
在zend/zend.h里面
typedef struct _zval_struct zval; //原来它是 _zval_struct 的别名
_zval_struct 定义如下
 
 
 
typedef union _zvalue_value { 
        long lval;  //保存long类型的数据 
        double dval; //保存 double类型的数据 
        struct { 
                char *val; //真正的值在这里 
                int len;   //这里返回长度 
        } str; 
        HashTable *ht; 
        zend_object_value obj; //这是一个对象 
} zvalue_value; 
  
struct _zval_struct { 
zvalue_value value;             //保存的值 
zend_uint refcount__gc;//被引用的次数 如果为1 则只被自己使用如果大于1 则被其他变量以&的形式引用. 
zend_uchar type;       //数据类型 这也是 为什么 PHP是弱类型的原因 
zend_uchar is_ref__gc;  //表示是否为引用 
}; 
如果还是不够清楚..那么我们实战一下..用C来创建一个PHP变量
这里需要一个扩展,PHP如果用C扩展模块 这里就不说了
关键代码
 
 
 
PHP_FUNCTION(test_siren){ 
        zval *value; 
        char *s="create a php variable"; 
        value=(zval*)malloc(sizeof(zval)); 
        memset(value,0,sizeof(value)); 
        value->is_ref__gc=0; //非引用变量 
        value->refcount__gc=1;//引用次数 只有自己 
value->type=IS_STRING;//The type is string
value->value.str.val=s;//value
value->value.str.len=strlen(s);//length
ZEND_SET_SYMBOL(EG(active_symbol_table),"a",value);
}
The third and fourth lines have the same function as MAKE_STD_ZVAL, allocating memory space to value
The function of lines 5-9 is the same as that of ZVAL_STRING,
The last line is to create a variable called $a in PHP for value and add it to the local Hash table.
This way in PHP
test_siren(1);
echo $a;
?>
It will output “create a php variable”
OK,
Done
Note that I created variables in the form of C in order to let everyone see the process of creating variables inside PHP,
Absolutely not recommended for everyone to do this.
You must still use PHP’s internal memory management mechanism to allocate and process memory.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477783.htmlTechArticlePHP HASH table In PHP, all data regardless of variables, constants, classes, and attributes are implemented using Hash tables . Let’s first talk about the HASH table typedef struct bucket { ulong h; /* Used for numeric indexing */ ui...
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 in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment