PHP Interpreter Engine Execution flow

Source: Internet
Author: User
Tags php language php cli sapi

Catalogue

1. SAPI Interface 2. PHP CLI mode explains the execution of the script process 3. PHP Zend Complile/execute Function Interface (Hook Call architecture Basics)

1. SAPI interface

PHP's SAPI layer implements the encapsulation of the upper interface, allowing PHP to be used in a variety of mode scenarios (such as Apache, NINGX, CGI, fastcgi, CLI) to CLI SAPI as an example of how the PHP interpreter engine handles PHP's user-state source code file CLI (command line Interface), which is now the default installation of PHP, and this SAPI is installed on the server, An executable file is typically generated

The start of the script execution begins with the SAPI interface implementation. Just different SAPI interface implementations will complete their specific work, such as Apache's mod_php SAPI implementations need to initialize some information obtained from Apache, the output content is to return the content to Apache, other SAPI implementations are similar

0x1:sapi_module_struct

To define a SAPI, first define a SAPI_MODULE_STRUCTPHP-SRC/SAPI/CLI/PHP_CLI.C

/* {{{sapi_module_struct cli_sapi_module */static sapi_module_struct cli_sapi_module = {"CLI",                /* Name Php_info () is used */"Command line Interface",/* Pretty name */Php_cli_startup, /* Startup */Php_module_shutdown_wrapper,/* shutdown */NULL,/* Activate */SAPI _cli_deactivate,/* Deactivate */sapi_cli_ub_write,/* unbuffered write */Sapi_cli_flush ,/* flush */NULL,/* GET UID */NULL,/*     getenv */php_error,/* ERROR handler */Sapi_cli_header_handler,/* Header handler */ Sapi_cli_send_headers,/* Send headers Handler */Sapi_cli_send_header,/* Send header handle R */NULL,/* Read POST Data */sapi_cli_read_cookies,/* Read cookies */SAP I_cli_register_variables,/* Register Server Variables */sapi_cli_log_message,/* Log message */NULL, /* Get Request time */NULL,/* Child terminate */Standard_sapi_module_properti es};/*}}} */

This structure contains constants, such as name, which will be used when we call Php_info (). Some initialization, closing function, and some function pointers to tell Zend, how to get, and output data, we will refer to the fields in the following process introduction

Relevant Link:

http://www.nowamagic.net/librarys/veda/detail/1285

2. PHP CLI Mode explanation execution script process

0x1:process Startup

Master process main after doing some necessary initialization work, it enters the SAPI logic flow, initializes some environment variables, which will take effect throughout the SAPI life cycle.

0x2:minit

After entering a specific SAPI mode, PHP invokes the Minit method of each extension \php-5.6.17\sapi\cli\php_cli.c

int main (int argc, char *argv[]) {    ..    Sapi_module_struct *sapi_module = &cli_sapi_module;:    Sapi_module->ini_defaults = Sapi_cli_ini_defaults;    Sapi_module->php_ini_path_override = ini_path_override;    Sapi_module->phpinfo_as_text = 1;    SAPI_MODULE->PHP_INI_IGNORE_CWD = 1;    Sapi_startup (sapi_module);    sapi_started = 1;    ..

Php_cli_startup

static int Php_cli_startup (sapi_module_struct *sapi_module)/* {{*/{    if (Php_module_startup (sapi_module, NULL, 0) ==failure) {        return FAILURE;    }    return SUCCESS;}

PHP invokes the Minit method of each extension, which allows these extensions to switch to the available state

/* {{{php_module_startup */int php_module_startup (sapi_module_struct *sf, Zend_    Module_entry *additional_modules, uint num_additional_modules) {..    Zend_module_entry *module;    ..    Module_shutdown = 0;    Module_startup = 1;    Sapi_initialize_empty_request (Tsrmls_c);    Sapi_activate (Tsrmls_c);    .. /* Start additional PHP extensions */PHP_REGISTER_EXTENSIONS_BC (additional_modules, Num_additional_modules tsrmls_cc)    ; /* Load and startup extensions compiled as shared objects (aka DLLs) as requested by php.ini entries Theese ar e loaded after initialization of internal extensions as extensions *might* rely on things from ext/standard wh Ich is always a internal extension and to being initialized ahead of all other internals */PHP_INI_REGISTER_EX    Tensions (Tsrmls_c);    Zend_startup_modules (Tsrmls_c);    /* Start Zend Extensions */zend_startup_extensions (); ..

Minit means "module initialization". Each module defines a set of functions, class libraries, etc. to handle other requests a typical Minit method is as follows

Php_minit_function (extension_name) {/* Initialize functions, classes etc *}

0x3:rinit

When a page request occurs, the SAPI layer takes control over to the PHP layer. PHP then sets the environment variables that are required to respond to this request. It also creates a variable table that holds the variable names and values that are generated during execution. PHP calls the Rinit method of each module, which is "request initialization"

A classic example is the Rinit of the session module, if the session module is enabled in PHP.ini, the $_session variable is initialized when the module is called Rinit, and the relevant content is read into

The Rinit method can be thought of as a preparation process that starts automatically before the program executes. A typical Rinit method is as follows

Php_rinit_function (extension_name) {/* Initialize session Variables,pre-populate variables, redefine global variables ETC */}

PHP handles some initialization, resource-allocation transactions at each request. This part is the Activate field to be defined, from the above structure we can see, from the above CLI corresponding to the cli_sapi_module struct, for CGI, it does not provide an initialization handle handle. For mod_php, that's different, he's going to register the resource destructor in the Apache pool, request space, initialize environment variables, and so on.

0x4:script

PHP executes the php script via Php_execute_script (&file_handle tsrmls_cc) \php-5.6.17\main\main.c

/* {{{php_execute_script */phpapi int php_execute_script (zend_file_handle *primary_file tsrmls_dc) {    //file_ The type of handle is Zend_file_handle, this is a zend to the file handle of a package, the contents and the script to be executed related    zend_file_handle *prepend_file_p, *append_file_p;    Zend_file_handle Prepend_file = {0}, Append_file = {0};.    .    Php_execute_script is ultimately called zend_execute_scripts    retval = (zend_execute_scripts (Zend_require tsrmls_cc, NULL, 3, Prepend_file_p, Primary_file, append_file_p) = = SUCCESS);.    

Php_execute_script is ultimately called the ZEND_EXECUTE_SCRIPTS{PHPSRC}/ZEND/ZEND.C

This function has variable parameters that can execute multiple PHP files at once zend_api int zend_execute_scripts (int type tsrmls_dc, zval **retval, int file_count, ...)/* {{{ */{    ..    EG (Active_op_array) = Zend_compile_file (File_handle, type TSRMLS_CC);.    if (eg (active_op_array))     {        eg (return_value_ptr_ptr) = retval? retval:null;        Zend_execute (EG (Active_op_array) tsrmls_cc);        

1. Compile compilation process

Zend_compile_file is a function pointer declared in {PHPSRC}/ZEND/ZEND_COMPILE.C

Zend_api Zend_op_array * (*zend_compile_file) (zend_file_handle *file_handle, int type TSRMLS_DC);  

When the engine is initialized, the address of the Compile_file function is assigned to the Zend_compile_file,compile_file function defined in {PHPSRC}/ZEND/ZEND_LANGUAGE_SCANNER.L

The function returns a pointer to Zend_op_array with the Zend_file_handle pointer as a parameter ZEND_API zend_op_array *compile_file (Zend_file_handle *file_ handle, int type TSRMLS_DC) {    ..    Lex lexical parsing process:    

2. Execute execution process (opcode)

Zend_execute is also a function pointer (opcode array obtained using the compile process), which is declared in {phpsrc}/zend/zend_execute.c

zend_api extern void (*zend_execute) (Zend_op_array *op_array tsrmls_dc);  

At the time of engine initialization, the address of the Execute function is assigned to the definition of Zend_execute,execute in {phpsrc}/zend/zend_vm_execute.h

Zend_execute takes a pointer to the ZEND_OP_ARRAY structure as a parameter, which is the return value of the previous zend_compile_file, Zend_execute starts executing op code in Op_array, executing the OP Code in the process, implemented the various functions of the PHP language Zend_api void Zend_execute (Zend_op_array *op_array tsrmls_dc) {    if (EG (Exception)) {        return;    }     ZEND_EXECUTE_EX (I_create_execute_data_from_op_array (op_array, 0 tsrmls_cc) tsrmls_cc);}

0x5:rshutdown

Once the page has been executed (either at the end of the file or with the exit or Die function aborted), PHP starts the cleanup program. It invokes the Rshutdown method of each module sequentially. Rshutdown is used to clear the symbol table generated when the program runs, that is, to call the unset function on each variable

Php_rshutdown_function (extension_name) {/* do memory management, unset all variables used in the last PHP call etc */}

0x6:mshutdown

Finally, all the requests have been processed and SAPI is ready to shut down, and PHP begins the second step: PHP calls each extended Mshutdown method, which is the last chance for each module to release memory

Php_mshutdown_function (extension_name) {/* Free handlers and persistent memory etc *}

/main/main.c

/* {{{php_module_shutdown_wrapper */int php_module_shutdown_wrapper (sapi_module_struct *sapi_globals) {    TSRMLS_ FETCH ();    Php_module_shutdown (Tsrmls_c);    return SUCCESS;}

Relevant Link:

http://www.nowamagic.net/librarys/veda/detail/1286http://www.nowamagic.net/librarys/veda/detail/1322http:// www.nowamagic.net/librarys/veda/detail/1323http://www.nowamagic.net/librarys/veda/detail/1332http:// blog.csdn.net/phpkernel/article/details/5716342http://www.nowamagic.net/librarys/veda/detail/1287http:// www.nowamagic.net/librarys/veda/detail/1289

3. PHP Zend Complile/execute Function Interface (Hook Call architecture Basics)

PHP kernel in the design of the implementation of the architecture, in addition to provide an extension mechanism, but also in the Zend of the two key processes (compile, execute) to provide a hook mechanism, PHP extension developers can hook hijack Zend compilation/interpretation execution process, Execute the custom code logic before Zend compiles, and then return control to Zend. At the time of Engine initialization (ZEND_STARTUP)

1. End_execute points to the default execute2. Zend_compile_file points to the default Compile_file

We can rewrite the Zend_execute and Zend_compile_file as other compile and execute functions before actually compiling and executing (in the rinit phase), leaving hooks for our extension engine, such as a more famous op that looks at PHP Code extension VLD, this extension is in each request initialization of the hook function (php_rinit_function), the Zend_execute and Zend_compile_file replaced with their own vld_execute and vld_ Compile_file, these two functions are actually encapsulated in the original function, adding the additional function of the output opcode information, because the engine initialization occurs before the module request initialization, and the module request initialization is also before compiling and executing, so such coverage can achieve the purpose

Relevant Link:

Copyright (c) Littlehann All rights reserved

  • Related Article

    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.