Home php教程 PHP开发 PHP kernel analysis (1)

PHP kernel analysis (1)

Dec 19, 2016 am 11:01 AM

The PHP version read here is PHP-7.1.0 RC3, and the platform for reading the code is Linux

The first thing is to find the entrance to PHP. PHP has many modes, apache, php-fpm, cli mode. If I want to start, just You can start with the simplest cli model.

So, I need to find

php -r 'echo 12;'
Copy after login

how this command is executed first.

First we need to look for the main entrance, because we are looking at the command line php program. Therefore, this entry is in sapi/cli/php_cli.c.


First define a series of variables

01      int c;    
02    zend_file_handle file_handle;    
03    int behavior = PHP_MODE_STANDARD;    
04    char *reflection_what = NULL;    
05    volatile int request_started = 0;    
06    volatile int exit_status = 0;    
07    char *php_optarg = NULL, *orig_optarg = NULL;    
08    int php_optind = 1, orig_optind = 1;    
09    char *exec_direct=NULL, *exec_run=NULL, *exec_begin=NULL, *exec_end=NULL;    
10    char *arg_free=NULL, **arg_excp=&arg_free;    
11    char *script_file=NULL, *translated_path = NULL;    
12    int interactive=0;    
13    int lineno = 0;    
14    const char *param_error=NULL;    
15    int hide_argv = 0;
Copy after login

Then this

sapi_module_struct *sapi_module = &cli_sapi_module;

This is a sapi_module_struct structure, which is the most important data structure in sapi. Its definition is in main/SAPI.h.


The following is the code with added comments:

01    struct _sapi_module_struct {  // SAPI模块结构    
02        char *name; // 应用层名称,比如cli,cgi等    
03        char *pretty_name; // 应用层更易读的名字,比如cli对应的就是Command Line Interface    
04    
05        int (*startup)(struct _sapi_module_struct *sapi_module); // 当一个应用要调用php的时候,这个模块启动的时候会调用的函数    
06        int (*shutdown)(struct _sapi_module_struct *sapi_module); // 当一个应用要调用php的时候,这个模块结束的时候会调用的函数    
07    
08        int (*activate)(void); // 在处理每个request的时候,激活需要调用的函数    
09        int (*deactivate)(void); // 在处理完每个request的时候,收尾时候要调用的函数    
10    
11        size_t (*ub_write)(const char *str, size_t str_length); // 这个函数告诉php如何输出数据    
12        void (*flush)(void *server_context); // 提供给php的刷新缓存的函数指针    
13        zend_stat_t *(*get_stat)(void); // 用来判断要执行文件的权限,来判断是否有执行权限    
14        char *(*getenv)(char *name, size_t name_len); // 获取环境变量的方法    
15    
16        void (*sapi_error)(int type, const char *error_msg, ...) ZEND_ATTRIBUTE_FORMAT(printf, 2, 3); // 错误处理方法    
17    
18        int (*header_handler)(sapi_header_struct *sapi_header, sapi_header_op_enum op, sapi_headers_struct *sapi_headers); // 这个函数会在我们调用header()的时候被调用    
19        int (*send_headers)(sapi_headers_struct *sapi_headers); // 发送所有的header    
20        void (*send_header)(sapi_header_struct *sapi_header, void *server_context); // 单独发送某一个header    
21    
22        size_t (*read_post)(char *buffer, size_t count_bytes); // 如何获取HTTP POST中的数据    
23        char *(*read_cookies)(void);  // 如何获取cookie中的数据    
24    
25        void (*register_server_variables)(zval *track_vars_array); // 这个函数可以给$_SERVER中获取变量    
26        void (*log_message)(char *message, int syslog_type_int); // 输出错误信息函数    
27        double (*get_request_time)(void); // 获取请求时间的函数    
28        void (*terminate_process)(void);  // TODO: 调用exit的时候调用的方法    
29    
30        char *php_ini_path_override;  // PHP的ini文件被复写了所复写的地址    
31    
32        void (*default_post_reader)(void); // 这里和前面的read_post有个差别,read_post负责如何获取POST数据,而这里的函数负责如何解析POST数据    
33        void (*treat_data)(int arg, char *str, zval *destArray); // 对数据进行处理,比如进行安全过滤等。 default_post_reader/tread_data/input_filter是三个能对输入进行过滤和处理的函数    
34        char *executable_location; // 执行的地理位置    
35    
36        int php_ini_ignore; // 是否不使用任何ini配置文件,比如php -n 就将这个位置设置为1    
37        int php_ini_ignore_cwd; // 不在当前路径寻找php.ini    
38    
39        int (*get_fd)(int *fd); // 获取执行文件的fd    
40    
41        int (*force_http_10)(void); // 强制使用http1.0    
42    
43        int (*get_target_uid)(uid_t *); // 获取执行程序的uid    
44        int (*get_target_gid)(gid_t *); // 获取执行程序的gid    
45    
46        unsigned int (*input_filter)(int arg, char *var, char **val, size_t val_len, size_t *new_val_len); // 对输入进行过滤。比如将输入参数填充到自动全局变量$_GET, $_POST, $_COOKIE中    
47    
48        void (*ini_defaults)(HashTable *configuration_hash); // 默认的ini配置    
49        int phpinfo_as_text; // 是否打印phpinfo信息    
50    
51        char *ini_entries; // 有没有附带的ini配置,比如使用php -d date.timezone=America/Adak,可以在命令行中设置时区    
52        const zend_function_entry *additional_functions; // 每个SAPI模块特有的一些函数注册,比如cli的cli_get_process_title    
53        unsigned int (*input_filter_init)(void); // TODO:    
54    };
Copy after login

There are a few points to summarize:


cli mode does not need to send headers, so there are three functions corresponding to header processing

1    sapi_cli_header_handler    
2    sapi_cli_send_headers    
3    sapi_cli_send_header
Copy after login

In fact They are all empty implementations.


The same is true for cookies

sapi_cli_read_cookies
Copy after login

We will analyze some other defined functions when we encounter them.

main

Go back to the main function. Based on the above structure, we understand

1    argv = save_ps_args(argc, argv); //这里获取一次当前执行进程的参数,环境变量等。为的是对特定平台,修正下argv变量以供后续使用。    
2    
3    cli_sapi_module.additional_functions = additional_functions; // cli模式特有的函数
Copy after login

signal

1    #ifdef HAVE_SIGNAL_H    
2    #if defined(SIGPIPE) && defined(SIG_IGN)    
3         // 忽略SIGPIPE是为了如果php是socket的客户端,那么当服务端关闭的话,会返回一个PIPE的信号,为的是当前的程序不会因为这个而结束    
4        signal(SIGPIPE, SIG_IGN);    
5    #endif    
6    #endif
Copy after login

The above is the content of PHP kernel analysis (1). For more related content, please pay attention to the PHP Chinese website (www. php.cn)!


Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 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.

See all articles