Skip to content

include: util: DIV_ROUND_UP and DIV_ROUND_CLOSEST accept division by zero #95302

@LucasRibeiro-Zuhlke

Description

@LucasRibeiro-Zuhlke

Describe the bug

On file include/zephyr/sys/util.h:

#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
...
#define DIV_ROUND_CLOSEST(n, d)
...
  • If zero is passed as denominator, undefined behavior will follow with these
    preprocessor macros:

For DIV_ROUND_UP only:

  • If there's an overflow when doing (n + d), wrong values will be returned;
  • Using negative operands returns wrong values, as it should round up towards
    positive infinity.

These macros are used extensively on Zephyr code, but I'm not sure if there's any
way to pass a zero as denominator when used, or if wrong calculations are being
made:

$ grep -RI DIV_ROUND_UP | wc -l
294
$ grep -RI DIV_ROUND_CLOSEST
43

The user might face issues if they use it in their application:

* Misc utilities usable by the kernel and application code.

Regression

  • This is a regression.

Steps to reproduce

No response

Relevant log output

Impact

Not sure

Environment

No response

Additional Context

No response

Metadata

Metadata

Labels

area: Base OSBase OS Library (lib/os)bugThe issue is a bug, or the PR is fixing a bugpriority: mediumMedium impact/importance bug

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions