百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分析 > 正文

每天一个PHP语法五引用计数与写时复制的实现

liebian365 2024-11-21 17:38 18 浏览 0 评论


说明

这里基于php7.2.5进行测试,php7之后内部结构变化应该不是太大,但与php5.X有差别。

引用计数

我们之前说过存放字符串的结构为zend_stirng, 忘了的看着里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 = 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, cli () 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的refcount变为1
$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内核剖析》

相关推荐

“版本末期”了?下周平衡补丁!国服最强5套牌!上分首选

明天,酒馆战棋就将迎来大更新,也聊了很多天战棋相关的内容了,趁此机会,给兄弟们穿插一篇构筑模式的卡组推荐!老规矩,我们先来看10职业胜率。目前10职业胜率排名与一周前基本类似,没有太多的变化。平衡补丁...

VS2017 C++ 程序报错“error C2065:“M_PI”: 未声明的标识符"

首先,程序中头文件的选择,要选择头文件,在文件中是没有对M_PI的定义的。选择:项目——>”XXX属性"——>配置属性——>C/C++——>预处理器——>预处理器定义,...

东营交警实名曝光一批酒驾人员名单 88人受处罚

齐鲁网·闪电新闻5月24日讯酒后驾驶是对自己和他人生命安全极不负责的行为,为守护大家的平安出行路,东营交警一直将酒驾作为重点打击对象。5月23日,东营交警公布最新一批饮酒、醉酒名单。对以下驾驶人醉酒...

Qt界面——搭配QCustomPlot(qt platform)

这是我第一个使用QCustomPlot控件的上位机,通过串口精确的5ms发送一次数据,再将读取的数据绘制到图表中。界面方面,尝试卡片式设计,外加QSS简单的配了个色。QCustomPlot官网:Qt...

大话西游2分享赢取种族坐骑手办!PK趣闻录由你书写

老友相聚,仗剑江湖!《大话西游2》2021全民PK季4月激燃打响,各PK玩法鏖战齐开,零门槛参与热情高涨。PK季期间,不仅各种玩法奖励丰厚,参与PK趣闻录活动,投稿自己在PK季遇到的趣事,还有机会带走...

测试谷歌VS Code AI 编程插件 Gemini Code Assist

用ClaudeSonnet3.7的天气测试编码,让谷歌VSCodeAI编程插件GeminiCodeAssist自动编程。生成的文件在浏览器中的效果如下:(附源代码)VSCode...

顾爷想知道第4.5期 国服便利性到底需优化啥?

前段时间DNF国服推出了名为“阿拉德B计划”的系列改版计划,截至目前我们已经看到了两项实装。不过关于便利性上,国服似乎还有很多路要走。自从顾爷回归DNF以来,几乎每天都在跟我抱怨关于DNF里面各种各样...

掌握Visual Studio项目配置【基础篇】

1.前言VisualStudio是Windows上最常用的C++集成开发环境之一,简称VS。VS功能十分强大,对应的,其配置系统较为复杂。不管是对于初学者还是有一定开发经验的开发者来说,捋清楚VS...

还嫌LED驱动设计套路深?那就来看看这篇文章吧

随着LED在各个领域的不同应用需求,LED驱动电路也在不断进步和发展。本文从LED的特性入手,推导出适合LED的电源驱动类型,再进一步介绍各类LED驱动设计。设计必读:LED四个关键特性特性一:非线...

Visual Studio Community 2022(VS2022)安装图文方法

直接上步骤:1,首先可以下载安装一个VisualStudio安装器,叫做VisualStudioinstaller。这个安装文件很小,很快就安装完成了。2,打开VisualStudioins...

Qt添加MSVC构建套件的方法(qt添加c++11)

前言有些时候,在Windows下因为某些需求需要使用MSVC编译器对程序进行编译,假设我们安装Qt的时候又只是安装了MingW构建套件,那么此时我们该如何给现有的Qt添加一个MSVC构建套件呢?本文以...

Qt为什么站稳c++GUI的top1(qt c)

为什么现在QT越来越成为c++界面编程的第一选择,从事QT编程多年,在这之前做C++界面都是基于MFC。当时为什么会从MFC转到QT?主要原因是MFC开发界面想做得好看一些十分困难,引用第三方基于MF...

qt开发IDE应该选择VS还是qt creator

如果一个公司选择了qt来开发自己的产品,在面临IDE的选择时会出现vs或者qtcreator,选择qt的IDE需要结合产品需求、部署平台、项目定位、程序猿本身和公司战略,因为大的软件产品需要明确IDE...

Qt 5.14.2超详细安装教程,不会来打我

Qt简介Qt(官方发音[kju:t],音同cute)是一个跨平台的C++开库,主要用来开发图形用户界面(GraphicalUserInterface,GUI)程序。Qt是纯C++开...

Cygwin配置与使用(四)——VI字体和颜色的配置

简介:VI的操作模式,基本上VI可以分为三种状态,分别是命令模式(commandmode)、插入模式(Insertmode)和底行模式(lastlinemode),各模式的功能区分如下:1)...

取消回复欢迎 发表评论: