Skip to content

Commit

Permalink
Fix Bugzilla 24630 - Casting a bool pointer to a mutable pointer type…
Browse files Browse the repository at this point in the history
… is unsafe
  • Loading branch information
ntrel authored and dlang-bot committed Jun 25, 2024
1 parent b7c32d3 commit 5058aa9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
4 changes: 4 additions & 0 deletions compiler/src/dmd/safe.d
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@ bool isSafeCast(Expression e, Type tfrom, Type tto, ref string msg)
// Runtime array cast reinterprets data
if (ttobn.ty == Tbool && tfromn.ty != Tbool && e.op != EXP.arrayLiteral)
msg = "Source element may have bytes which are not 0 or 1";
// Can't alias a bool pointer with a non-bool pointer
if (ttobn.ty != Tbool && tfromn.ty == Tbool && ttobn.isMutable() &&
e.op != EXP.arrayLiteral)
msg = "Target element could be assigned a byte which is not 0 or 1";

// If the struct is opaque we don't know about the struct members then the cast becomes unsafe
if (ttobn.ty == Tstruct && !(cast(TypeStruct)ttobn).sym.members)
Expand Down
16 changes: 11 additions & 5 deletions compiler/test/fail_compilation/bool_cast.d
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@
REQUIRED_ARGS: -de -preview=dip1000
TEST_OUTPUT:
---
fail_compilation/bool_cast.d(15): Deprecation: cast from `ubyte[]` to `bool[]` not allowed in safe code
fail_compilation/bool_cast.d(15): Source element may have bytes which are not 0 or 1
fail_compilation/bool_cast.d(19): Deprecation: cast from `int*` to `bool*` not allowed in safe code
fail_compilation/bool_cast.d(19): Source element may have bytes which are not 0 or 1
fail_compilation/bool_cast.d(17): Deprecation: cast from `ubyte[]` to `bool[]` not allowed in safe code
fail_compilation/bool_cast.d(17): Source element may have bytes which are not 0 or 1
fail_compilation/bool_cast.d(22): Deprecation: cast from `int*` to `bool*` not allowed in safe code
fail_compilation/bool_cast.d(22): Source element may have bytes which are not 0 or 1
fail_compilation/bool_cast.d(24): Deprecation: cast from `bool*` to `byte*` not allowed in safe code
fail_compilation/bool_cast.d(24): Target element could be assigned a byte which is not 0 or 1
---
*/

void main() @safe
{
ubyte[] a = [2, 4];
auto b = cast(bool[]) a; // reinterprets a's data
auto c = cast(bool[]) [2, 4]; // literal cast applies to each element
auto c = cast(bool[]) [2, 4]; // OK, literal cast applies to each element
auto d = cast(const(byte)[]) b; // OK, result's elements are const

int i = 2;
auto p = cast(bool*) &i;
bool v;
auto bp = cast(byte*) &v;
*bp = 2; // v is now invalid
}

0 comments on commit 5058aa9

Please sign in to comment.