Skip to content

fix(netdev): avoid division by zero in ping statistics when all packets lost - #11862

Open
ymj0440 wants to merge 2 commits into
RT-Thread:masterfrom
ymj0440:fix-netdev-ping-div-zero
Open

ymj0440 wants to merge 2 commits into
RT-Thread:masterfrom
ymj0440:fix-netdev-ping-div-zero

Conversation

@ymj0440

@ymj0440 ymj0440 commented Oct 11, 2026

Copy link
Copy Markdown

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

[

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

netdev_cmd_ping() computes avg_time = avg_time / received when printing ping statistics without checking that received is non-zero. When every ping attempt times out (target unreachable, the most common diagnostic scenario), received stays 0 and the integer division faults: SIGFPE on x86 and division-by-zero HardFault on Cortex-M, which kills the shell thread.

Fixes #11852

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

Move the avg_time / received computation inside the existing if (received > 0) guard so the division is never executed when no reply was received. Statistics still print 100% packet loss without min/max/avg values, matching the expected behavior described in #11852.

Verified on bsp/simulator with a test netdev whose ping op always returns -RT_ETIMEOUT:

  • before the fix: AddressSanitizer reports FPE (division by zero), process crashes
  • after the fix: 4 packets transmitted, 0 received, 100% packet loss, no crash

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

  • BSP: bsp/simulator

  • .config: N/A (no configuration change)

  • action: local build with scons -j4 on bsp/simulator (Linux x86-64) passed; RT-Thread CI will run on this PR after creation.

]

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

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

  • 本拉取/合并请求是一个成熟版本 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

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-netdev-ping-div-zero
    Enter PR branch fix-netdev-ping-div-zero 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-netdev-ping-div-zero 分支,关联的 Pull Request 也会同步更新。
Once completed, commits will be pushed to the fix-netdev-ping-div-zero 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 Oct 11, 2026 •

Copy link
Copy Markdown

📌 Code Review Assignment

🏷️ Tag: components

Reviewers: @Maihuanyi

Changed Files (Click to expand)
  • components/net/netdev/src/netdev.c

