Press "Enter" to skip to content


why xdebug extension must be loaded as a zend extension?
what is zend extension and what are the differents between regular php extension and zend extension?
let's start from that the extension loading process.

PHP是可以被扩展的, PHP的核心引擎Zend Engine也是可以被扩展的, 如果你也对Apache Module的编写也有所了解的话, 那么, 你就会对如下的结构很熟悉了:

struct _zend_extension {
        char *name;
        char *version;
        char *author;
        char *URL;
        char *copyright;
        startup_func_t startup;
        shutdown_func_t shutdown;
        activate_func_t activate;
        deactivate_func_t deactivate;
        message_handler_func_t message_handler;
        op_array_handler_func_t op_array_handler;
        statement_handler_func_t statement_handler;
        fcall_begin_handler_func_t fcall_begin_handler;
        fcall_end_handler_func_t fcall_end_handler;
        op_array_ctor_func_t op_array_ctor;
        op_array_dtor_func_t op_array_dtor;
        int (*api_no_check)(int api_no);
        void *reserved2;
        void *reserved3;
        void *reserved4;
        void *reserved5;
        void *reserved6;
        void *reserved7;
        void *reserved8;
        DL_HANDLE handle;
        int resource_number;

然后, 让我们对比下PHP extension的module entry:

	struct _zend_module_entry {
		unsigned short size;
		unsigned int zend_api;
		unsigned char zend_debug;
		unsigned char zts;
		struct _zend_ini_entry *ini_entry;
		struct _zend_module_dep *deps;
		char *name;
		struct _zend_function_entry *functions;
		int (*module_startup_func)(INIT_FUNC_ARGS);
		int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
		int (*request_startup_func)(INIT_FUNC_ARGS);
		int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
		void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
		char *version;
		size_t globals_size;
	#ifdef ZTS
		ts_rsrc_id* globals_id_ptr;
		void* globals_ptr;
		void (*globals_ctor)(void *global TSRMLS_DC);
		void (*globals_dtor)(void *global TSRMLS_DC);
		int (*post_deactivate_func)(void);
		int module_started;
		unsigned char type;
		void *handle;
		int module_number;

上面的结构, 可以结合我之前的文章用C/C++扩展你的PHP来帮助理解.
恩,回到主题:既然Xdebug要以Zend Extension方式加载, 那么它必然有基于Zend Extension的需求, 会是什么呢?
恩, 我们知道Xdebug有profile PHP的功能, 对, 就是statement_handler:
the statement handler callback inserts an additional opcode at the end of every statement in a script in which the callback is called. One of the primary uses for this sort of callback is to implement per-line profiling, stepping debuggers, or code-coverage utilities.
并且,因为Xdebug也提供了给用户脚本使用的函数, 所以, 它也会有部分PHP extension的实现, 并且由于它要以ZendExt方式载入的原因,所以它必须自己实现本身PHPExt部分的载入过程.

最后, 将PHP Extension的载入过程罗列如下(我会慢慢加上注释), 当然, 如果你等不及想知道, 也欢迎你直接在我的博客风雪之隅留言探讨.
1. 在mod_php5.c中,定义了Apache模块结构:

