>  기사  >  백엔드 개발  >  PHP에 대한 깊은 이해: gdb를 사용하여 소스 코드 디버깅

PHP에 대한 깊은 이해: gdb를 사용하여 소스 코드 디버깅

WBOY
WBOY앞으로
2022-12-28 18:12:254503검색

이 기사는 PHP에 대한 관련 지식을 제공하며, 주로 gdb를 사용하여 소스 코드를 디버깅하는 것과 관련된 내용을 소개합니다. 모두에게 도움이 되기를 바랍니다.

PHP에 대한 깊은 이해: gdb를 사용하여 소스 코드 디버깅

추천 연구: "PHP 비디오 튜토리얼"

PHP에는 컴파일 시 디버그 모드가 있습니다. 이 모드는 전체 PHP를 볼 수 있도록 메모리 최적화, 프롬프트 메모리 누수 및 보호 호출 스택 최적화를 끕니다. C 레벨 호출 스택.

보통 저는 서로 다른 디렉토리에 두 개의 PHP 버전(하나는 일반, 하나는 디버그 활성화)을 컴파일하고 내보내기를 통해 어떤 버전을 사용할지 결정합니다.

php-config 명령을 통해 구성 옵션을 볼 수 있으며, 접두사와 with-config-file-path를 새 디렉터리로 수정한 다음 --enable-debug 명령을 추가할 수 있습니다

yongkbmaster ➜  ~ php-config
Usage: /data/env/runtime/php-7.1.33-debug/bin/php-config [OPTION]
Options:
  --prefix            [/data/env/runtime/php-7.1.33-debug]
  --includes          [-I/data/env/runtime/php-7.1.33-debug/include/php -I/data/env/runtime/php-7.1.33-debug/include/php/main -I/data/env/runtime/php-7.1.33-debug/include/php/TSRM -I/data/env/runtime/php-7.1.33-debug/include/php/Zend -I/data/env/runtime/php-7.1.33-debug/include/php/ext -I/data/env/runtime/php-7.1.33-debug/include/php/ext/date/lib]
  --ldflags           []
  --libs              [-lcrypt   -lz -lexslt -lresolv -lcrypt -lrt -lldap -llber -lpng -lz -ljpeg -lcurl -lbz2 -lz -lrt -lm -ldl -lnsl  -lxml2 -lz -lm -ldl -lgssapi_krb5 -lkrb5 -lk5crypto -lcom_err -lssl -lcrypto -lcurl -lxml2 -lz -lm -ldl -lfreetype -lxml2 -lz -lm -ldl -lxml2 -lz -lm -ldl -lcrypt -lxml2 -lz -lm -ldl -lxml2 -lz -lm -ldl -lxml2 -lz -lm -ldl -lxml2 -lz -lm -ldl -lxslt -lxml2 -lz -ldl -lm -lssl -lcrypto -lcrypt ]
  --extension-dir     [/data/env/runtime/php-7.1.33-debug/lib/php/extensions/debug-non-zts-20160303]
  --include-dir       [/data/env/runtime/php-7.1.33-debug/include/php]
  --man-dir           [/data/env/runtime/php-7.1.33-debug/php/man]
  --php-binary        [/data/env/runtime/php-7.1.33-debug/bin/php]
  --php-sapis         [ cli fpm phpdbg cgi]
  --configure-options [--prefix=/data/env/runtime/php-7.1.33-debug --enable-debug --enable-phpdbg-debug --with-config-file-path=/data/env/runtime/php-7.1.33-debug/etc --with-curl --with-freetype-dir --with-gd --with-gettext --with-iconv-dir --with-kerberos --with-libdir=lib64 --with-libxml-dir --with-mysqli --with-openssl --with-pcre-regex --with-pdo-mysql --with-pdo-sqlite --with-pear --with-png-dir --with-jpeg-dir --with-xmlrpc --with-xsl --with-zlib --with-bz2 --with-mhash --enable-fpm --enable-bcmath --enable-libxml --enable-inline-optimization --enable-gd-native-ttf --enable-mbregex --enable-mbstring --enable-opcache --enable-pcntl --enable-shmop --enable-soap --enable-sockets --enable-sysvsem --enable-sysvshm --enable-xml --enable-zip --with-ldap]
  --version           [7.1.33]
  --vernum            [70133]

