rt-thread icon indicating copy to clipboard operation
rt-thread copied to clipboard

修复C++11 thread_local对象析构函数与实际内存释放动作顺序相反问题

Open atwwww opened this issue 1 year ago • 5 comments

拉取/合并请求描述:(PR description)

[

为什么提交这份PR (why to submit this PR)

修复C++11 thread_local对象析构函数与实际内存释放动作顺序相反问题 原实现方案缺陷:顺序遍历_pthread_key数组,调用TLS析构函数,这导致可能首先遍历到emutls_key_destructor清除实际分配内存,后续才遍历到对象析构函数,造成use after free内存安全隐患,例如,当对象中存在指针时,需要先调用析构函数释放对应指针空间

你的解决方案是什么 (what is your solution)

使用emutls_pthread_key作为标志,从emutls_pthread_key标志前一个index开始倒序遍历, 使得emutls_key_destructor最后被调用

请提供验证的bsp和config (provide the config and bsp)

  • BSP: bsp\stm32\stm32f407-atk-explorer
  • .config: #define RT_USING_CPLUSPLUS #define RT_USING_CPLUSPLUS11
  • action: 修改前: pthread线程结束时,对于C++TLS空间,emutls_key_destructor可能先被调用,释放了对象占用内存空间。之后才调用到对象析构函数。

修改后: 从emutls_pthread_key代表的前一个key槽逆序遍历key调用析构函数,使得emutls_key_destructor最后调用,确保先调用对象的析构函数。

编译通过: image

]

当前拉取/合并请求的状态 Intent for your PR

必须选择一项 Choose one (Mandatory):

  • [ ] 本拉取/合并请求是一个草稿版本 This PR is for a code-review and is intended to get feedback
  • [x] 本拉取/合并请求是一个成熟版本 This PR is mature, and ready to be integrated into the repo

代码质量 Code Quality:

我在这个拉取/合并请求中已经考虑了 As part of this pull request, I've considered the following:

  • [x] 已经仔细查看过代码改动的对比 Already check the difference between PR and old code
  • [x] 代码风格正确,包括缩进空格,命名及其他风格 Style guide is adhered to, including spacing, naming and other styles
  • [x] 没有垃圾代码,代码尽量精简,不包含#if 0代码,不包含已经被注释了的代码 All redundant code is removed and cleaned up
  • [x] 所有变更均有原因及合理的,并且不会影响到其他软件组件代码或BSP All modifications are justified and not affect other components or BSP
  • [x] 对难懂代码均提供对应的注释 I've commented appropriately where code is tricky
  • [x] 代码是高质量的 Code in this PR is of high quality
  • [x] 已经使用formatting 等源码格式化工具确保格式符合RT-Thread代码规范 This PR complies with RT-Thread code specification

atwwww avatar Apr 16 '24 04:04 atwwww

static code analysis似乎误报,提交中未修改对应代码片段: image

image

RT-Thread BSP Static Build Check / others_at32_hc32和提交也无关联。 image

atwwww avatar Apr 16 '24 05:04 atwwww

static code analysis 报错请忽略

mysterywolf avatar Apr 18 '24 03:04 mysterywolf

RT-Thread BSP Static Build Check / others_at32_hc32 (pull_request) 这个CI有报错 麻烦修一下

mysterywolf avatar Apr 24 '24 04:04 mysterywolf

RT-Thread BSP Static Build Check / others_at32_hc32 (pull_request) 这个CI有报错 麻烦修一下

这个报错是不开启C++支持时,emutls.c文件没有被编译,新增加的emutls_get_pthread_key找不到。

做了以下修改:

  1. 使用“RT_USING_CPLUSPLUS11”宏控制,使得C++11支持打开时,才会进行emutls_get_pthread_key符号的查找。同时精简了不启用C++特性时的目标文件大小。
  2. 考虑到C中_Thread_local也会使用emutls,将emutls.c文件移动到posix中,因为emutls依赖于RT_USING_PTHREADS。移动文件后,无论是C还是C++都能够正确使用emutls。

atwwww avatar Apr 24 '24 09:04 atwwww

static code analysis原因: 修改了emutls.c文件位置,ci调用的tools/ci/cpp_check.py脚本找不到移动后的emutls.c文件的位置。

atwwww avatar Apr 27 '24 06:04 atwwww