Skip to content

Commit 1731e3a

Browse files
committed
Add warning when union has randomize_layout attr
1 parent fe25c0e commit 1731e3a

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

clang/include/clang/Basic/DiagnosticASTKinds.td

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,4 +343,6 @@ def warn_padded_struct_size : Warning<
343343
InGroup<Padded>, DefaultIgnore;
344344
def warn_unnecessary_packed : Warning<
345345
"packed attribute is unnecessary for %0">, InGroup<Packed>, DefaultIgnore;
346+
def warn_randomize_attr_union : Warning<
347+
"union declared with 'randomize_layout' attribute">, InGroup<DiagGroup<"randomize-layout">>;
346348
}

clang/lib/AST/RecordLayoutBuilder.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2989,10 +2989,16 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const {
29892989
const ASTRecordLayout *NewEntry = nullptr;
29902990

29912991
bool ShouldBeRandomized = D->getAttr<RandomizeLayoutAttr>() != nullptr;
2992-
2993-
if (ShouldBeRandomized && !D->isUnion()) {
2994-
Randstruct randstruct;
2995-
randstruct.reorganizeFields(*this,D);
2992+
if (ShouldBeRandomized) {
2993+
// There is no technical benefit to randomizing the fields of a union
2994+
// since they all share the same offset of zero.
2995+
if (D->isUnion()) {
2996+
getDiagnostics().Report(D->getLocation(), diag::warn_randomize_attr_union);
2997+
}
2998+
else {
2999+
Randstruct randstruct;
3000+
randstruct.reorganizeFields(*this,D);
3001+
}
29963002
}
29973003

29983004
if (isMsLayout(*this)) {

0 commit comments

Comments
 (0)