diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -11588,7 +11588,9 @@ def err_hlsl_numthreads_invalid : Error<"total number of threads cannot exceed %0">; def err_hlsl_attribute_param_mismatch : Error<"%0 attribute parameters do not match the previous declaration">; -// Layout randomization warning. +// Layout randomization diagnostics. +def err_non_designated_init_used : Error< + "a randomized struct can only be initialized with a designated initializer">; def err_cast_from_randomized_struct : Error< "casting from randomized structure pointer type %0 to %1">; } // end of sema component. diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp --- a/clang/lib/Sema/SemaInit.cpp +++ b/clang/lib/Sema/SemaInit.cpp @@ -2176,6 +2176,27 @@ break; } + // Check if this is an initializer of forms: + // + // struct foo f = {}; + // struct foo g = {0}; + // + // These are okay for randomized structures. [C99 6.7.8p19] + auto IsZeroInitializer = [&](const Expr *I) { + if (IList->getNumInits() == 1) + if (const auto *IL = dyn_cast(I)) + return IL->getValue().isZero(); + return false; + }; + + // Don't allow non-designated initializers on randomized structures. + if (RD->isRandomized() && !IsZeroInitializer(Init)) { + if (!VerifyOnly) + SemaRef.Diag(InitLoc, diag::err_non_designated_init_used); + hadError = true; + break; + } + // We've already initialized a member of a union. We're done. if (InitializedSomething && DeclType->isUnionType()) break; diff --git a/clang/test/Sema/init-randomized-struct.c b/clang/test/Sema/init-randomized-struct.c new file mode 100644 --- /dev/null +++ b/clang/test/Sema/init-randomized-struct.c @@ -0,0 +1,34 @@ +// RUN: %clang_cc1 %s -verify -fsyntax-only -frandomize-layout-seed=1234567890abcdef + +typedef void (*func_ptr)(); + +void foo(void); +void bar(void); +void baz(void); +void gaz(void); + +struct test { + func_ptr a; + func_ptr b; + func_ptr c; + func_ptr d; + func_ptr e; + func_ptr f; + func_ptr g; +} __attribute__((randomize_layout)); + +struct test t1 = {}; // This should be fine per WG14 N2900 (in C23) + our extension handling of it in earlier modes +struct test t2 = {0}; // This should also be fine per C99 6.7.8p19 + +struct test t3 = { .a = foo, bar, baz }; // expected-error {{a randomized struct can only be initialized with a designated initializer}} + +struct other_test { + func_ptr a; + func_ptr b[3]; + func_ptr c; +} __attribute__((randomize_layout)); + +struct other_test t4 = { .a = foo, .b[0] = foo }; // Ok +struct other_test t5 = { .a = foo, .b[0] = foo, bar, baz }; // Ok +struct other_test t7 = { .a = foo, .b = { foo, bar, baz } }; // Ok +struct other_test t6 = { .a = foo, .b[0] = foo, bar, baz, gaz }; // expected-error {{a randomized struct can only be initialized with a designated initializer}}