同事發現一個在使用set_error_handler的時候, 能100%重現的core, 提煉後的重現代碼如下(環境必須不能訪問internet):
<?php
function err_handler(){
exit;
return true;
}
set_error_handler('err_handler');
$client = file_get_contents("http://www.laruence.com/ServiceNoWse.asmx?WSDL");
這段代碼, 放在webServer中, 第一次訪問不會有事, 第二第三次的時候就會出core.
gdb跟蹤以後發現, core出在php_stream_display_wrapper_errors函數中, 對err_stack中的錯誤資訊字串做處理的時刻, core的堆棧如下:
#0 0x000000302af6ff20 in strlen () from /lib64/tls/libc.so.6
#1 0x0000002a989d97c1 in php_stream_display_wrapper_errors (wrapper=0x2a98e884a0, path=Variable "path" is not available.
) at /home/huixc/package/php-5.2.14/main/streams/streams.c:151
#2 0x0000002a989dca22 in _php_stream_open_wrapper_ex (path=0x76e7c8 "http://www.laruence.com/ServiceNoWse.asmx?WSDL", mode=0x2a98ae3087 "rb", options=8, opened_path=0x0,
context=0x76e808) at /home/huixc/package/php-5.2.14/main/streams/streams.c:1893
#3 0x0000002a98966541 in zif_file_get_contents (ht=-1729541984, return_value=0x76e738, return_value_ptr=Variable "return_value_ptr" is not available.
) at /home/huixc/package/php-5.2.14/ext/standard/file.c:541
#4 0x0000002a98a2c05e in zend_do_fcall_common_helper_SPEC (execute_data=0x7fbfffca30) at /home/huixc/package/php-5.2.14/Zend/zend_vm_execute.h:200
#5 0x0000002a98a2b671 in execute (op_array=0x769890) at /home/huixc/package/php-5.2.14/Zend/zend_vm_execute.h:92
#6 0x0000002a98a0c734 in zend_execute_scripts (type=8, retval=0x0, file_count=3) at /home/huixc/package/php-5.2.14/Zend/zend.c:1134
#7 0x0000002a989c965d in php_execute_script (primary_file=0x7fbfffef00) at /home/huixc/package/php-5.2.14/main/main.c:2036
#8 0x0000002a98a9bd36 in php_handler (r=0x8f1ba8) at /home/huixc/package/php-5.2.14/sapi/apache2handler/sapi_apache2.c:639
經過半個多小時的跟蹤, 終於找到原因
是因為, 在PHP中, 對於exit, 其實是藉助了set/longjmp來實現使用者指令碼退出以後, 到達收尾工作, 而對於出錯代碼出是根據wrapper的err_count計數來確定有多少錯誤資訊要輸出.
並且, 在輸出完錯誤資訊以後, 清空wrap的錯誤資訊, 置零錯誤計數.
void php_stream_tidy_wrapper_error_log(php_stream_wrapper *wrapper TSRMLS_DC)
{
if (wrapper) {
/* tidy up the error stack */
int i;
for (i = 0; i < wrapper->err_count; i++) {
efree(wrapper->err_stack[i]);
}
if (wrapper->err_stack) {
efree(wrapper->err_stack);
}
wrapper->err_stack = NULL;
wrapper->err_count = 0;
}
}
而, 因為在現實錯誤資訊之後, 會緊接著觸發php_error_docref1, 繼而觸發代碼中設定的error_handler, 而在handler中, 卻調用了exit, 最終longjmp到了soap處理時刻設定的跳轉點, 造成跳過了對 php_stream_tidy_wrapper_error_log 的調用, 所以導致第二次再來請求的時候, err_count並沒有正確的被初始化為零, 還是保持著上次請求的錯誤數.
於是, 在輸出錯誤資訊的時候,
......
for (i = 0, l = 0; i < wrapper->err_count; i++) {
l += strlen(wrapper->err_stack[i]); //出core了
if (i < wrapper->err_count - 1) {
l += brlen;
}
}
暫時來說, 解決這個辦法, 可以在streams的php_stream_display_wrapper_errors函數調用php_error_docref1之前掉後用php_stream_tidy_wrapper_error_log;