수정 후 모습 그런 다음 디버그 버전을 얻으려면 컴파일하고 설치하세요

--prefix=/data/env/runtime/php-7.1.33-debug --enable-debug --enable-phpdbg-debug --with-config-file-path=/data/env/runtime/php-7.1.33-debug/etc --with-curl --with-freetype-dir --with-gd --with-gettext --with-iconv-dir --with-kerberos --with-libdir=lib64 --with-libxml-dir --with-mysqli --with-openssl --with-pcre-regex --with-pdo-mysql --with-pdo-sqlite --with-pear --with-png-dir --with-jpeg-dir --with-xmlrpc --with-xsl --with-zlib --with-bz2 --with-mhash --enable-fpm --enable-bcmath --enable-libxml --enable-inline-optimization --enable-gd-native-ttf --enable-mbregex --enable-mbstring --enable-opcache --enable-pcntl --enable-shmop --enable-soap --enable-sockets --enable-sysvsem --enable-sysvshm --enable-xml --enable-zip --with-ldap

php --version

yongkbmaster ➜  ~ /data/env/runtime/php-7.1.33-debug/bin/php --version
PHP 7.1.33 (cli) (built: Dec 29 2020 19:16:50) ( NTS DEBUG )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologie

에서 DEBUG를 참조하세요. 참고: 확장 프로그램의 디버그 버전은 다시 컴파일하고 설치해야 하며 일반 버전은 그럴 수 없습니다. 설치 방법은 일반 확장과 동일합니다. 일반적으로 추가 디버그 매개변수를 열 필요가 없습니다. swoole과 같은 확장을 디버그해야 하는 경우 확장의 디버그 매개변수를 설정해야 합니다. 확장의 ./configure 파일 설명을 참조할 수 있습니다.

Gdb 사용하기

여기서 gdb의 기본 사용법에 대해 간략하게 소개합니다. 더 자세한 사용법은 직접 구글링해보시면 됩니다. start gdbartcapture process

gdb -p {pid}

run 메소드 start

gdb php
run test3.php
via core 파일
gdb -c core.8451

breakspointingbreak n : line n에서 중단 점을 설정합니다 (코드 경로를 가져올 수 있습니다. 코드명)

//注意:这里只能断点c代码,php文件不行的,var.c:201在php-7.1.33是var_dump的入口
break var.c:201

b fn1 if a>b: 조건부 중단점 설정

break func (break는 b로 축약됨): 함수 func() 입구에 중단점 설정

//大部分php的方法在c层面的方法名都是zif_ + php方法名。 例如 var_dump 在c的方法名叫zif_var_dump
break zif_var_dump

delete 중단점 번호 n: n번째 삭제 breakpointdisable 중단점 번호 n: n번째 중단점 일시 중지enable 중단점 번호 n: n번째 중단점 활성화

clear 줄 번호 n: n번째 줄의 중단점 지우기

info b(정보 중단점): 중단점 설정을 표시합니다. 현재 프로그램

delete breakpoints: 모든 중단점을 지웁니다.

Others

list(약어로 l), 해당 기능은 프로그램 코드의 소스를 나열하는 것입니다. 한 번에 10줄이 표시됩니다. 기본.

list line number: "line number"를 중심으로 현재 파일 앞뒤 10줄의 코드를 표시합니다. print a: a

  • continue(약어 c) 값을 표시합니다. ): 실행을 계속하고 다음 중단점(또는 실행 끝)으로 이동합니다. 중단점을 설정한 후 이 버튼을 눌러야 합니다.

  • next(약어 n): 현재 함수, 다음 줄

  • step(약어 s): 함수 내부로 점프

  • where/bt: 현재 실행 중인 스택 목록

  • php; gdb 작은 도구

  • 이 기사의 초점은 PHP가 gdb용 작은 도구 세트를 제공한다는 것입니다. 소스 코드 디렉토리의 .gdbinit 파일은 gdb PHP 소스 코드를 더 잘 이해하는 데 도움이 될 수 있습니다.
  • 준비
  • 더 나은 시연을 위해 여기에 PHP 파일을 준비하겠습니다.
