使用 gdb 調試 PHP core

1、開啓

查看是否開啓 core dump 輸出

ulimit -aphp

打開 core dump 文件記錄

ulimit -c unlimitedhtml

yum install gdb php-dbgnginx

關閉 core dump 文件記錄

ulimit -c 0git

設置內核core dump出來的存放路徑(注意目錄要有權限給php寫):
echo "/tmp/core.%e.%p.%t" > /proc/sys/kernel/core_patterngithub

2、調試

一、準備 .gdbinit 文件

獲取地址:https://github.com/php/php-src/blob/master/.gdbinit
保存在服務器上,例如 /root/.gdbinit 備用。服務器

二、用 gdb 打開 core 文件

gdb php-fpm -c core-php-fpm.920php7

能夠看到相似下邊的字樣:app

Core was generated by `php-fpm: pool www            '.
Program terminated with signal 11, Segmentation fault.

三、查看 core 發生時刻的堆棧

(gdb) bt
#0  zend_mm_alloc_small (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:1295
#1  zend_mm_alloc_heap (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:1366
#2  _emalloc (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:2450
#3  0x00007f7a6fad0511 in apm_sprintf (fmt=0x7f7a6faeff50 "\n %04d-%02d-%02d %02d:%02d:%02d Version %s\n Process %d received signal %2d: %s , bss[%p]\n")
    at /PHP/64/source/php7.0.0_nzts/ext/apm/apm_common.c:371
#4  0x00007f7a6facbefd in print_backtrace (sig=11) at /PHP/64/source/php7.0.0_nzts/ext/apm/apm.c:1937
#5  0x00007f7a6facbfd7 in agent_fatal_signal_handler (sig=11) at /PHP/64/source/php7.0.0_nzts/ext/apm/apm.c:1955
#6  <signal handler called>
#7  zend_mm_alloc_small (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:1295
#8  zend_mm_alloc_heap (size=<value optimized out>) at /usr/src/debug/php-7.0.6/Zend/zend_alloc.c:1366

四、引入 PHP 源代碼中提供的 .gdbinit (gdb 命令編寫腳本)

(gdb) source /root/.gdbinit

五、查看 backtrace 和變量值

(gdb) zbacktrace
[0x7f7a75e138c0] C("DEBUG") /usr/share/nginx/html/smartphp/common.php:28
[0x7f7a75e137d0] Model->_connectDb() /usr/share/nginx/html/smartphp/core/Model.class.php:44
[0x7f7a75e13680] Model->bindData("SELECT\40tips\40FROM\40keyword_phone\40WHERE\40word=:word", array(1)[0x7f7a75e136f0], "getdata") /usr/share/nginx/html/smartphp/core/Model.class.php:143
[0x7f7a75e13580] Model->getData("SELECT\40tips\40FROM\40keyword_phone\40WHERE\40word=:word", array(1)[0x7f7a75e135f0]) /usr/share/nginx/html/smartphp/core/Model.class.php:215
[0x7f7a75e134c0] Model->getField("SELECT\40tips\40FROM\40keyword_phone\40WHERE\40word=:word", array(1)[0x7f7a75e13530]) /usr/share/nginx/html/appdata/smartphp/core/Model.class.php:264
(gdb) print ((zval *)0x7f7a75e13530)
$1 = (zval *) 0x7f7a75e13530

(gdb) printzv $1
[0x7f7a75e13530] (refcount=3) array:     Packed(1)[0x7f7a75e94888]: {
      [0] 0 => [0x7f7a75e6ad88] (refcount=4) string: PP紅包。
}

https://bugs.php.net/bugs-generating-backtrace.php
http://www.laruence.com/2011/06/23/2057.html
https://kn007.net/topics/php-fpm-how-to-core-dump/
http://www.laruence.com/2011/12/06/2381.htmlphp-fpm

相關文章
相關標籤/搜索