	module MODULE_VAR_EXPORT php5_module =
		php_init_handler,           /* initializer */
		php_create_dir,             /* per-directory config creator */
		php_merge_dir,              /* dir merger */
		NULL,                       /* per-server config creator */
		NULL,                       /* merge server config */
		php_commands,               /* command table */
		php_handlers,               /* handlers */
		NULL,                       /* filename translation */
		NULL,                       /* check_user_id */
		NULL,                       /* check auth */
		NULL,                       /* check access */
		NULL,                       /* type_checker */
		NULL,                       /* fixups */
		NULL                        /* logger */
	#if MODULE_MAGIC_NUMBER >= 19970103
		, NULL                      /* header parser */
	#if MODULE_MAGIC_NUMBER >= 19970719
		, NULL                      /* child_init */
	#if MODULE_MAGIC_NUMBER >= 19970728
		, php_child_exit_handler        /* child_exit */
	#if MODULE_MAGIC_NUMBER >= 19970902
		, NULL                      /* post read-request */
/* }}} */

可见, 最开始被调用的将会是php_init_handler,

static void php_init_handler(server_rec *s, pool *p)
    register_cleanup(p, NULL, (void (*)(void *))apache_php_module_shutdown_wrapper, (void (*)(void *))php_module_shutdown_for_exec);
    if (!apache_php_initialized) {
        apache_php_initialized = 1;
#ifdef ZTS
        tsrm_startup(1, 1, 0, NULL);
#if MODULE_MAGIC_NUMBER >= 19980527
        if (PG(expose_php)) {
            ap_add_version_component("PHP/" PHP_VERSION);

这里, 调用了sapi_startup, 这部分是初始化php的apache sapi,

static int php_apache_startup(sapi_module_struct *sapi_module)
    if (php_module_startup(sapi_module, &apache_module_entry, 1) == FAILURE) {
        return FAILURE;
    } else {
        return SUCCESS;

这个时候,调用了php_module_startup, 其中有:

/* this will read in php.ini, set up the configuration parameters,
       load zend extensions and register php function extensions
       to be loaded later */
    if (php_init_config(TSRMLS_C) == FAILURE) {
        return FAILURE;

调用了php_init_config, 这部分读取所有的php.ini和关联的ini文件, 然后对于每一条配置指令调用:

 if (sapi_module.ini_entries) {
        zend_parse_ini_string(sapi_module.ini_entries, 1, php_config_ini_parser_cb, &extension_lists);
               if (!strcasecmp(Z_STRVAL_P(arg1), "extension")) { /* load function module */
                    zval copy;
                    copy = *arg2;
                    copy.refcount = 0;
                    zend_llist_add_element(&extension_lists.functions, &copy);
                } else if (!strcasecmp(Z_STRVAL_P(arg1), ZEND_EXTENSION_TOKEN)) { /* load Zend extension */
                    char *extension_name = estrndup(Z_STRVAL_P(arg2), Z_STRLEN_P(arg2));
                    zend_llist_add_element(&extension_lists.engine, &extension_name);
                } else {
                    zend_hash_update(&configuration_hash, Z_STRVAL_P(arg1), Z_STRLEN_P(arg1) + 1, arg2, sizeof(zval), (void **) &entry);
                    Z_STRVAL_P(entry) = zend_strndup(Z_STRVAL_P(entry), Z_STRLEN_P(entry));

这里记录下来所有要载入的php extension和zend extension,
然后, 让我们回到php_module_startup, 后面有调用到了

void php_ini_register_extensions(TSRMLS_D)
    zend_llist_apply(&extension_lists.engine, php_load_zend_extension_cb TSRMLS_CC);
    zend_llist_apply(&extension_lists.functions, php_load_function_extension_cb TSRMLS_CC);

我们可以看到, 对于每一个扩展记录, 都调用了一个回叫函数, 我们这里只看php_load_function_extension_cb:

static void php_load_function_extension_cb(void *arg TSRMLS_DC)
    zval *extension = (zval *) arg;
    zval zval;
    php_dl(extension, MODULE_PERSISTENT, &zval, 0 TSRMLS_CC);

最后, 就是核心的载入逻辑了:

void php_dl(zval *file, int type, zval *return_value, int start_now TSRMLS_DC)
        void *handle;
        char *libpath;
        zend_module_entry *module_entry;
        zend_module_entry *(*get_module)(void);
        int error_type;
        char *extension_dir;
        if (type == MODULE_PERSISTENT) {
                extension_dir = INI_STR("extension_dir");
        } else {
                extension_dir = PG(extension_dir);
        if (type == MODULE_TEMPORARY) {
                error_type = E_WARNING;
        } else {
                error_type = E_CORE_WARNING;
        if (extension_dir && extension_dir[0]){
                int extension_dir_len = strlen(extension_dir);
                if (type == MODULE_TEMPORARY) {
                        if (strchr(Z_STRVAL_P(file), '/') != NULL || strchr(Z_STRVAL_P(file), DEFAULT_SLASH) != NULL) {
                                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Temporary module name should contain only filename");
                if (IS_SLASH(extension_dir[extension_dir_len-1])) {
                        spprintf(&libpath, 0, "%s%s", extension_dir, Z_STRVAL_P(file));
                } else {
                        spprintf(&libpath, 0, "%s%c%s", extension_dir, DEFAULT_SLASH, Z_STRVAL_P(file));
        } else {
                libpath = estrndup(Z_STRVAL_P(file), Z_STRLEN_P(file));
        /* load dynamic symbol */
        handle = DL_LOAD(libpath);
        if (!handle) {
                php_error_docref(NULL TSRMLS_CC, error_type, "Unable to load dynamic library '%s' - %s", libpath, GET_DL_ERROR());
                GET_DL_ERROR(); /* free the buffer storing the error */
        get_module = (zend_module_entry *(*)(void)) DL_FETCH_SYMBOL(handle, "get_module");
         * some OS prepend _ to symbol names while their dynamic linker
         * does not do that automatically. Thus we check manually for
         * _get_module.
        if (!get_module)
                get_module = (zend_module_entry *(*)(void)) DL_FETCH_SYMBOL(handle, "_get_module");
        if (!get_module) {
                php_error_docref(NULL TSRMLS_CC, error_type, "Invalid library (maybe not a PHP library) '%s' ", Z_STRVAL_P(file));
        module_entry = get_module();
        if ((module_entry->zend_debug != ZEND_DEBUG) || (module_entry->zts != USING_ZTS)
                || (module_entry->zend_api != ZEND_MODULE_API_NO)) {
                /* Check for pre-4.1.0 module which has a slightly different module_entry structure :( */
                        struct pre_4_1_0_module_entry {
                                  char *name;
                                  zend_function_entry *functions;
                                  int (*module_startup_func)(INIT_FUNC_ARGS);
                                  int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
                                  int (*request_startup_func)(INIT_FUNC_ARGS);
                                  int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
                                  void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
                                  int (*global_startup_func)(void);
                                  int (*global_shutdown_func)(void);
                                  int globals_id;
                                  int module_started;
                                  unsigned char type;
                                  void *handle;
                                  int module_number;
                                  unsigned char zend_debug;
                                  unsigned char zts;
                                  unsigned int zend_api;
                        char *name;
                        int zend_api;
                        unsigned char zend_debug, zts;
                        if ((((struct pre_4_1_0_module_entry *)module_entry)->zend_api > 20000000) &&
                                (((struct pre_4_1_0_module_entry *)module_entry)->zend_api < 20010901)
                        ) {
                                name       = ((struct pre_4_1_0_module_entry *)module_entry)->name;
                                zend_api   = ((struct pre_4_1_0_module_entry *)module_entry)->zend_api;
                                zend_debug = ((struct pre_4_1_0_module_entry *)module_entry)->zend_debug;
                                zts        = ((struct pre_4_1_0_module_entry *)module_entry)->zts;
                        } else {
                                name       = module_entry->name;
                                zend_api   = module_entry->zend_api;
                                zend_debug = module_entry->zend_debug;
                                zts        = module_entry->zts;
                        php_error_docref(NULL TSRMLS_CC, error_type,
                                          "%s: Unable to initialize module\n"
                                          "Module compiled with module API=%d, debug=%d, thread-safety=%d\n"
                                          "PHP    compiled with module API=%d, debug=%d, thread-safety=%d\n"
                                          "These options need to match\n",
                                          name, zend_api, zend_debug, zts,
                                          ZEND_MODULE_API_NO, ZEND_DEBUG, USING_ZTS);
        module_entry->type = type;
        module_entry->module_number = zend_next_free_module();
        module_entry->handle = handle;
        if ((module_entry = zend_register_module_ex(module_entry TSRMLS_CC)) == NULL) {
        if ((type == MODULE_TEMPORARY || start_now) && zend_startup_module_ex(module_entry TSRMLS_CC) == FAILURE) {
        if ((type == MODULE_TEMPORARY || start_now) && module_entry->request_startup_func) {
                if (module_entry->request_startup_func(type, module_entry->module_number TSRMLS_CC) == FAILURE) {
                        php_error_docref(NULL TSRMLS_CC, error_type, "Unable to initialize module '%s'", module_entry->name);


  1. Tarsus Apartman temizliği, birçok farklı işlemdir ve sürekli olarak yapılması gerekir.
    Her odanın ve ortak alanların düzenli olarak temizlenmesi, hijyenik bir ortamın oluşmasını sağlar.
    Ayrıca, apartmanın iç mekanlarının düzenli olarak boyanması ve onarılması gerekir. Tarsus Apartman Temizliği

  2. cc shop
    cc shop February 25, 2018

    Hi bros! Why you are here?

  3. Buy cc dumps
    Buy cc dumps February 6, 2018

    Hi all! How you doing? Im fine

  4. chen
    chen December 29, 2017


  5. Callie
    Callie September 7, 2017

    Hallo! Jemahd in meinem Myspace Webseite mit uns soo zu geben ihm einen Blick
    kam ich. Icch bin definitiv genießen Informationen. Ichh binn Buch-Kennzeichnung und mein Nachfolger werden twerting this!
    Ausstehrnde undd grandiksen design.

  6. Cristal
    Cristal October 22, 2016

    J’ai vu quelques-uns des plus stupides, les réponses inutiles ici. Certains sont simplement comique, mais certains pourraient vraiment être dangereux ou causer des dommages à la propriété ou la perte d’argent ou de temps tout simplement gaspillée. Le problème, bien sûr, est que les geeks de Yahoo ont ce jeu à venir en haut dans les recherches web propageant ces réponses stupides sur une zone plus large ..

  7. tony
    tony October 6, 2016


  8. Azra
    Azra July 5, 2016

    very nice web

  9. online slot malaysia
    online slot malaysia May 13, 2016

    You actually make it seem so easy with your presentation but I find this matter to be really something that I think I would never understand.
    It seems too complex and very broad for me. I’m looking forward for your next post, I will try to get the
    hang of it!

  10. Misty Lawry
    Misty Lawry May 12, 2016

    Nice blog right here! Additionally your site rather a lot up fast!
    What webb host are you the use of? Can Igget your associate link in your host?
    I wish my web site loadesd up as quickly as yours lol

  11. Chance Muramats
    Chance Muramats May 12, 2016

    Greate pieces. Keeep posting such kind of info on your page.
    Im eally impressed by it.
    Hey there, You’ve donbe a great job. I will definitely digg itt and for
    my part recommend to my friends. I’m confident they will be benefited from this

  12. StevenBema
    StevenBema April 2, 2016

    Made promise of $100 WalMart gift card that wasn’t authentic Said an e-mail will be transmitted in the next 5 minutes and I could cancel whatever it was they were attempting to get me to purchase. That e-mail never came and it has been 13 days and today they are looking to get money with no method to get in touch with an actual individual out of me

  13. Ouida
    Ouida February 25, 2016

    Furthermore, you should be aware that attacking strategies are different
    at every stage. I think Clan of the Vein is going to be their project that
    establishes Neil and Neo as Double N. Among the
    many examples of this are Tetris, Sokoban, and Solitaire.

  14. Bev
    Bev February 22, 2016

    Some gamers prefer first or third person shooting style games, others prefer sports apps.
    I think Clan of the Vein is going to be their project that establishes Neil and Neo as Double N.
    I don’t have a problem with surveys, but I understand the concerns.

  15. Ardmxurcold
    Ardmxurcold January 31, 2016

    Ozxcjkl Maefegvtjy dfdfdfdsdgd

  16. Lorenzo
    Lorenzo December 6, 2015

    Good answers in return of this query with genuine arguments and
    describing all regarding that.

  17. pussy galore band
    pussy galore band October 27, 2014

    The natural materials tend to be an ideal addition to your adult
    acne cure irrelevant to age. As your official Goddess Lifestyle Passionista and personal love cheerleader, news of a sexy new shop in New York City gives me reasons to celebrate.
    These are great sources, however, sometimes finding a local option for these is not
    the best option.

  18. I think the admin of this site is truly working
    hard in support of his web page, because here every data is quality based data.

  19. Madelaine
    Madelaine October 23, 2014

    I blog quite often and I seriously appreciate your content.
    This great article has really peaked my interest.
    I am going to book mark your site and keep checking for new details about once a week.
    I opted in for your RSS feed as well.

  20. nagelpilz behandlung
    nagelpilz behandlung October 23, 2014

    Amazing blog! Is your theme custom made or did you download it
    from somewhere? A design like yours with a few simple tweeks
    would really make my blog jump out. Please let me know where you got your theme.
    Bless you

  21. October 23, 2014

    Hi it’s me, I am also visiting this web site on a regular basis, this site is truly pleasant and the people are actually sharing pleasant thoughts.

  22. October 19, 2014

    Hello very cool site!! Man .. Excellent .. Superb ..
    I will bookmark your site and take the feeds additionally?
    I am happy to seek out so many useful info right here in the publish, we need work out more strategies on this regard, thanks for
    sharing. . . . . .

  23. servicii optimizare seo
    servicii optimizare seo October 13, 2014

    WOW just what I was searching for. Came here by searching for why
    xdebug extension must be loaded as a zend extension

  24. bed bug spray
    bed bug spray October 11, 2014

    Thank you for some other great post. Where else may just anybody get that kind of info in such an ideal method of writing?
    I’ve a presentation next week, and I am at the search for such information.

  25. Maritza
    Maritza October 10, 2014

    Definitely imagine that that you said. Your favourite justification appeared
    to be at the internet the easiest thing to consider of.
    I say to you, I certainly get irked at the same time as other
    folks think about concerns that they just don’t recognise about.
    You controlled to hit the nail upon the highest and defined
    out the entire thing without having side-effects ,
    folks could take a signal. Will likely be again to get more.

  26. Hello Dear, are you really visiting this web page regularly,
    if so afterward you will absolutely obtain nice know-how.

  27. gaming channel
    gaming channel October 6, 2014

    This is really interesting, You are a very skilled blogger.
    I’ve joined your feed and look forward to seeking more
    of your fantastic post. Also, I have shared your website
    in my social networks!

  28. montce swim discount code
    montce swim discount code October 5, 2014

    Hi there everyone, it’s my first pay a visit at this site,
    and paragraph is really fruitful designed for me, keep up posting these content.

  29. click here
    click here October 5, 2014

    Sweet blog! I found it while surfing around on Yahoo News. Do you have
    any tips on how to get listed in Yahoo News? I’ve been trying for a
    while but I never seem to get there! Thanks

  30. Maryanne
    Maryanne October 3, 2014

    Every weekend i used to go to see this web page, as i want enjoyment, since
    this this web site conations truly fastidious funny material too.

  31. plasterers st albans
    plasterers st albans September 2, 2014

    Hi there! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  32. August 30, 2014

    Hello, I think your blog might be having browser compatibility issues.
    When I look at your blog in Firefox, it looks fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to give you a quick
    heads up! Other then that, superb blog!

  33. laptop second hand ieftine
    laptop second hand ieftine August 25, 2014

    Thanks for finally writing about > 深入理解PHP原理之扩展载入过程 | 风雪之隅 < Liked it!

  34. August 25, 2014

    Superb site you have here but I was wanting to know if you knew of any message boards that cover
    the same topics discussed in this article? I’d really like to
    be a part of group where I can get feedback from other knowledgeable individuals that share the same interest.
    If you have any suggestions, please let me know. Thanks!

  35. Soila
    Soila August 19, 2014

    I know this if off topic but I’m looking into starting my own weblog and was curious what all is needed to get set up?
    I’m assuming having a blog like yours would cost a pretty
    penny? I’m not very web savvy so I’m not 100% sure.
    Any suggestions or advice would be greatly appreciated.

  36. Dennis
    Dennis August 19, 2014

    Hi Dear, are you really visiting this web page daily, if so then you will without doubt get nice

  37. Millard
    Millard August 18, 2014

    This paragraph will help the internet people for creating new website or
    even a weblog from start to end.

  38. August 15, 2014

    Also known as “the pearl of orient” is a dream destination not only for the people of the country but even people from
    across the globe. The political policy of this nation is socialist in nature, meaning the
    government provides many services to its citizens.
    Another special deal that you might want to consider is the $95 per night accommodation in the Hyatt
    Regency OHare, which is just two miles away from the Chicago OHare International Airport.

  39. August 12, 2014

    Villas in Cochin Dreamflower is a well known builder
    in Cochin, Kerala. It’s been estimated that
    the green technology sector has the greatest potential for job growth in the next 10
    years. The trusses can be installed 2 feet on center with a h clip in center span between the trusses for support.

  40. boiler spare parts
    boiler spare parts August 12, 2014

    It has developed villas, flats,apartments and homes accross Kerala.
    When choosing the best screwdriver, you have to consider some important factors.
    Fill in operates, which are projects which contractors
    do once they cannot do common scheduled work, can also be regarded.

  41. Angeline
    Angeline August 12, 2014

    Competition swimming is a different matter; many male competitors in the swimming world tend to
    wear a full skin tight bodysuit for competitions rather
    than shorts or small swimming trunks. The internet now provides you with the means
    for buying bikinis all through the year. The Hurley boardshorts were designed for the active surfer.

  42. septic tank jacksonville fl
    septic tank jacksonville fl August 11, 2014

    Despite the “correction” in home prices, demand remains weak.
    The appreciation of a excellent plumber and their solutions only gets seen when anything is improper with your plumbing these kinds of
    as leaks in faucets, toilets and showers. Knowing that you’re
    covered if a repair doesn’t last or if a mistake is made gives peace
    of mind because you know it will be taken care of either way.

  43. Veola
    Veola August 8, 2014

    Actually, for the reason that numerous companies at this moment offer you sun tanning alternatives,
    the price tag on having a imitation auburn possesses ditched due
    to only thirty five in order to 62 dollars, according to the style of application form you
    want in order to select. Use the comments section below to let us know what you liked and what just didn’t work for you.
    Also apply the tanner on the earlobes and upper ears.

  44. find homes
    find homes July 29, 2014

    One of those sellers called us and told us that their tenant moved out of a house they owned and they did
    not want to be landlords any more. Ahmedabad is the commercial capital of Gujarat and one of the rapidly growing tier II cities of the country.
    Each house gets assigned by the asset manager to a realtor who is a listing agent for the asset manager (bank).

  45. cashrape
    cashrape July 27, 2014

    Like a tradesman, Moll enjters into physical relationships with various men in order to make the transaction of
    sexual intercourse. Thhe car maker CEO went on to sayy China was the only emerging market in which it had sent
    Lamborghini managers to oversee the growth of the
    business and help deal with red tape and complex
    safety regulations. She adds, “He failed not to set forth the easy prosperous Life which I was going to live” andd that “He Reason’d me out of my Reason [.

  46. […] 我之前的文章介绍过PHP的扩展载入过程(深入理解PHP原理之扩展载入过程), 但没有涉及到模块关闭过程, 而这个问题就和模块载入顺序和模块关闭函数很有关系了. 总体来说, 就是PHP会根据模块载入的顺序的反序来在每次请求处理结束后依次调用各个扩展的请求关闭函数. […]

  47. 雪候鸟
    雪候鸟 November 27, 2009

    @偶左眼跳 请问是啥问题呢?

  48. 偶左眼跳
    偶左眼跳 November 24, 2009

    博主你好,我是PHP新手,现在在学习用xdebug调试PHP程序,我用的集成环境是WAMP,经过一天多的GOOGLE和BAIDU ,还是不能成功的在WAMP下成功的安装Xdebug。看了您的文章,了解到您应该能从原理上解决这个问题。期待您的帮助,谢谢~

Comments are closed.