每天一個 PHP 語法五引用計數與寫時複製的實現

ifelse發表於2020-04-18

說明

這裡基於php7.2.5進行測試,php7之後內部結構變化應該不是太大,但與php5.X有差別。

引用計數

我們之前說過存放字串的結構為zend_stirng, 忘了的看著裡

struct _zend_string {
  // 這裡是引用計數
    zend_refcounted_h gc; 
    zend_ulong        h;                /* hash value */
    size_t            len; // 長度
    char              val[1]; // 內容
};

來看zend_refcounted_h的結構

typedef struct _zend_refcounted_h {
  // 我們只關注這裡 整型的 引用計數 1/2/3...
    uint32_t         refcount;            /* reference counter 32-bit */
    union {
        struct {
            ZEND_ENDIAN_LOHI_3(
                zend_uchar    type,
                zend_uchar    flags,    /* used for strings & objects */
                uint16_t      gc_info)  /* keeps GC root number (or 0) and color */
        } v;
        uint32_t type_info;
    } u;
} zend_refcounted_h;

引用計數是什麼

因為引用計數存在zend_value的具體型別中的,如zend_string, zend_array等,所以,引用計數是指當前這個zend_value被多少個zval指向。

引用計數如何產生作用

$a = "hi".time();
$b = $a;

$a = time()."hello";
echo $a;

$b = $a;

echo $b;

當賦值$a時,$a指向”hi”.time()所在的zend_value, 所以此時引用計數為1

當$b賦值時,$b也指向了”hi”.time(), 這時引用計數更新為2

$a = time()."hello";
echo $a;

$b = $a;

echo $b;

unset($b);

echo $a;

這裡我們通過gdb除錯程式可以看到引用計數的變化

gdb /home/php7.2.5/debug/bin/php
// 設定斷點  ZEND_ECHO_SPEC_CV_HANDLER 是echo 的處理程式
(gdb) b ZEND_ECHO_SPEC_CV_HANDLER
Breakpoint 1 at 0x973289: file /root/php-7.2.5/Zend/zend_vm_execute.h, line 33086.
// 執行指令碼
(gdb) run hello.php

