Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/dmd/dstruct.d
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,19 @@ extern (C++) class StructDeclaration : AggregateDeclaration
Type origType = t;
Type tb = t.toBasetype();

const hasPointers = tb.hasPointers();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems to me like this block would be big enough to put it into a function.
This would help preventing diverging error messages.

if (hasPointers)
{
if ((stype.alignment() < Target.ptrsize ||
(v.offset & (Target.ptrsize - 1))) &&
sc.func.setUnsafe())
{
.error(loc, "field `%s.%s` cannot assign to misaligned pointers in `@safe` code",
toChars(), v.toChars());
return false;
}
}

/* Look for case of initializing a static array with a too-short
* string literal, such as:
* char[5] foo = "abc";
Expand Down
12 changes: 12 additions & 0 deletions src/dmd/initsem.d
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import dmd.identifier;
import dmd.init;
import dmd.mtype;
import dmd.statement;
import dmd.target;
import dmd.tokens;
import dmd.visitor;

Expand Down Expand Up @@ -187,6 +188,17 @@ private extern(C++) final class InitializerSemanticVisitor : Visitor
errors = true;
continue;
}
if (vd.type.hasPointers)
{
if ((t.alignment() < Target.ptrsize ||
(vd.offset & (Target.ptrsize - 1))) &&
sc.func.setUnsafe())
{
error(i.loc, "field `%s.%s` cannot assign to misaligned pointers in `@safe` code",
sd.toChars(), vd.toChars());
errors = true;
}
}
for (size_t k = 0; k < nfields; k++)
{
VarDeclaration v2 = sd.fields[k];
Expand Down
27 changes: 27 additions & 0 deletions test/fail_compilation/test18597.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/* TEST_OUTPUT:
---
fail_compilation/test18597.d(24): Error: field `Unaligned.p` cannot modify misaligned pointers in `@safe` code
fail_compilation/test18597.d(25): Error: field `Unaligned.p` cannot assign to misaligned pointers in `@safe` code
fail_compilation/test18597.d(26): Error: field `Unaligned.p` cannot assign to misaligned pointers in `@safe` code
---
*/

// https://issues.dlang.org/show_bug.cgi?id=18597

@safe:

align(1)
struct Unaligned
{
align(1):
ubyte filler;
int* p;
}

void test()
{
Unaligned u;
u.p = new int;
Unaligned v = Unaligned(0, new int);
Unaligned w = { p : new int };
}