Skip to content

Limit static object sizes #18315

Open

Description

@dlangBugzillaToGithub

Andrei Alexandrescu (@andralex) reported this on 2010-11-05T17:38:13Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=5176

CC List

Description

Objects of very large size can corrupt memory when used via null pointers:

struct S {
    char raw[100_000];
}

S * s = null;

To avoid this, static object sizes should be limited to a value that guarantees hardware memory protection (e.g. 64KB).

Activity

  1. dlangBugzillaToGithub commented on Nov 6, 2010

    @dlangBugzillaToGithub
    Author

    bearophile_hugs commented on 2010-11-06T00:46:12Z

    Is this for @safe modules only?
    If the answer is negative, what's the way to override this limit? If I am writing a kernel using D, that's a system language, I may want to ignore this corruption problem.
  2. dlangBugzillaToGithub commented on Nov 6, 2010

    @dlangBugzillaToGithub
    Author

    nfxjfg commented on 2010-11-06T02:46:38Z

    64 KB ought to be enough for everyone.
  3. dlangBugzillaToGithub commented on Nov 6, 2010

    @dlangBugzillaToGithub
    Author

    andrei (@andralex) commented on 2010-11-06T06:43:55Z

    This change doesn't limit what can be done in a systems-level program.
  4. dlangBugzillaToGithub commented on Jun 16, 2011

    @dlangBugzillaToGithub
    Author

    yebblies commented on 2011-06-16T01:04:46Z

    *** Issue 3677 has been marked as a duplicate of this issue. ***
  5. dlangBugzillaToGithub commented on Jun 16, 2011

    @dlangBugzillaToGithub
    Author

    michel.fortin commented on 2011-06-16T03:23:20Z

    (In reply to comment #0)
    > To avoid this, static object sizes should be limited to a value that guarantees
    > hardware memory protection (e.g. 64KB).
    
    I think on OS X the size of that guaranty is significantly smaller, 4 Kb if I remember well. Is it reasonable to limit structs and objects to 4 Kb on OS X?
    
    Note that it's not only structs and objects. Types such as char[100_000]* also pose a risk.
  6. dlangBugzillaToGithub commented on Mar 18, 2012

    @dlangBugzillaToGithub
    Author

    andrei (@andralex) commented on 2012-03-18T10:03:05Z

    One possibility is to allow arbitrary sizes but have the compiler insert checks for all field accesses through pointer or reference when the field offset is beyond the OS's protected area.
  7. dlangBugzillaToGithub commented on Mar 18, 2012

    @dlangBugzillaToGithub
    Author

    code (@MartinNowak) commented on 2012-03-18T10:07:28Z

    In reply to comment #5)
    > I think on OS X the size of that guaranty is significantly smaller, 4 Kb if I
    > remember well. Is it reasonable to limit structs and objects to 4 Kb on OS X?
    
    Wouldn't it also be possible to additionally protect memory up to the desired @safe object size limit during application startup?
  8. dlangBugzillaToGithub commented on Mar 18, 2012

    @dlangBugzillaToGithub
    Author

    deadalnix commented on 2012-03-18T10:14:04Z

    What about int[1000000]* ? The problem is the same.
  9. dlangBugzillaToGithub commented on Mar 20, 2012

    @dlangBugzillaToGithub
    Author

    michel.fortin commented on 2012-03-20T04:14:52Z

    (In reply to comment #7)
    > Wouldn't it also be possible to additionally protect memory up to the desired
    > @safe object size limit during application startup?
    
    That'll work only if those pages are not used for anything. My guess is that if they're readable (writable?) it's because they're being used in some way, possibly by some system APIs.
  10. dlangBugzillaToGithub commented on Mar 20, 2012

    @dlangBugzillaToGithub
    Author

    michel.fortin commented on 2012-03-20T04:45:08Z

    (In reply to comment #6)
    > One possibility is to allow arbitrary sizes but have the compiler insert checks
    > for all field accesses through pointer or reference when the field offset is
    > beyond the OS's protected area.
    
    That'd work. It'd introduce uneven performance characteristics, but that could be the price to pay for safety. (To not pay this price we'd need statically-enforced non-nullable pointers.)
    
    On second thought, it needs a little tweak. Take this example:
    
    struct A {
      /* a lot of fields */
      int f; // offset is 3 Kb - 4 bytes
    }
    struct B {
      A a1; // field offset is 0
      A a2; // field offset is 3 Kb
    }
    
    int foo(ref A a) {
      return a.f; // offset is 3K-4, considered safe?
    }
    int bar(B * b) {
      return foo(b.a2); // offset is 3K, considered safe?
    }
    
    Here, if you call bar(null), it'll call foo() with address null + 3K. foo() will in turn add 3K-4 to the pointer, making it 6K-4 bytes, beyond the 4K protected range.
    
    What you need to take into account when deciding to insert the null check is not whether the offset is beyond the protected range, but whether the memory area of the field is entirely encompassed in the protected range. So you need to use field.offsetof+field.sizeof < 4K (or whatever the protected range is for a specific machine).
    
    Note that you also need to do this same check when taking the address of a field:
    
    B * baz() {
      return null;
    }
    void coz() {
      B * b = baz();
      A * a = &b.a2; // b.a2 spans on 3K..6K range, unsafe
      int f = a.f; // address of field is 6K-4
    }
  11. dlangBugzillaToGithub commented on Mar 20, 2012

    @dlangBugzillaToGithub
    Author

    deadalnix commented on 2012-03-20T04:50:47Z

    (In reply to comment #10)
    > (In reply to comment #6)
    > > One possibility is to allow arbitrary sizes but have the compiler insert checks
    > > for all field accesses through pointer or reference when the field offset is
    > > beyond the OS's protected area.
    > 
    > That'd work. It'd introduce uneven performance characteristics, but that could
    > be the price to pay for safety. (To not pay this price we'd need
    > statically-enforced non-nullable pointers.)
    > 
    > On second thought, it needs a little tweak. Take this example:
    > 
    > struct A {
    >   /* a lot of fields */
    >   int f; // offset is 3 Kb - 4 bytes
    > }
    > struct B {
    >   A a1; // field offset is 0
    >   A a2; // field offset is 3 Kb
    > }
    > 
    
    Classes are references types. So both a1.f and a2.f will have the same offset.
  12. dlangBugzillaToGithub commented on Mar 20, 2012

    @dlangBugzillaToGithub
    Author

    ricochet1k commented on 2012-03-20T13:55:38Z

    (In reply to comment #11)
    > Classes are references types. So both a1.f and a2.f will have the same offset.
    
    Those are structs, not classes.
  13. dlangBugzillaToGithub commented on Jan 9, 2013

    @dlangBugzillaToGithub
    Author

    hsteoh commented on 2013-01-09T17:21:29Z

    Very large structs can also corrupt memory not just via null references, but via stack overflow. (Just pass a large struct by value down a few levels of recursion, and the stack will overflow.) And it's easier than one might think:
    
    struct S {
      dchar[256] buffer;
    }
    
    Looks small, right? Well, sizeof(dchar)=4, which means sizeof(S)=1024. On Linux, the default stacksize is about 4KB. That means passing S by value down just 3-4 levels of recursion is enough to overflow the stack. And currently, I don't think DMD does any handling for stack overflow; it just crashes (and may corrupt memory as well, I didn't look into it).
  14. dlangBugzillaToGithub commented on Jan 9, 2013

    @dlangBugzillaToGithub
    Author

    deadalnix commented on 2013-01-09T17:41:47Z

    (In reply to comment #13)
    > Very large structs can also corrupt memory not just via null references, but
    > via stack overflow. (Just pass a large struct by value down a few levels of
    > recursion, and the stack will overflow.) And it's easier than one might think:
    > 
    > struct S {
    >   dchar[256] buffer;
    > }
    > 
    > Looks small, right? Well, sizeof(dchar)=4, which means sizeof(S)=1024. On
    > Linux, the default stacksize is about 4KB. That means passing S by value down
    > just 3-4 levels of recursion is enough to overflow the stack. And currently, I
    > don't think DMD does any handling for stack overflow; it just crashes (and may
    > corrupt memory as well, I didn't look into it).
    
    A page is reserved after the stack to detect it I think. It require to limit the size of what can be put on stack in a single operation. Or to add the checks that matter.
    
    But a better option IMO is to reserve an insane amount of memory space for fiber's stack (and then some page to be protected for stack overflow detection) and run everything within a fiber. This is not very 32 bits compliant, but can work really well on 64bits systems.
  15. dlangBugzillaToGithub commented on Jan 9, 2013

    @dlangBugzillaToGithub
    Author

    bearophile_hugs commented on 2013-01-09T18:30:05Z

    (In reply to comment #13)
    > Very large structs can also corrupt memory not just via null references, but
    > via stack overflow. (Just pass a large struct by value down a few levels of
    > recursion, and the stack will overflow.) And it's easier than one might think:
    > 
    > struct S {
    >   dchar[256] buffer;
    > }
    > 
    > Looks small, right? Well, sizeof(dchar)=4, which means sizeof(S)=1024. On
    > Linux, the default stacksize is about 4KB. That means passing S by value down
    > just 3-4 levels of recursion is enough to overflow the stack.
    
    A 1 kb struct should be considered very little for the stack. Generally it's a good idea to use the stack in D, because it avoids many slow heap allocations and decreases pressure on the GC.
    
    On a modern PC with 1 GB RAM a D programmer should be free to use 1-10 MB of RAM for the stack. On Windows there is a linker command to increase the stack size.
    
    
    > And currently, I
    > don't think DMD does any handling for stack overflow; it just crashes (and may
    > corrupt memory as well, I didn't look into it).
    
    DMD used to give a readable error message on Windows, but now programs just crash.
  16. 8 remaining items

  17. dlangBugzillaToGithub commented on Jan 10, 2013

    @dlangBugzillaToGithub
    Author

    doob (@jacob-carlborg) commented on 2013-01-10T10:14:47Z

    (In reply to comment #22)
    > How large are the guard pages on each OS?
    > 
    > We should either restrict object size to a reasonable maximum, or insert
    > runtime checks at least in @safe mode when accessing fields through pointers
    > that may be null.
    
    Perhaps doing something similar as with array bounds checking. Insert a check and provide a compiler flag to remove it. Or remove the check in -release builds.
  18. dlangBugzillaToGithub commented on Jan 10, 2013

    @dlangBugzillaToGithub
    Author

    hsteoh commented on 2013-01-10T11:46:07Z

    (In reply to comment #17)
    > Windows inserts a "guard page" that is hardware protected beyond the end of the
    > allocated stack. A stack overflow runs into that guard page, which throws a seg
    > fault.
    > 
    > It does not corrupt memory.
    
    Oh yes it does:
    
    http://d.puremagic.com/test-results/pull.ghtml?projectid=1&runid=448588
    
    (But I did make a mistake, it's not Linux that this happens on, but OSX/64.)
    
    For reference, this is the failing code (N.B. the last assert, compare with output in the autotester, you can see that garbage values are produced, I've traced this and found that it's caused by stack overflow):
    
    unittest
    {
        struct TransientRange
        {
            dchar[128] _buf;
            dstring[] _values;
            this(dstring[] values)
            {
                _values = values;
            }
            @property bool empty()
            {
                return _values.length == 0;
            }
            @property auto front()
            {
                foreach (i; 0 .. _values.front.length)
                {
                    _buf[i] = _values[0][i];
                }
                return _buf[0 .. _values.front.length];
            }
            void popFront()
            {
                _values = _values[1 .. $];
            }
        }
    
        auto rr = TransientRange(["abc"d, "12"d, "def"d, "34"d]);
    
        // Can't use array() or equal() directly because they fail with transient
        // .front.
        dchar[] result;
        foreach (c; rr.joiner()) {
            result ~= c;
        }
    
        assert(equal(result, "abc12def34"d),
            "Unexpected result: '%s'"d.format(result));
    }
  19. dlangBugzillaToGithub commented on Jan 10, 2013

    @dlangBugzillaToGithub
    Author

    bugzilla (@WalterBright) commented on 2013-01-10T12:03:50Z

    (In reply to comment #22)
    > How large are the guard pages on each OS?
    
    Usually 4k. But the function prologs, when creating a stack frame larger than 4k, will do "probes" for each 4k page. So, no, you can't corrupt memory with an overflow.
    
    > We should either restrict object size to a reasonable maximum, or insert
    > runtime checks at least in @safe mode when accessing fields through pointers
    > that may be null.
    
    There's a separate set of guard pages at address 0, to cause a seg fault if 1, 2, 3, etc. is accessed. I don't know how big they are.
  20. dlangBugzillaToGithub commented on Jan 10, 2013

    @dlangBugzillaToGithub
    Author

    bugzilla (@WalterBright) commented on 2013-01-10T12:08:12Z

    > Oh yes it does:
    
    You can test this with a far simpler program. Just write a function that calls itself and run it under the debugger.
  21. dlangBugzillaToGithub commented on May 20, 2013

    @dlangBugzillaToGithub
    Author

    sibaqexozequgaba commented on 2013-05-20T00:58:57Z

    Copying my comment from the forums so it won't get lost:
    (http://forum.dlang.org/post/[email protected])
    
    Isn't the solution as easy as doing:
    OR PTR:[address], 0
    the same way it's done for the stack?
    
    The offset it known at compile time in most cases, so the command 
    would be required only if both:
    * The object is larger than target OS' guard page size.
    * The position is greater than target OS' guard page size, OR is 
    unknown at compile time.
    
    Walter: "Not a bad idea." :)
  22. dlangBugzillaToGithub commented on May 20, 2013

    @dlangBugzillaToGithub
    Author

    deadalnix commented on 2013-05-20T01:07:53Z

    (In reply to comment #28)
    > Copying my comment from the forums so it won't get lost:
    > (http://forum.dlang.org/post/[email protected])
    > 
    > Isn't the solution as easy as doing:
    > OR PTR:[address], 0
    > the same way it's done for the stack?
    > 
    > The offset it known at compile time in most cases, so the command 
    > would be required only if both:
    > * The object is larger than target OS' guard page size.
    > * The position is greater than target OS' guard page size, OR is 
    > unknown at compile time.
    > 
    > Walter: "Not a bad idea." :)
    
    The thing is that you may get over the page protection by several dereferences. So you must check based not on the dereferenced address, but on the maximum addres that will be dereferenced (ie the end of the object).
    
    It means that every single reference taking on a 4kb+ object must have a check.
  23. dlangBugzillaToGithub commented on May 20, 2013

    @dlangBugzillaToGithub
    Author

    sibaqexozequgaba commented on 2013-05-20T01:13:22Z

    (In reply to comment #29)
    > The thing is that you may get over the page protection by several dereferences.
    
    What do you mean by several dereferences?
    Can you provide an example?
  24. dlangBugzillaToGithub commented on May 20, 2013

    @dlangBugzillaToGithub
    Author

    deadalnix commented on 2013-05-20T01:26:56Z

    (In reply to comment #30)
    > (In reply to comment #29)
    > > The thing is that you may get over the page protection by several dereferences.
    > 
    > What do you mean by several dereferences?
    > Can you provide an example?
    
    Yes sure. Let's consider the example below :
    
    struct Foo {
        ubyte[512] bar;
    }
    
    struct Buzz {
        ubyte[256] pad;
        Foo[8] qux;
    }
    
    Buzz* b;
    
    auto deref1 = (b.qux[7]); // deref below 4kb.
    deref1.bar[300]; // offset is bellow 4kb, but teh address is above 4kb.
    
    If we consider deref address only no check happens here. So it is needed to base the decision to check or not not based on the actual address, but according the the maximal address possibly reached.
    
    In other words, a 4kb+ conglomerate of value types need null check on every single pointer operation, even the on bellow 4kb.
  25. dlangBugzillaToGithub commented on May 20, 2013

    @dlangBugzillaToGithub
    Author

    sibaqexozequgaba commented on 2013-05-20T02:08:00Z

    (In reply to comment #31)
    > Yes sure. Let's consider the example below :
    > 
    > struct Foo {
    >     ubyte[512] bar;
    > }
    > 
    > struct Buzz {
    >     ubyte[256] pad;
    >     Foo[8] qux;
    > }
    > 
    > Buzz* b;
    > 
    > auto deref1 = (b.qux[7]); // deref below 4kb.
    > deref1.bar[300]; // offset is bellow 4kb, but teh address is above 4kb.
    > 
    > If we consider deref address only no check happens here. So it is needed to
    > base the decision to check or not not based on the actual address, but
    > according the the maximal address possibly reached.
    > 
    > In other words, a 4kb+ conglomerate of value types need null check on every
    > single pointer operation, even the on bellow 4kb.
    
    Your example is safe, as it will crash on the first dereference (value semantics).
    
    You probably meant something similar to:
    
    Buzz* b;
    
    auto deref1 = &(b.qux[7]); // take address below 4kb.
    deref1.bar[300] = 0; // offset is bellow 4kb, but the address is above 4kb.
    
    Maybe it's worth adding another case then, when both are true:
    * Taking an address of an object whose size is above OS' guard page (Buzz in the example).
    * The referenced object's last available byte offset is above OS' guard page (qux[7]'s last byte in the example).
  26. dlangBugzillaToGithub commented on May 20, 2013

    @dlangBugzillaToGithub
    Author

    andrei (@andralex) commented on 2013-05-20T05:34:03Z

    (In reply to comment #32)
    > Buzz* b;
    > 
    > auto deref1 = &(b.qux[7]); // take address below 4kb.
    > deref1.bar[300] = 0; // offset is bellow 4kb, but the address is above 4kb.
    
    This is a red herring. The null check is inserted not if the address of the field falls above the limit, but if the address of the field PLUS the size of the field does.
  27. dlangBugzillaToGithub commented on May 20, 2013

    @dlangBugzillaToGithub
    Author

    sibaqexozequgaba commented on 2013-05-20T06:03:10Z

    (In reply to comment #33)
    > (In reply to comment #32)
    > > Buzz* b;
    > > 
    > > auto deref1 = &(b.qux[7]); // take address below 4kb.
    > > deref1.bar[300] = 0; // offset is bellow 4kb, but the address is above 4kb.
    > 
    > This is a red herring. The null check is inserted not if the address of the
    > field falls above the limit, but if the address of the field PLUS the size of
    > the field does.
    
    That's what I meant by saying "The referenced object's last available byte".
  28. dlangBugzillaToGithub commented on May 20, 2013

    @dlangBugzillaToGithub
    Author

    andrei (@andralex) commented on 2013-05-20T06:05:16Z

    (In reply to comment #34)
    > (In reply to comment #33)
    > > (In reply to comment #32)
    > > > Buzz* b;
    > > > 
    > > > auto deref1 = &(b.qux[7]); // take address below 4kb.
    > > > deref1.bar[300] = 0; // offset is bellow 4kb, but the address is above 4kb.
    > > 
    > > This is a red herring. The null check is inserted not if the address of the
    > > field falls above the limit, but if the address of the field PLUS the size of
    > > the field does.
    > 
    > That's what I meant by saying "The referenced object's last available byte".
    
    Thanks, I replied to the wrong message. But I don't think that's a special case, the check should always work that way.
  29. dlangBugzillaToGithub commented on Apr 8, 2020

    @dlangBugzillaToGithub
    Author

    r.sagitario commented on 2020-04-08T05:30:50Z

    *** Issue 20725 has been marked as a duplicate of this issue. ***
  30. dlangBugzillaToGithub commented on Aug 6, 2024

    @dlangBugzillaToGithub
    Author

    razvan.nitu1305 commented on 2024-08-06T12:07:37Z

    *** Issue 24696 has been marked as a duplicate of this issue. ***
  31. added theissue type on Apr 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions