Skip to content

[drivers][virtio] Fix RPMsg probe error handling and NS memory leaks - #11968

Open
Huoyanlifusu wants to merge 1 commit into
RT-Thread:masterfrom
Huoyanlifusu:fix/virtio-rpmsg-release
Open

Huoyanlifusu wants to merge 1 commit into
RT-Thread:masterfrom
Huoyanlifusu:fix/virtio-rpmsg-release

Conversation

@Huoyanlifusu

@Huoyanlifusu Huoyanlifusu commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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

[

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

  1. virtio_rpmsg 在 probe 函数申请 vrpmsg->ns 失败后,直接进入失败分支,未置错误码,会返回 0 让上层驱动认为 probe 成功,导致后续有指针踩踏风向。
  2. virtio_rpmsg 在 probe 函数 device_register 失败后,未释放 rpmsg namespace 内存,导致内存泄漏风险。

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

针对两处风险进行优化。

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

  • BSP: bsp/qemu-virt64-aarch64 (standard RT-Thread, SMP 4 cores).
  • Toolchain: Arm GNU Toolchain 13.2.Rel1, aarch64-none-elf / Newlib 4.3.0.
  • Emulator: QEMU 6.2.0, virt, Cortex-A53, GICv2, 128 MiB RAM.
  • .config: starting from this BSP's committed configuration, enable the following and regenerate rtconfig.h with scons --pyconfig-silent (do not edit the generated header):
CONFIG_RT_USING_RPMSG=y
CONFIG_RT_RPMSG_CHAR_MSG_MAX=64
CONFIG_RT_RPMSG_CHAR_MSG_SIZE_MAX=256
# CONFIG_RT_RPMSG_RT_THREAD_VIRTIO is not set
CONFIG_RT_VIRTIO_RPMSG=y
  • action: No GitHub Actions result is claimed here. Build and QEMU execution were performed locally.

测试结果与范围 (test results and scope)

The RPMsg-enabled BSP builds and boots to msh. The temporary test below includes the actual virtio-rpmsg.c and invokes its probe/remove functions using real RT-Thread heap allocations. It replaces bus registration/removal and queue setup/notification with controlled stubs, injects allocation/registration failures, and checks return codes and allocation/free counts.

测试代码由 AI 辅助生成,并已在本地 QEMU 中实际编译、执行。它验证这次修改的错误路径和对象释放,不是双核 RPMsg 端到端通信测试,也没有覆盖真实总线回调、DMA、中断或板端行为。测试代码仅附在 PR 中供复现,没有加入提交。

AI disclosure: The temporary test harness was generated with AI assistance and actually built and run under QEMU. It is a lifecycle/fault-injection test, not an end-to-end RPMsg communication or physical-board test. The harness is provided below for reproduction and is not part of the patch.

Case Before fix After fix
NS allocation fails FAIL: returns 0 instead of -RT_ENOMEM PASS
NS registration fails FAIL: 4 allocations, 3 frees PASS: 4 allocations, 4 frees
Parent registration fails PASS PASS
Normal removal with NS FAIL: 4 allocations, 3 frees PASS: 4 allocations, 4 frees
Normal removal without NS PASS PASS

Before-fix run: the same harness was built against the parent version of virtio-rpmsg.c (cbc19778d0), reproducing all three defects. After-fix run: 65f5028613, 5/5 passed.

RPMSG_TEST ns_alloc_failure PASS ret=-12 expected=-12 alloc=3 free=3 remove=1 release=1
RPMSG_TEST ns_register_failure PASS ret=-22 expected=-22 alloc=4 free=4 remove=1 release=1
RPMSG_TEST parent_register_failure PASS ret=-22 expected=-22 alloc=3 free=3 remove=0 release=1
RPMSG_TEST normal_remove_ns PASS ret=0 expected=0 alloc=4 free=4 remove=2 release=1
RPMSG_TEST normal_remove_no_ns PASS ret=0 expected=0 alloc=3 free=3 remove=1 release=1
RPMSG_TEST SUMMARY 5/5 passed

如何复现 (reproduction)

In a disposable checkout, save the code below as bsp/qemu-virt64-aarch64/applications/rpmsg_lifecycle_review.c. The existing application SConscript picks it up automatically. Apply the configuration above, set RTT_EXEC_PATH to the toolchain's bin directory, then run from the BSP directory:

scons --pyconfig-silent
scons -j8
qemu-system-aarch64 -M virt,gic-version=2 -cpu cortex-a53 -smp 4 -m 128M \
  -kernel rtthread.bin -append 'console=ttyAMA0 earlycon' \
  -display none -serial mon:stdio -net none

At the msh prompt, run rpmsg_lifecycle_test. Exit QEMU with Ctrl+A, then X. For the baseline comparison, use the parent version of components/drivers/virtio/virtio-rpmsg.c in the disposable checkout and rebuild with the same harness and configuration.

完整测试代码 / Full AI-assisted QEMU lifecycle test harness
#include <rtthread.h>
#include <rtdevice.h>
#include <drivers/rpmsg.h>
#include <drivers/virtio.h>

/* Temporary QEMU-only fault injection; never included in the pushed commit. */
enum review_case { NS_ALLOC_FAIL, NS_REGISTER_FAIL, PARENT_REGISTER_FAIL, NORMAL_NS, NORMAL_NO_NS };
static enum review_case scenario;
static void *live[8];
static int calloc_calls, allocs, frees, registrations, removals, releases;
static struct rt_virtqueue review_queues[2];

static void *track(void *ptr)
{
    if (ptr)
    {
        for (int i = 0; i < 8; ++i)
        {
            if (!live[i])
            {
                live[i] = ptr;
                ++allocs;
                return ptr;
            }
        }
        RT_ASSERT(0);
    }
    return ptr;
}

static rt_bool_t is_live(void *ptr)
{
    for (int i = 0; i < 8; ++i)
        if (ptr && live[i] == ptr)
            return RT_TRUE;
    return RT_FALSE;
}

static void *review_calloc(rt_size_t count, rt_size_t size)
{
    ++calloc_calls;
    if (scenario == NS_ALLOC_FAIL && calloc_calls == 2)
        return RT_NULL;
    return track(rt_calloc(count, size));
}

static void *review_malloc(rt_size_t size)
{
    return track(rt_malloc(size));
}

static void review_free(void *ptr)
{
    if (!ptr)
        return;
    for (int i = 0; i < 8; ++i)
    {
        if (live[i] == ptr)
        {
            live[i] = RT_NULL;
            ++frees;
            rt_free(ptr);
            return;
        }
    }
    RT_ASSERT(0);
}

static rt_err_t review_register(struct rt_rpmsg_device *dev)
{
    RT_ASSERT(is_live(dev));
    ++registrations;
    if ((scenario == PARENT_REGISTER_FAIL && registrations == 1) ||
        (scenario == NS_REGISTER_FAIL && registrations == 2))
        return -RT_EINVAL;
    return RT_EOK;
}

static rt_err_t review_remove(rt_device_t dev)
{
    /* Embedded parent members start at offset zero in both objects. */
    RT_ASSERT(is_live(dev));
    ++removals;
    return RT_EOK;
}

static rt_err_t review_install(struct rt_virtio_device *dev, int count,
        struct rt_virtqueue *vqs[], const char *names[], rt_virtqueue_callback cbs[])
{
    RT_ASSERT(count == 2);
    rt_memset(review_queues, 0, sizeof(review_queues));
    for (int i = 0; i < count; ++i)
    {
        vqs[i] = &review_queues[i];
        vqs[i]->vdev = dev;
        vqs[i]->name = names[i];
        vqs[i]->callback = cbs[i];
    }
    return RT_EOK;
}

static rt_err_t review_release(struct rt_virtio_device *dev)
{
    (void)dev;
    ++releases;
    return RT_EOK;
}

static rt_size_t review_queue_size(struct rt_virtqueue *vq)
{
    (void)vq;
    return 8;
}

static rt_err_t review_add_in(struct rt_virtqueue *vq, void *buf, rt_size_t size)
{
    (void)vq; (void)buf; (void)size;
    return RT_EOK;
}

static rt_bool_t review_notify(struct rt_virtqueue *vq)
{
    (void)vq;
    return RT_TRUE;
}

#define rt_calloc review_calloc
#define rt_malloc review_malloc
#define rt_free review_free
#define rt_rpmsg_device_register review_register
#define rt_bus_remove_device review_remove
#define rt_virtio_virtqueue_install review_install
#define rt_virtio_virtqueue_release review_release
#define rt_virtqueue_get_virtq_size review_queue_size
#define rt_virtqueue_add_inbuf review_add_in
#define rt_virtqueue_submit review_notify
#define rt_virtqueue_notify review_notify
#undef RT_VIRTIO_DRIVER_EXPORT
#define RT_VIRTIO_DRIVER_EXPORT(driver)
#include "../../../components/drivers/virtio/virtio-rpmsg.c"
#undef rt_calloc
#undef rt_malloc
#undef rt_free

static int run_case(enum review_case which, const char *name, rt_err_t expected)
{
    struct rt_virtio_device dev = {0};
    int failed;
    scenario = which;
    calloc_calls = allocs = frees = registrations = removals = releases = 0;
    rt_memset(live, 0, sizeof(live));
    dev.features = which == NORMAL_NO_NS ? 0 : RT_BIT(VIRTIO_RPMSG_F_NS);
    rt_err_t result = virtio_rpmsg_probe(&dev);
    if (expected == RT_EOK && result == RT_EOK && is_live(dev.priv))
        virtio_rpmsg_remove(&dev);
    int expected_removals = which == PARENT_REGISTER_FAIL ? 0 : which == NORMAL_NS ? 2 : 1;
    failed = result != expected || allocs != frees || releases != 1 || removals != expected_removals;
    rt_kprintf("RPMSG_TEST %s %s ret=%d expected=%d alloc=%d free=%d remove=%d release=%d\n",
            name, failed ? "FAIL" : "PASS", result, expected, allocs, frees, removals, releases);
    /* Clean leaked allocations after a failing baseline, so tests are isolated. */
    for (int i = 0; i < 8; ++i)
        if (live[i])
            review_free(live[i]);
    return failed;
}

static int rpmsg_lifecycle_test(void)
{
    int failures = 0;
    (void)virtio_rpmsg_driver;
    failures += run_case(NS_ALLOC_FAIL, "ns_alloc_failure", -RT_ENOMEM);
    failures += run_case(NS_REGISTER_FAIL, "ns_register_failure", -RT_EINVAL);
    failures += run_case(PARENT_REGISTER_FAIL, "parent_register_failure", -RT_EINVAL);
    failures += run_case(NORMAL_NS, "normal_remove_ns", RT_EOK);
    failures += run_case(NORMAL_NO_NS, "normal_remove_no_ns", RT_EOK);
    rt_kprintf("RPMSG_TEST SUMMARY %d/5 passed\n", 5 - failures);
    return failures ? -RT_ERROR : RT_EOK;
}
MSH_CMD_EXPORT(rpmsg_lifecycle_test, Test RPMsg lifecycle with injected dependency failures);

]

当前拉取/合并请求的状态 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:

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

@github-actions

github-actions Bot commented Nov 2, 2026

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/virtio-rpmsg-release
    Enter PR branch fix/virtio-rpmsg-release 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/virtio-rpmsg-release 分支,关联的 Pull Request 也会同步更新。
Once completed, commits will be pushed to the fix/virtio-rpmsg-release 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

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

📌 Code Review Assignment

🏷️ Tag: components

Reviewers: @Maihuanyi

Changed Files (Click to expand)
  • components/drivers/virtio/virtio-rpmsg.c

📊 Current Review Status (Last Updated: 2026-11-02 11:42 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.

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