www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 15399] New: unaligned pointers are not safe

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

          Issue ID: 15399
           Summary: unaligned pointers are not  safe
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Keywords: accepts-invalid, safe
          Severity: major
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: thecybershadow gmail.com

This  safe program produces dangling GC pointers by storing the only references
to them in an unaligned struct field:

//////////////////////////////// test.d ////////////////////////////////
 safe:

struct Victim
{
    bool alive = true;
    ~this() { alive = false; }
}

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

pragma(msg, Unaligned.sizeof);

void main()
{
    enum N = 100;

    Unaligned[N] hosts;

    foreach (n; 0..N)
    {
        hosts[n].p = new Victim;
        assert(hosts[n].p.alive);
    }

    // Unaligned.p is invisible to the GC due to alignment

    void trustedCollect()  trusted { import core.memory; GC.collect(); }
    trustedCollect();

    foreach (n; 0..N)
        assert(hosts[n].p.alive); // Dangling pointer!
}
////////////////////////////////////////////////////////////////////////

--
Dec 02 2015