Skip to content

Commit

Permalink
Fix Bugzilla 24631 - Pointer cast allows changing @System field in @safe
Browse files Browse the repository at this point in the history
 code
  • Loading branch information
ntrel authored and dlang-bot committed Jun 26, 2024
1 parent 5cfc340 commit 74618ab
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 9 deletions.
25 changes: 16 additions & 9 deletions compiler/src/dmd/safe.d
Original file line number Diff line number Diff line change
Expand Up @@ -231,15 +231,6 @@ bool isSafeCast(Expression e, Type tfrom, Type tto, ref string msg)
return false;
}

// For bool, only 0 and 1 are safe values
// 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 All @@ -252,6 +243,22 @@ bool isSafeCast(Expression e, Type tfrom, Type tto, ref string msg)
return false;
}

if (e.op != EXP.arrayLiteral)
{
// For bool, only 0 and 1 are safe values
// Runtime array cast reinterprets data
if (ttobn.ty == Tbool && tfromn.ty != Tbool)
msg = "Source element may have bytes which are not 0 or 1";
else if (ttobn.hasUnsafeBitpatterns())
msg = "Target element type has unsafe bit patterns";

// Can't alias a bool pointer with a non-bool pointer
if (ttobn.ty != Tbool && tfromn.ty == Tbool && ttobn.isMutable())
msg = "Target element could be assigned a byte which is not 0 or 1";
else if (tfromn.hasUnsafeBitpatterns() && ttobn.isMutable())
msg = "Source element type has unsafe bit patterns and target element type is mutable";
}

const frompointers = tfromn.hasPointers();
const topointers = ttobn.hasPointers();

Expand Down
25 changes: 25 additions & 0 deletions compiler/test/fail_compilation/system_ptr_cast.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
REQUIRED_ARGS: -preview=dip1000 -de
TEST_OUTPUT:
---
fail_compilation/system_ptr_cast.d(20): Deprecation: cast from `S*` to `int*` not allowed in safe code
fail_compilation/system_ptr_cast.d(20): Source element type has unsafe bit patterns and target element type is mutable
fail_compilation/system_ptr_cast.d(24): Deprecation: cast from `int*` to `S*` not allowed in safe code
fail_compilation/system_ptr_cast.d(24): Target element type has unsafe bit patterns
---
*/

struct S
{
@system int i;
}

void main() @safe
{
S s;
auto p = cast(int*) &s;
*p = 8;

int i = 8;
auto ps = cast(S*) &i;
}

0 comments on commit 74618ab

Please sign in to comment.