📊 Current Review Status (Last Updated: 2026-10-12 20:47 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.

@CLAassistant

CLAassistant commented Oct 11, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@CXSforHPU

Copy link
Copy Markdown
Contributor

关于本文件中,1372行for循环中

    for (index = 0; index < times; index++)
    {
        int delay_tick = 0;
        rt_tick_t start_tick = 0;

        rt_memset(&ping_resp, 0x00, sizeof(struct netdev_ping_resp));
        start_tick = rt_tick_get();
        ret = netdev->ops->ping(netdev, (const char *)target_name, size, NETDEV_PING_RECV_TIMEO, &ping_resp, isbind);
        if (ret == -RT_ETIMEOUT)
        {
            rt_kprintf("ping: from %s icmp_seq=%d timeout\n",
                (ip_addr_isany(&(ping_resp.ip_addr))) ? target_name : inet_ntoa(ping_resp.ip_addr), index + 1);
        }
        else if (ret == -RT_ERROR)
        {
            rt_kprintf("ping: unknown %s %s\n",
                (ip_addr_isany(&(ping_resp.ip_addr))) ? "host" : "address",
                    (ip_addr_isany(&(ping_resp.ip_addr))) ? target_name : inet_ntoa(ping_resp.ip_addr));
        }
        else
        {
            if (ping_resp.ttl == 0)
            {
                rt_kprintf("%d bytes from %s icmp_seq=%d time=%d ms\n",
                            ping_resp.data_len, inet_ntoa(ping_resp.ip_addr), index + 1, ping_resp.ticks);
            }
            else
            {
                rt_kprintf("%d bytes from %s icmp_seq=%d ttl=%d time=%d ms\n",
                            ping_resp.data_len, inet_ntoa(ping_resp.ip_addr), index + 1, ping_resp.ttl, ping_resp.ticks);
            }
            received += 1;
            if (ping_resp.ticks > max_time)
            {
                max_time = ping_resp.ticks;
            }
            else if (ping_resp.ticks < min_time)
            {
                min_time = ping_resp.ticks;
            }
            avg_time += ping_resp.ticks;
        }

        /* if the response time is more than NETDEV_PING_DELAY, no need to delay */
        delay_tick = ((rt_tick_get() - start_tick) > NETDEV_PING_DELAY) || (index == times) ? 0 : NETDEV_PING_DELAY;
        rt_thread_delay(delay_tick);
    }

第1416行代码:

        delay_tick = ((rt_tick_get() - start_tick) > NETDEV_PING_DELAY) || (index == times) ? 0 : NETDEV_PING_DELAY;

其目的是最后一次ping就不需要再补齐时间delay。其中 index是严格小于times的为永假条件。且当delay_tick为0时会进入rt_thread_delay(0)函数,并被返回非法参数 -RT_EINVAL。对这两个问题提出以下修复方案

    for (index = 0; index < times; index++)
    {
        rt_tick_t start_tick = 0,cost_tick = 0,delay_tick = 0;

        rt_memset(&ping_resp, 0x00, sizeof(struct netdev_ping_resp));
        start_tick = rt_tick_get();
        ret = netdev->ops->ping(netdev, (const char *)target_name, size, NETDEV_PING_RECV_TIMEO, &ping_resp, isbind);
        if (ret == -RT_ETIMEOUT)
        {
            rt_kprintf("ping: from %s icmp_seq=%d timeout\n",
                (ip_addr_isany(&(ping_resp.ip_addr))) ? target_name : inet_ntoa(ping_resp.ip_addr), index + 1);
        }
        else if (ret == -RT_ERROR)
        {
            rt_kprintf("ping: unknown %s %s\n",
                (ip_addr_isany(&(ping_resp.ip_addr))) ? "host" : "address",
                    (ip_addr_isany(&(ping_resp.ip_addr))) ? target_name : inet_ntoa(ping_resp.ip_addr));
        }
        else
        {
            if (ping_resp.ttl == 0)
            {
                rt_kprintf("%d bytes from %s icmp_seq=%d time=%d ms\n",
                            ping_resp.data_len, inet_ntoa(ping_resp.ip_addr), index + 1, ping_resp.ticks);
            }
            else
            {
                rt_kprintf("%d bytes from %s icmp_seq=%d ttl=%d time=%d ms\n",
                            ping_resp.data_len, inet_ntoa(ping_resp.ip_addr), index + 1, ping_resp.ttl, ping_resp.ticks);
            }
            received += 1;
            if (ping_resp.ticks > max_time)
            {
                max_time = ping_resp.ticks;
            }
            else if (ping_resp.ticks < min_time)
            {
                min_time = ping_resp.ticks;
            }
            avg_time += ping_resp.ticks;
        }

        /* if the response time is more than NETDEV_PING_DELAY, no need to delay */
        cost_tick = rt_tick_get() - start_tick;
        if (index != times - 1)
        {
            if (cost_tick < NETDEV_PING_DELAY)
            {
                delay_tick = NETDEV_PING_DELAY - cost_tick;
            }
        }

        if(delay_tick > 0)
        {
            rt_thread_delay(delay_tick);
        }
    }

@CXSforHPU

Copy link
Copy Markdown
Contributor

在本pr中是否合适一并修改

…read_delay(0)

The 'index == times' condition in the delay_tick calculation is never true,
so the delay was still applied after the last ping, contrary to the comment.
Skip the delay on the final ping by checking 'index != times - 1'.

Also only call rt_thread_delay() when delay_tick > 0, since passing 0
returns -RT_EINVAL.
@ymj0440

ymj0440 commented Oct 12, 2026

Copy link
Copy Markdown
Author

@CXSforHPU 非常感谢您的建议!已按您指出的两个问题一并修复并推送:

  1. 最后一次 ping 不再补 delay:原 index == times 永假,导致最后一条也会被 delay;现改用 index != times - 1 判断,最后一次不补时延。
  2. 避免 rt_thread_delay(0):改为 delay_tick > 0 时才调用 rt_thread_delay(),不再传入 0 触发 -RT_EINVAL。

修复位于 components/net/netdev/src/netdev.c,commit f241103c(在除零修复 dfc25cff 之后追加)。已编译链接验证通过,请再帮忙 review,谢谢!

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.

[Bug] [netdev] ping crashes the shell with a division by zero when the target is unreachable (received == 0)

3 participants