// 第一個echo斷點
Breakpoint 1, ZEND_ECHO_SPEC_CV_HANDLER () at /root/php-7.2.5/Zend/zend_vm_execute.h:33086
33086        SAVE_OPLINE();
Missing separate debuginfos, use: debuginfo-install glibc-2.17-222.el7.x86_64 libxml2-2.9.1-6.el7_2.3.x86_64 nss-softokn-freebl-3.36.0-5.el7_5.x86_64 xz-libs-5.2.2-1.el7.x86_64 zlib-1.2.7-17.el7.x86_64
(gdb) n
33087        z = _get_zval_ptr_cv_undef(opline->op1.var EXECUTE_DATA_CC);
(gdb) n
33089        if (Z_TYPE_P(z) == IS_STRING) {
// 列印當前zval, zval.u1.v.type=6說明是字串
(gdb) p *z
$1 = {value = {lval = 140737318919936, dval = 6.9533474366143666e-310, counted = 0x7ffff5e69f00, str = 0x7ffff5e69f00, arr = 0x7ffff5e69f00, obj = 0x7ffff5e69f00,
    res = 0x7ffff5e69f00, ref = 0x7ffff5e69f00, ast = 0x7ffff5e69f00, zv = 0x7ffff5e69f00, ptr = 0x7ffff5e69f00, ce = 0x7ffff5e69f00, func = 0x7ffff5e69f00, ww = {
      w1 = 4125531904, w2 = 32767}}, u1 = {v = {type = 6 '\006', type_flags = 20 '\024', const_flags = 0 '\000', reserved = 0 '\000'}, type_info = 5126}, u2 = {next = 0,
    cache_slot = 0, lineno = 0, num_args = 0, fe_pos = 0, fe_iter_idx = 0, access_flags = 0, property_guard = 0, extra = 0}}
(gdb) p *$1.value.str
// 可以看到 目前的refcount=1
$2 = {gc = {refcount = 1, u = {v = {type = 6 '\006', flags = 0 '\000', gc_info = 0}, type_info = 6}}, h = 0, len = 15, val = "1"}
(gdb) p *$2.val@15
$3 = "1587044278hello"
(gdb) n
33090            zend_string *str = Z_STR_P(z);
(gdb) n
33092            if (ZSTR_LEN(str) != 0) {
(gdb) c
Continuing.
1587044278hello
// 到了第二個echo
Breakpoint 1, ZEND_ECHO_SPEC_CV_HANDLER () at /root/php-7.2.5/Zend/zend_vm_execute.h:33086
33086        SAVE_OPLINE();
(gdb) p z
$4 = (zval *) 0x7ffff5e1e090
// 列印當前的zval 
(gdb) p *z
$5 = {value = {lval = 140737318919936, dval = 6.9533474366143666e-310, counted = 0x7ffff5e69f00, str = 0x7ffff5e69f00, arr = 0x7ffff5e69f00, obj = 0x7ffff5e69f00,
    res = 0x7ffff5e69f00, ref = 0x7ffff5e69f00, ast = 0x7ffff5e69f00, zv = 0x7ffff5e69f00, ptr = 0x7ffff5e69f00, ce = 0x7ffff5e69f00, func = 0x7ffff5e69f00, ww = {
      w1 = 4125531904, w2 = 32767}}, u1 = {v = {type = 6 '\006', type_flags = 20 '\024', const_flags = 0 '\000', reserved = 0 '\000'}, type_info = 5126}, u2 = {next = 0,
    cache_slot = 0, lineno = 0, num_args = 0, fe_pos = 0, fe_iter_idx = 0, access_flags = 0, property_guard = 0, extra = 0}}
(gdb) p *$5.value.str
// 可以看到refount增加為2
$6 = {gc = {refcount = 2, u = {v = {type = 6 '\006', flags = 0 '\000', gc_info = 0}, type_info = 6}}, h = 0, len = 15, val = "1"}

可以看到當給$a賦值時,值的引用計數為1,當$a賦值給$b,引用計數再次加1變為2.


// unset 操作的處理
Breakpoint 2, ZEND_UNSET_CV_SPEC_CV_UNUSED_HANDLER () at /root/php-7.2.5/Zend/zend_vm_execute.h:40511
40511        zval *var = EX_VAR(opline->op1.var);
(gdb) n
40513        if (Z_REFCOUNTED_P(var)) {
(gdb) n
40514            zend_refcounted *garbage = Z_COUNTED_P(var);
(gdb) n
40516            ZVAL_UNDEF(var);
(gdb) n
40517            SAVE_OPLINE();
(gdb) n
// --GC_REFCOUNT 引用計數減一
40518            if (!--GC_REFCOUNT(garbage)) {
(gdb) n
40521                gc_check_possible_root(garbage);
(gdb) n
40523            ZEND_VM_NEXT_OPCODE_CHECK_EXCEPTION();
(gdb) n
40528    }
(gdb) p *var
$5 = {value = {lval = 140737318919936, dval = 6.9533474366143666e-310, counted = 0x7ffff5e69f00, str = 0x7ffff5e69f00, arr = 0x7ffff5e69f00, obj = 0x7ffff5e69f00,
    res = 0x7ffff5e69f00, ref = 0x7ffff5e69f00, ast = 0x7ffff5e69f00, zv = 0x7ffff5e69f00, ptr = 0x7ffff5e69f00, ce = 0x7ffff5e69f00, func = 0x7ffff5e69f00, ww = {
      w1 = 4125531904, w2 = 32767}}, u1 = {v = {type = 0 '\000', type_flags = 0 '\000', const_flags = 0 '\000', reserved = 0 '\000'}, type_info = 0}, u2 = {next = 0,
    cache_slot = 0, lineno = 0, num_args = 0, fe_pos = 0, fe_iter_idx = 0, access_flags = 0, property_guard = 0, extra = 0}}
(gdb) p *$5.value.str
// 再次列印value的ref
$6 = {gc = {refcount = 1, u = {v = {type = 6 '\006', flags = 0 '\000', gc_info = 0}, type_info = 6}}, h = 0, len = 15, val = "1"}
(gdb)

也就是在執行unset($b)之後引用計數減一

寫時複製

意思就是變數發生變化時再複製一份。

如上所示$b=$a時,並沒有把$a複製一份給$b,而是$b、$a指向同一個zend_value, 並更新zend_value的refcount,這樣是節省記憶體的。

那如果接著操作$b重新賦值會發生什麼呢

$a = time()."hello";
echo $a;

$b = $a;


$b = "hi".time();

echo $b;


看除錯結果

(gdb) p *z
$1 = {value = {lval = 140737318919856, dval = 6.9533474366104141e-310, counted = 0x7ffff5e69eb0, str = 0x7ffff5e69eb0, arr = 0x7ffff5e69eb0, obj = 0x7ffff5e69eb0,
    res = 0x7ffff5e69eb0, ref = 0x7ffff5e69eb0, ast = 0x7ffff5e69eb0, zv = 0x7ffff5e69eb0, ptr = 0x7ffff5e69eb0, ce = 0x7ffff5e69eb0, func = 0x7ffff5e69eb0, ww = {
      w1 = 4125531824, w2 = 32767}}, u1 = {v = {type = 6 '\006', type_flags = 20 '\024', const_flags = 0 '\000', reserved = 0 '\000'}, type_info = 5126}, u2 = {next = 0,
    cache_slot = 0, lineno = 0, num_args = 0, fe_pos = 0, fe_iter_idx = 0, access_flags = 0, property_guard = 0, extra = 0}}
(gdb) p z
$2 = (zval *) 0x7ffff5e1e080
(gdb) p *$1.value.str
// $a = time()."hello" 之後 refcount=1
$3 = {gc = {refcount = 1, u = {v = {type = 6 '\006', flags = 0 '\000', gc_info = 0}, type_info = 6}}, h = 0, len = 15, val = "1"}
(gdb) p *$3.val@15
$4 = "1587215850hello"
......
(gdb) c
Continuing.
1587215850hello
// $b = $a 操作
Breakpoint 2, ZEND_ASSIGN_SPEC_CV_CV_RETVAL_UNUSED_HANDLER () at /root/php-7.2.5/Zend/zend_vm_execute.h:43779
43779        SAVE_OPLINE();
(gdb) n
43780        value = _get_zval_ptr_cv_BP_VAR_R(opline->op2.var EXECUTE_DATA_CC);
(gdb) n
43781        variable_ptr = _get_zval_ptr_cv_undef_BP_VAR_W(opline->op1.var EXECUTE_DATA_CC);
(gdb) n
43789            value = zend_assign_to_variable(variable_ptr, value, IS_CV);
(gdb) n
43797        ZEND_VM_NEXT_OPCODE_CHECK_EXCEPTION();
(gdb) n
43798    }
(gdb) p *value
$5 = {value = {lval = 140737318919856, dval = 6.9533474366104141e-310, counted = 0x7ffff5e69eb0, str = 0x7ffff5e69eb0, arr = 0x7ffff5e69eb0, obj = 0x7ffff5e69eb0,
    res = 0x7ffff5e69eb0, ref = 0x7ffff5e69eb0, ast = 0x7ffff5e69eb0, zv = 0x7ffff5e69eb0, ptr = 0x7ffff5e69eb0, ce = 0x7ffff5e69eb0, func = 0x7ffff5e69eb0, ww = {
      w1 = 4125531824, w2 = 32767}}, u1 = {v = {type = 6 '\006', type_flags = 20 '\024', const_flags = 0 '\000', reserved = 0 '\000'}, type_info = 5126}, u2 = {next = 0,
    cache_slot = 0, lineno = 0, num_args = 0, fe_pos = 0, fe_iter_idx = 0, access_flags = 0, property_guard = 0, extra = 0}}
(gdb) p *$5.value.str
// $b = $a之後 refcount=2
$6 = {gc = {refcount = 2, u = {v = {type = 6 '\006', flags = 0 '\000', gc_info = 0}, type_info = 6}}, h = 0, len = 15, val = "1"}

....

// $b = "hi".time()
Breakpoint 1, ZEND_ECHO_SPEC_CV_HANDLER () at /root/php-7.2.5/Zend/zend_vm_execute.h:33086
33086        SAVE_OPLINE();
(gdb) n
33087        z = _get_zval_ptr_cv_undef(opline->op1.var EXECUTE_DATA_CC);
(gdb) n
33089        if (Z_TYPE_P(z) == IS_STRING) {
(gdb) p *z
  // 注意str的地址 跟$a不是一個了
$7 = {value = {lval = 140737318919936, dval = 6.9533474366143666e-310, counted = 0x7ffff5e69f00, str = 0x7ffff5e69f00, arr = 0x7ffff5e69f00, obj = 0x7ffff5e69f00,
    res = 0x7ffff5e69f00, ref = 0x7ffff5e69f00, ast = 0x7ffff5e69f00, zv = 0x7ffff5e69f00, ptr = 0x7ffff5e69f00, ce = 0x7ffff5e69f00, func = 0x7ffff5e69f00, ww = {
      w1 = 4125531904, w2 = 32767}}, u1 = {v = {type = 6 '\006', type_flags = 20 '\024', const_flags = 0 '\000', reserved = 0 '\000'}, type_info = 5126}, u2 = {next = 0,
    cache_slot = 0, lineno = 0, num_args = 0, fe_pos = 0, fe_iter_idx = 0, access_flags = 0, property_guard = 0, extra = 0}}
(gdb) p *$7.value.str
// 新值的refcount=1
$8 = {gc = {refcount = 1, u = {v = {type = 6 '\006', flags = 0 '\000', gc_info = 0}, type_info = 6}}, h = 0, len = 12, val = "h"}
(gdb) p *$8.val@12
$12 = "hi1587216014"

// 再來看 原值的refcount 變為了1
(gdb) p *$1.value.str
$11 = {gc = {refcount = 1, u = {v = {type = 6 '\006', flags = 0 '\000', gc_info = 0}, type_info = 6}}, h = 0, len = 15, val = "1"}

總結

引用計數與寫時複製是PHP自動垃圾回收的基礎。

通過對zval的引用計數的變化監測判斷是否可以回收變數,而寫時複製則會節省變數所佔記憶體。

注意事項:

gdb除錯時,PHP必須要開啟debug模式,在編譯的時候加上–enable-debug即可

參考資料:
《PHP7核心剖析》

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章