Skip to content

add safety checks for pointer casting #2414

@andrewrk

Description

@andrewrk

I'm excited about this one. This connects a lot of dots and is part of the unofficial Make The Safe Build Modes More Safe project (#2301).

Here are some of the features of Zig this depends on:

  • there is no such thing as zero initialization
  • all values must be explicitly initialized (but initialization to undefined is OK)
  • most types (e.g. non-packed non-extern structs) intentionally have no well-defined in-memory layout

The proposal is to add a secret safety field to types which have no well-defined in-memory layout, similar to how unions have a secret safety tag field. The secret safety field has an integer which denotes the type id. A unique integer id will be generated for every type across an entire compilation.

Next, augment the rules about undefined values (see #1947) with this: in safe build modes, the bit pattern of undefined shall be 0xaa (repeating) across the store size of the type and for types which have no well-defined in-memory layout, the bit pattern 0xaa repeated across the store size shall not match a valid state.

This makes it possible to add safety checks to @ptrCast, @intToPtr, and @fieldParentPtr. It will be detectable illegal behavior (see #2402) if the actual element type does not match the target type specified in the cast, or if the memory has an undefined value.

Sometimes it is desired to @ptrCast or @intToPtr when you know the memory is undefined. For these cases we introduce @ptrCastUndef and @intToPtrUndef which simultaneously cast and assign undefined to the memory. These functions allow the programmer to change the type of memory in a legal way.

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    Status

    To do

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions