Skip to content

[drivers][ofw] Fix phandle hash buffer overflow - #11845

Open
Huoyanlifusu wants to merge 1 commit into
RT-Thread:masterfrom
Huoyanlifusu:fix/ofw-phandle-hash-overflow
Open

Huoyanlifusu wants to merge 1 commit into
RT-Thread:masterfrom
Huoyanlifusu:fix/ofw-phandle-hash-overflow

Conversation

@Huoyanlifusu

@Huoyanlifusu Huoyanlifusu commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

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

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

ofw_phandle_hash_reset() 分配 phandle 表时使用了 max - min,但查找时的下标是 phandle - min。当 phandle 等于范围上限时,会访问到分配区域之外。

另外,扩容时直接把旧的 phandle 上限 old_max 当成数组下标来清零,没有减去起始值。当起始 phandle 不是 1 时,清零位置不正确,可能越界或漏掉新增表项。

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

分配数量改为 max - min + 1,包含范围的两个端点。扩容时根据 old_max - old_min + 1 计算旧表项数量,从旧表末尾开始清零新增区域。

在 Linux PC 上提取修复前后的原函数,使用 GCC 和 AddressSanitizer / UndefinedBehaviorSanitizer 做了函数级验证,内存分配接口用主机的 calloc/realloc 模拟:

  • 起始 phandle 分别取 1、5、128,检查访问上限 128 对应的表项;
  • 将上限从 128 扩展到 256,检查旧表项保留、新增表项全部清零。

共 6 个用例,修复前均触发 AddressSanitizer 堆越界报告,修复后全部通过。随后在 QEMU AArch64 virt 上完成 BSP 编译和启动验证,结果如下。

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

  • BSP: bsp/qemu-virt64-aarch64,QEMU 6.2.0,AArch64 virt,4 核,128 MB 内存。
  • .config: 使用 BSP 默认配置,未修改配置项。默认已启用 CONFIG_RT_USING_OFW=y、CONFIG_RT_USING_SMP=y、CONFIG_RT_CPUS_NR=4、CONFIG_RT_USING_MEMHEAP_AS_HEAP=y。
  • action: 本地 SCons 构建通过,GitHub Actions 尚未运行。

QEMU 中增加了临时测试代码,将修复后的分配函数原样提取,仅重命名函数并使用独立的表状态,调用 RT-Thread 的内存分配接口,避免影响系统正在使用的 phandle 表。同时遍历实际设备树,调用 rt_ofw_find_node_by_phandle() 检查返回节点是否一致。测试代码不包含在本次提交中。

PHANDLE min=1 boundary=PASS
PHANDLE min=1 grow=PASS preserved=PASS zero=PASS
PHANDLE min=5 boundary=PASS
PHANDLE min=5 grow=PASS preserved=PASS zero=PASS
PHANDLE min=128 boundary=PASS
PHANDLE min=128 grow=PASS preserved=PASS zero=PASS
PHANDLE live_dtb_lookup=PASS nodes=8
PHANDLE ALL PASS

系统正常进入 MSH,未出现测试断言失败。本次未进行实板验证。

QEMU 验证命令及临时测试代码(AI 辅助生成)

将下方代码保存为 BSP 的 applications/phandle_verify.c,在 BSP 目录执行(RTT_EXEC_PATH 指向自己的 AArch64 bare-metal 工具链):

export RTT_EXEC_PATH=/path/to/aarch64-none-elf-toolchain/bin
scons -j8
qemu-system-aarch64 -M virt,gic-version=2 -cpu max -smp 4 -m 128 \
  -kernel rtthread.bin \
  -append 'console=ttyAMA0 earlycon cma=8M coherent_pool=2M' \
  -nographic

测试代码:

#include <rtthread.h>
#include <drivers/ofw.h>
#define OFW_NODE_MIN_HASH 128
static rt_phandle _phandle_range[2] = {1,1}, _phandle_next = 1;
static struct rt_ofw_node **_phandle_hash;
rt_err_t test_hash_reset(rt_phandle min, rt_phandle max)
{
    rt_err_t err = RT_EOK;
    rt_phandle next = max;
    struct rt_ofw_node **hash_ptr = RT_NULL;

    max = RT_ALIGN(max, OFW_NODE_MIN_HASH);

    if (max > _phandle_range[1])
    {
        rt_size_t size = sizeof(*_phandle_hash) * (max - min + 1);

        if (!_phandle_hash)
        {
            hash_ptr = rt_calloc(1, size);
        }
        else
        {
            hash_ptr = rt_realloc(_phandle_hash, size);

            if (hash_ptr)
            {
                rt_size_t old_min = _phandle_range[0];
                rt_size_t old_max = _phandle_range[1];
                rt_size_t old_count = old_max - old_min + 1;

                rt_memset(&hash_ptr[old_count], 0, size - old_count * sizeof(*_phandle_hash));
            }
        }
    }

    if (hash_ptr)
    {
        /* We always reset min value only once */
        if (min)
        {
            _phandle_range[0] = min;
        }
        _phandle_range[1] = max;
        _phandle_next = next + 1;
        _phandle_hash = hash_ptr;
    }
    else
    {
        err = -RT_ENOMEM;
    }

    return err;
}


static int phandle_verify(void)
{
    unsigned mins[] = {1,5,128};
    unsigned c, i, count = 0;
    struct rt_ofw_node *np, *found;
    static struct rt_ofw_node marker;
    for(c=0;c<3;c++)
    {
        unsigned min=mins[c];
        _phandle_range[0]=1; _phandle_range[1]=1;
        _phandle_hash=RT_NULL;
        RT_ASSERT(test_hash_reset(min,128)==RT_EOK);
        _phandle_hash[128-min]=&marker;
        RT_ASSERT(_phandle_hash[128-min]==&marker);
        rt_kprintf("PHANDLE min=%u boundary=PASS\n",min);
        RT_ASSERT(test_hash_reset(min,129)==RT_EOK);
        RT_ASSERT(_phandle_hash[128-min]==&marker);
        for(i=129-min;i<=256-min;i++) RT_ASSERT(_phandle_hash[i]==RT_NULL);
        rt_kprintf("PHANDLE min=%u grow=PASS preserved=PASS zero=PASS\n",min);
        rt_free(_phandle_hash);
    }
    rt_ofw_foreach_allnodes(np)
    {
        if(!np->phandle || np->phandle==0xffffffffU) continue;
        found=rt_ofw_find_node_by_phandle(np->phandle);
        RT_ASSERT(found==np);
        rt_ofw_node_put(found);
        count++;
    }
    RT_ASSERT(count>0);
    rt_kprintf("PHANDLE live_dtb_lookup=PASS nodes=%u\n",count);
    rt_kprintf("PHANDLE ALL PASS\n");
    return 0;
}
INIT_APP_EXPORT(phandle_verify);

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

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

  • 本拉取/合并请求是一个草稿版本 This PR is for a code-review and is intended to get feedback
  • 本拉取/合并请求是一个成熟版本 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:

@github-actions

Copy link
Copy Markdown

👋 感谢您对 RT-Thread 的贡献!Thank you for your contribution to RT-Thread!

为确保代码符合 RT-Thread 的编码规范,请在你的仓库中执行以下步骤运行代码格式化工作流(如果格式化CI运行失败)。
To ensure your code complies with RT-Thread's coding style, please run the code formatting workflow by following the steps below (If the formatting of CI fails to run).


🛠 操作步骤 | Steps

  1. 前往 Actions 页面 | Go to the Actions page
    点击进入工作流 → | Click to open workflow →

  2. 点击 Run workflow | Click Run workflow

  • Use workflow from 保持默认分支(通常为 master)
    Keep the default branch (usually master) in Use workflow from
  • 在 branch 输入框填写 PR 分支 fix/ofw-phandle-hash-overflow
    Enter PR branch fix/ofw-phandle-hash-overflow in the branch field
  • 设置需排除的文件/目录(目录请以"/"结尾)
    Set files/directories to exclude (directories should end with "/")
  1. 等待工作流完成 | Wait for the workflow to complete
    格式化后的代码将作为独立提交推送至你的分支。
    The formatting changes will be pushed to your branch as a separate commit.

完成后,提交将自动更新至 fix/ofw-phandle-hash-overflow 分支,关联的 Pull Request 也会同步更新。
Once completed, commits will be pushed to the fix/ofw-phandle-hash-overflow branch automatically, and the related Pull Request will be updated.

如有问题欢迎联系我们,再次感谢您的贡献!💐
If you have any questions, feel free to reach out. Thanks again for your contribution!

@github-actions

Copy link
Copy Markdown

📌 Code Review Assignment

🏷️ Tag: components

Reviewers: @Maihuanyi

Changed Files (Click to expand)
  • components/drivers/ofw/base.c

📊 Current Review Status (Last Updated: 2026-09-29 20:11 CST)


📝 Review Instructions

  1. 维护者可以通过单击此处来刷新审查状态: 🔄 刷新状态
    Maintainers can refresh the review status by clicking here: 🔄 Refresh Status

  2. 确认审核通过后评论 LGTM/lgtm
    Comment LGTM/lgtm after confirming approval

  3. PR合并前需至少一位维护者确认
    PR must be confirmed by at least one maintainer before merging

ℹ️ 刷新CI状态操作需要具备仓库写入权限。
ℹ️ Refresh CI status operation requires repository Write permission.

@github-actions

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant