Skip to content

Commit

Permalink
Merge pull request #8019 from WalterBright/fix18597
Browse files Browse the repository at this point in the history
fix Issue 18597 - more unsafe unaligned pointer errors
merged-on-behalf-of: Mike Franklin <JinShil@users.noreply.github.com>
  • Loading branch information
dlang-bot committed Mar 23, 2018
2 parents ad598ec + 3afbfb2 commit a0764d9
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/dmd/dstruct.d
Expand Up @@ -479,6 +479,19 @@ extern (C++) class StructDeclaration : AggregateDeclaration
Type origType = t;
Type tb = t.toBasetype();

const hasPointers = tb.hasPointers();
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
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
@@ -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 };
}

0 comments on commit a0764d9

Please sign in to comment.