<?php
const A = &#39;test const&#39;;
const B = &#39;test const B&#39;;
class B {
        public $a = &#39;test&#39;;
        public function funB() {
                var_dump(&#39;test funB&#39;);
        }
}
class C extends B {
        public function funC() {
                var_dump(&#39;test funC&#39;);
        }
}
$a = &#39;test&#39;;
$b = [&#39;a1&#39; => 1, &#39;a2&#39; => 2];
$c = new B();
$d = [A, B];
$e = new C();
$f = $b;
var_dump($a, $b, $c, $d, $e, $f);
get_object_vars($e);

gdb를 시작하고 2개의 중단점을 설정하세요.

gdb php //注意这里要用debug版本的
(gdb) break var.c:211
Breakpoint 1 at 0x76e717: file /data/env/runtime/php-7.1.33-src/ext/standard/var.c, line 211.
(gdb) break zend_object_handlers.c:492
Breakpoint 2 at 0x86ce9d: file /data/env/runtime/php-7.1.33-src/Zend/zend_object_handlers.c, line 492.
(gdb) r test4.php

그런 다음 가젯을 로드하고

source /data/env/runtime/php-7.1.33-src/.gdbinit

zbacktrace를 사용하여 현재 PHP 호출 스택을 표시하고

(gdb) zbacktrace
[0x7ffff1614200] var_dump("test", array(2)[0x7ffff1614260], object[0x7ffff1614270], array(2)[0x7ffff1614280], object[0x7ffff1614290], array(2)[0x7ffff16142a0]) [internal function]
[0x7ffff1614030] (main) /root/test4.php:26

dump_bt를 사용하여 현재 호출 스택 및

(gdb) dump_bt executor_globals.current_execute_data
[0x7ffff1614200] var_dump("test", array(2)[0x7ffff1614260], object[0x7ffff1614270], array(2)[0x7ffff1614280], object[0x7ffff1614290], array(2)[0x7ffff16142a0]) [internal function]
[0x7ffff1614030] (main) /root/test4.php:26

printzv 출력 zend 값

(gdb) printzv &args[0]
[0x7ffff1614250] (refcount=0) string: test
과 유사한 zbacktrace를 확인하세요.

print_global_vars 출력 전역 변수

(gdb) print_global_vars
Hash(13)[0x11bf0d0]: {
  [0] _GET => [0x7ffff1657100] (refcount=2) array:
  [1] _POST => [0x7ffff1657120] (refcount=2) array:
  [2] _COOKIE => [0x7ffff1657140] (refcount=2) array:
  [3] _FILES => [0x7ffff1657160] (refcount=2) array:
  [4] argv => [0x7ffff1657180] (refcount=2) array:
  [5] argc => [0x7ffff16571a0] long: 1
  [6] _SERVER => [0x7ffff16571c0] (refcount=2) array:
  [7] a => [0x7ffff16571e0] indirect: [0x7ffff1613080] (refcount=0) string: test
  [8] b => [0x7ffff1657200] indirect: [0x7ffff1613090] (refcount=5) array:
  [9] c => [0x7ffff1657220] indirect: [0x7ffff16130a0] (refcount=2) object(B) #2
  [10] d => [0x7ffff1657240] indirect: [0x7ffff16130b0] (refcount=2) array:
  [11] e => [0x7ffff1657260] indirect: [0x7ffff16130c0] (refcount=2) object(C) #3
  [12] f => [0x7ffff1657280] indirect: [0x7ffff16130d0] (refcount=5) array:
print_const_table 정의된 상수 출력
(gdb) print_const_table executor_globals.zend_constants
[0x14e8380] {
  Hash(2340)[0x14e8380]: {
    [0] E_ERROR => [0x14fd660] long: 1
    [1] E_RECOVERABLE_ERROR => [0x14fe8a0] long: 4096
    [2] E_WARNING => [0x14fe900] long: 2
    [3] E_PARSE => [0x14fe960] long: 4
    [4] E_NOTICE => [0x14fe9c0] long: 8
    [5] E_STRICT => [0x14fea20] long: 2048
    [6] E_DEPRECATED => [0x14fea80] long: 8192
    [7] E_CORE_ERROR => [0x14feae0] long: 16
    [8] E_CORE_WARNING => [0x14feb40] long: 32
    [9] E_COMPILE_ERROR => [0x14feba0] long: 64
    [10] E_COMPILE_WARNING => [0x14fec10] long: 128
    [11] E_USER_ERROR => [0x14fec70] long: 256
    [12] E_USER_WARNING => [0x14fecd0] long: 512
    [13] E_USER_NOTICE => [0x14fed30] long: 1024
    [14] E_USER_DEPRECATED => [0x14feda0] long: 16384
    [15] E_ALL => [0x14fee00] long: 32767
    [16] DEBUG_BACKTRACE_PROVIDE_OBJECT => [0x14fee70] long: 1
    [17] DEBUG_BACKTRACE_IGNORE_ARGS => [0x14feee0] long: 2
    [18] true => [0x14fef70] bool: true
    [19] false => [0x14ff000] bool: false
    [20] ZEND_THREAD_SAFE => [0x14ff070] bool: false
    [21] ZEND_DEBUG_BUILD => [0x14ff0e0] bool: true
    [22] null => [0x14ff170] NULL
    [23] PHP_VERSION => [0x1500380] (refcount=1) string: 7.1.33
 ......
print_zstr 출력 zend 문자열

(gdb) print_zstr args[0]
string(4) "test"
(gdb) print_zstr args[0] 2
string(4) "te..."
(gdb) print_zstr args[0] 4
string(4) "test"

print_cvs 컴파일된 변수 및 해당 값 인쇄 zend_execute_data 유형 값을 전달해야 합니다. 먼저 호출 스택을 살펴볼 수 있습니다.

(gdb) bt //这里看到 #2 层这里是 zend_vm_execute 的执行入口,这里有zend_execute_data 类型的值。
#0  zif_var_dump (execute_data=0x7ffff1614120, return_value=0x7fffffffa9b0) at /data/env/runtime/php-7.1.33-src/ext/standard/var.c:209
#1  0x0000000000ab08d4 in ZEND_DO_ICALL_SPEC_RETVAL_UNUSED_HANDLER () at /data/env/runtime/php-7.1.33-src/Zend/zend_vm_execute.h:628
#2  0x0000000000ab01c3 in execute_ex (ex=0x7ffff1614030) at /data/env/runtime/php-7.1.33-src/Zend/zend_vm_execute.h:429
#3  0x0000000000ab02d5 in zend_execute (op_array=0x7ffff1672d00, return_value=0x0) at /data/env/runtime/php-7.1.33-src/Zend/zend_vm_execute.h:474
#4  0x0000000000a510f9 in zend_execute_scripts (type=8, retval=0x0, file_count=3) at /data/env/runtime/php-7.1.33-src/Zend/zend.c:1482
#5  0x00000000009c02f4 in php_execute_script (primary_file=0x7fffffffdf30) at /data/env/runtime/php-7.1.33-src/main/main.c:2577
#6  0x0000000000b31387 in do_cli (argc=2, argv=0x14e7f30) at /data/env/runtime/php-7.1.33-src/sapi/cli/php_cli.c:993
#7  0x0000000000b32346 in main (argc=2, argv=0x14e7f30) at /data/env/runtime/php-7.1.33-src/sapi/cli/php_cli.c:1381
(gdb) f 2 //跳到#2 这一层
#2  0x0000000000ab01c3 in execute_ex (ex=0x7ffff1614030) at /data/env/runtime/php-7.1.33-src/Zend/zend_vm_execute.h:429
429                     ((opcode_handler_t)OPLINE->handler)(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU);
(gdb) print_cvs ex //输出
Compiled variables count: 6
[0] &#39;a&#39;
[0x7ffff1614080] (refcount=0) string: test
[1] &#39;b&#39;
[0x7ffff1614090] (refcount=5) array:     Hash(2)[0x7ffff170e300]: {
      [0] a1 => [0x7ffff1793e20] long: 1
      [1] a2 => [0x7ffff1793e40] long: 2
}
[2] &#39;c&#39;
[0x7ffff16140a0] (refcount=2) object(B) #2
Properties     Hash(1)[0x7ffff170e480]: {
      [0] a => [0x7ffff1793f60] indirect: [0x7ffff170e388] (refcount=4) string: test
}
[3] &#39;d&#39;
[0x7ffff16140b0] (refcount=2) array:     Packed(2)[0x7ffff170e3c0]: {
      [0] 0 => [0x7ffff1793688] (refcount=1) string: test const
      [1] 1 => [0x7ffff17936a8] (refcount=1) string: test const B
}
[4] &#39;e&#39;
[0x7ffff16140c0] (refcount=2) object(C) #3
Properties     Hash(1)[0x7ffff170e4e0]: {
      [0] a => [0x7ffff17940a0] indirect: [0x7ffff170e448] (refcount=4) string: test
}
[5] &#39;f&#39;
[0x7ffff16140d0] (refcount=5) array:     Hash(2)[0x7ffff170e300]: {
      [0] a1 => [0x7ffff1793e20] long: 1
      [1] a2 => [0x7ffff1793e40] long: 2
}

print_ht는 HashTable을 출력합니다. HashTable은 PHP 배열의 구현입니다. HashTable은 PHP 소스 코드에서도 널리 사용되어 다양한 내용을 저장합니다. k v 구조 또는 배열 구조.

(gdb) print_ht args[1].value
Hash(2)[0x7ffff170e300]: {
  [0] a1 => [0x7ffff1793e20] long: 1
  [1] a2 => [0x7ffff1793e40] long: 2
}
(gdb) print_ht args[3].value
Packed(2)[0x7ffff170e3c0]: {
  [0] 0 => [0x7ffff1793688] (refcount=1) string: test const
  [1] 1 => [0x7ffff17936a8] (refcount=1) string: test const B
}

print_htptr은 zval의 값이 아닌 zval의 주소를 출력합니다.

(gdb) print_htptr args[1].value
Hash(2)[0x7ffff170e300]: {
  [0] a1 => 0x7ffff1793e20
  [1] a2 => 0x7ffff1793e40
}

print_htstr은 HashTable이 zval 대신 c char을 저장한다는 점을 제외하면 print_ht와 유사합니다. 대부분 문자열을 저장할 때 zend string을 직접 사용하게 되는데, php_cli_server_mime_type_ctor를 사용하는 곳을 찾았습니다.

(gdb) print_htstr &server->extension_mime_types
Hash(2)[0x11b9228]: {
  [0] ez => application/andrew-inset
  [1] aw => application/applixware
}

print_ft는 zend_function의 주소가 저장되어 있다는 점만 빼고는 비슷합니다. HashTable.

(gdb) print_ft &args[2].value.obj.ce.function_table
Hash(1)[0x7ffff1783210]: {
  [0] funb => "funB"
}

print_inh는 클래스 관련 정보를 출력합니다.

(gdb) print_inh &args[4].value.obj.ce
class C extends B {
 class B {
 }
}

print_pi는 객체의 속성과 관련된 정보를 출력하며 zend_object_handlers.c:492에서 사용되는 형식의 주소를 전달해야 합니다. PHP의 get_object_vars($e).

(gdb) c
Continuing.
Breakpoint 2, zend_check_property_access (zobj=0x7ffff170e420, prop_info_name=0x7ffff173c2c0) at /data/env/runtime/php-7.1.33-src/Zend/zend_object_handlers.c:492
492             zend_string_release(member);
(gdb) print_pi property_info
[0x7ffff17833c8] {
    offset = 0x28
    ce = [0x7ffff17831d0] B
    flags = 0x100 (ZEND_ACC_PUBLIC)
    name  = string(1) "a"
    default value: [0x7ffff17690c0] (refcount=4) string: test
}

추천 학습: "

PHP 비디오 튜토리얼

"

위 내용은 PHP에 대한 깊은 이해: gdb를 사용하여 소스 코드 디버깅의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 腾讯技术工程微信公众号에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제