Skip to content

NonZero constructor in debug-builds should assert input is actually nonzero. #31217

Closed
@pnkfelix

Description

@pnkfelix

NonZero constructor in debug-builds should assert input is actually nonzero.

In particular, I am a bit concerned by the somewhat free-wheeling way that we are adding uses of the unsafe NonZero::new constructor function without any checks that the given input actually is non-zero.

I freely admit that I do not have many examples of current bugs that such a check would have prevented. However, I can point to some questionable code in a previous iteration of the libstd btree code that such a check would have at least caught: prior to PR #30426, the btree node.rs code had this line:

self.keys = unsafe { Unique::new(ptr::null_mut()) };

Was this a bug? Well, ... according to the invariants of Unique and NonZero, the keys.is_null() check should in principle be optimizable to be "always false", right?

  • The assignment occurs at the end of a drop method implementation, but the struct in question was marked #[unsafe_no_drop_flag], and so that drop code can (and will) be run repeatedly, so that keys.is_null() call can well occur in a context where the data is in a "bad state"
  • (indeed, the whole point of the keys.is_null() check is to catch the null being used as a sentinel value, even though it is in fact illegal in that context.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions