llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Absurdly big structs get wrong sizeof

Open Sir-Walrus opened this issue 3 years ago • 5 comments

struct a {
    char x[1ull<<60];
    char x2[1ull<<60];
};
a z[1];
long long x() { return sizeof(a); }
long long x2() { return sizeof(a::x); }
long long x3() { return sizeof(a::x2); }
long long x4() { return sizeof(z); }
x():                                  # @x()
        movabs  rax, 1152921504606846976
        ret
x2():                                 # @x2()
        movabs  rax, 1152921504606846976
        ret
x3():                                 # @x3()
        movabs  rax, 1152921504606846976
        ret
x4():                                 # @x4()
        movabs  rax, 1152921504606846976
        ret
z:
        .zero   1

https://godbolt.org/z/5GMber5GM

Certainly sizeof a struct isn't allowed to be less than the sum of its members (unless some members are empty structs with [[no_unique_address]])?

And certainly z should be assigned a .zero equal to its sizeof?

(Correct behavior would be erroring out if a struct goes anywhere near 2**60 bytes. Such structs have zero usecases other than breaking things.)

Sir-Walrus avatar Jan 24 '23 22:01 Sir-Walrus

@llvm/issue-subscribers-clang-frontend

llvmbot avatar Jan 24 '23 22:01 llvmbot

Oversized structs can yield additional absurdities on 32bit targets, for example objects with sizeof being (size_t)(1ull<<32) aka 0, an oversized .zero directive, or improper plurals in error messages. https://godbolt.org/z/c3c55xonr

struct a {
    char x[1u<<31];
    char x2[1u<<31];
};
a s;
// a s2[1]; // error: array is too large (1 elements)
bool h() { return sizeof(a) == 0; }
h():                                  # @h()
        li      a0, 1
        ret
s:
        .zero   4294967296

https://godbolt.org/z/bd547vj4Y

I could file "1 elements" as a separate bug, but the real fix is banning the guilty struct, and I'm not sure if typos in should-be-unreachable error messages are bugs.

Sir-Walrus avatar Jan 24 '23 23:01 Sir-Walrus

This issue comes because of when we iterate over struct fields, We track of fieldOffsets and Current DataSize/Size in bits.. So, (2305843009213693952 * 8) overflows and Wraps to 0. clang/lib/AST/RecordLayoutBuilder.cpp @Shafik Any suggestion? Can we use APInt instead of uint64_t?

Edit : We also need to fix this in llvm::backend so it emits correct value for .zero

Long5hot avatar Mar 03 '24 10:03 Long5hot

Changing such a fundamental piece to bigint would probably have performance implications.

The easiest fix would be simply error out for those inputs. It's not like such structs can be created in practice.

Sir-Walrus avatar Mar 03 '24 11:03 Sir-Walrus

Closing the issue, since the fix to emit error is committed.

xgupta avatar Jul 07 '26 08:07 xgupta