Issue 20482 - formatValue overlap detection does not account for nested anonymous unions
Summary: formatValue overlap detection does not account for nested anonymous unions
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P3 normal
Assignee: No Owner
URL:
Keywords: safe
Depends on:
Blocks:
 
Reported: 2020-01-05 13:19 UTC by Dennis
Modified: 2024-12-01 16:36 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Dennis 2020-01-05 13:19:42 UTC
The logic std.format uses for detecting overlap of anonymous unions is incorrect.
It looks at the difference in .offsetof for consecutive members in .tupleof, but doesn't account for nested unions.
```
import std;

struct S {
    union {
        struct {
            union {
                string a = "string a";
                long overlapsAlength;
            }
            string b = "string b";
        }   
        string[2] overlapsAandB;
    }
}

void main() @safe {
    S s;
    s.overlapsAlength = 32;
    writeln(s);
}
```

Prints:
S(#{overlap a, overlapsAlength}, "string b", ["string a\0string b\0%s\0/dlang/dmd-", "string b"])

It only detects the overlap of `a` and `overlapsAlength`, while `overlapsAandB` gets printed, resulting in memory corruption.

The example calls writeln on s, but writeln is simply a wrapper around formatValue which is at the heart of the issue:
```
    auto a = appender!string;
    auto f = singleSpec("%s");
    formatValue(a, s, f);
    writeln(a.data);
```

The specific logic can be found here:
https://github.com/dlang/phobos/blob/cc977c37b8fa7af5fc54bc64a6aad14714e5cf2d/std/format.d#L4411
Comment 1 Berni44 2021-04-21 18:03:17 UTC
IMHO, there is more about this: members of unions are only printed, if they are members of structs, but not stand alone unions. They are just formatted as their name.

I think, either, members of unions should always be printed (and then correctly) or not at all.
Comment 2 dlangBugzillaToGithub 2024-12-01 16:36:09 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/phobos/issues/9786

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB