1 //===- unittest/AST/RandstructTest.cpp ------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains tests for Clang's structure field layout randomization. 10 // 11 //===----------------------------------------------------------------------===// 12 13 /* 14 * Build this test suite by running `make ASTTests` in the build folder. 15 * 16 * Run this test suite by running the following in the build folder: 17 * ` ./tools/clang/unittests/AST/ASTTests 18 * --gtest_filter=StructureLayoutRandomization*` 19 */ 20 21 #include "clang/AST/Randstruct.h" 22 #include "gtest/gtest.h" 23 24 #include "DeclMatcher.h" 25 #include "clang/AST/RecordLayout.h" 26 #include "clang/ASTMatchers/ASTMatchers.h" 27 #include "clang/Frontend/ASTUnit.h" 28 #include "clang/Testing/CommandLineArgs.h" 29 #include "clang/Tooling/Tooling.h" 30 31 #include <vector> 32 33 using namespace clang; 34 using namespace clang::ast_matchers; 35 using namespace clang::randstruct; 36 37 using field_names = std::vector<std::string>; 38 39 static std::unique_ptr<ASTUnit> makeAST(const std::string &SourceCode) { 40 std::vector<std::string> Args = getCommandLineArgsForTesting(Lang_C99); 41 Args.push_back("-frandomize-layout-seed=1234567890abcdef"); 42 43 IgnoringDiagConsumer IgnoringConsumer = IgnoringDiagConsumer(); 44 45 return tooling::buildASTFromCodeWithArgs( 46 SourceCode, Args, "input.c", "clang-tool", 47 std::make_shared<PCHContainerOperations>(), 48 tooling::getClangStripDependencyFileAdjuster(), 49 tooling::FileContentMappings(), &IgnoringConsumer); 50 } 51 52 static RecordDecl *getRecordDeclFromAST(const ASTContext &C, 53 const std::string &Name) { 54 RecordDecl *RD = FirstDeclMatcher<RecordDecl>().match( 55 C.getTranslationUnitDecl(), recordDecl(hasName(Name))); 56 return RD; 57 } 58 59 static std::vector<std::string> getFieldNamesFromRecord(const RecordDecl *RD) { 60 std::vector<std::string> Fields; 61 62 Fields.reserve(8); 63 for (auto *Field : RD->fields()) 64 Fields.push_back(Field->getNameAsString()); 65 66 return Fields; 67 } 68 69 static bool isSubsequence(const field_names &Seq, const field_names &Subseq) { 70 unsigned SeqLen = Seq.size(); 71 unsigned SubLen = Subseq.size(); 72 73 bool IsSubseq = false; 74 for (unsigned I = 0; I < SeqLen; ++I) 75 if (Seq[I] == Subseq[0]) { 76 IsSubseq = true; 77 for (unsigned J = 0; J + I < SeqLen && J < SubLen; ++J) { 78 if (Seq[J + I] != Subseq[J]) { 79 IsSubseq = false; 80 break; 81 } 82 } 83 } 84 85 return IsSubseq; 86 } 87 88 namespace clang { 89 namespace ast_matchers { 90 91 #define RANDSTRUCT_TEST_SUITE_TEST StructureLayoutRandomizationTestSuiteTest 92 93 TEST(RANDSTRUCT_TEST_SUITE_TEST, CanDetermineIfSubsequenceExists) { 94 const field_names Seq = {"a", "b", "c", "d"}; 95 96 EXPECT_TRUE(isSubsequence(Seq, {"b", "c"})); 97 EXPECT_TRUE(isSubsequence(Seq, {"a", "b", "c", "d"})); 98 EXPECT_TRUE(isSubsequence(Seq, {"b", "c", "d"})); 99 EXPECT_TRUE(isSubsequence(Seq, {"a"})); 100 EXPECT_FALSE(isSubsequence(Seq, {"a", "d"})); 101 } 102 103 #define RANDSTRUCT_TEST StructureLayoutRandomization 104 105 TEST(RANDSTRUCT_TEST, UnmarkedStruct) { 106 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 107 struct test { 108 int bacon; 109 long lettuce; 110 long long tomato; 111 float mayonnaise; 112 }; 113 )c"); 114 115 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 116 117 const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test"); 118 119 EXPECT_FALSE(RD->hasAttr<RandomizeLayoutAttr>()); 120 EXPECT_FALSE(RD->isRandomized()); 121 } 122 123 TEST(RANDSTRUCT_TEST, MarkedNoRandomize) { 124 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 125 struct test { 126 int bacon; 127 long lettuce; 128 long long tomato; 129 float mayonnaise; 130 } __attribute__((no_randomize_layout)); 131 )c"); 132 133 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 134 135 const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test"); 136 137 EXPECT_TRUE(RD->hasAttr<NoRandomizeLayoutAttr>()); 138 EXPECT_FALSE(RD->isRandomized()); 139 } 140 141 TEST(RANDSTRUCT_TEST, MarkedRandomize) { 142 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 143 struct test { 144 int bacon; 145 long lettuce; 146 long long tomato; 147 float mayonnaise; 148 } __attribute__((randomize_layout)); 149 )c"); 150 151 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 152 153 const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test"); 154 155 EXPECT_TRUE(RD->hasAttr<RandomizeLayoutAttr>()); 156 EXPECT_TRUE(RD->isRandomized()); 157 } 158 159 TEST(RANDSTRUCT_TEST, MismatchedAttrsDeclVsDef) { 160 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 161 struct test __attribute__((randomize_layout)); 162 struct test { 163 int bacon; 164 long lettuce; 165 long long tomato; 166 float mayonnaise; 167 } __attribute__((no_randomize_layout)); 168 )c"); 169 170 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 171 172 DiagnosticsEngine &Diags = AST->getDiagnostics(); 173 174 EXPECT_FALSE(Diags.hasFatalErrorOccurred()); 175 EXPECT_FALSE(Diags.hasUncompilableErrorOccurred()); 176 EXPECT_FALSE(Diags.hasUnrecoverableErrorOccurred()); 177 EXPECT_EQ(Diags.getNumWarnings(), 1u); 178 EXPECT_EQ(Diags.getNumErrors(), 0u); 179 } 180 181 TEST(RANDSTRUCT_TEST, MismatchedAttrsRandomizeVsNoRandomize) { 182 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 183 struct test2 { 184 int bacon; 185 long lettuce; 186 long long tomato; 187 float mayonnaise; 188 } __attribute__((randomize_layout)) __attribute__((no_randomize_layout)); 189 )c"); 190 191 EXPECT_TRUE(AST->getDiagnostics().hasErrorOccurred()); 192 193 DiagnosticsEngine &Diags = AST->getDiagnostics(); 194 195 EXPECT_TRUE(Diags.hasUncompilableErrorOccurred()); 196 EXPECT_TRUE(Diags.hasUnrecoverableErrorOccurred()); 197 EXPECT_EQ(Diags.getNumWarnings(), 0u); 198 EXPECT_EQ(Diags.getNumErrors(), 1u); 199 } 200 201 TEST(RANDSTRUCT_TEST, MismatchedAttrsNoRandomizeVsRandomize) { 202 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 203 struct test3 { 204 int bacon; 205 long lettuce; 206 long long tomato; 207 float mayonnaise; 208 } __attribute__((no_randomize_layout)) __attribute__((randomize_layout)); 209 )c"); 210 211 EXPECT_TRUE(AST->getDiagnostics().hasErrorOccurred()); 212 213 DiagnosticsEngine &Diags = AST->getDiagnostics(); 214 215 EXPECT_TRUE(Diags.hasUncompilableErrorOccurred()); 216 EXPECT_TRUE(Diags.hasUnrecoverableErrorOccurred()); 217 EXPECT_EQ(Diags.getNumWarnings(), 0u); 218 EXPECT_EQ(Diags.getNumErrors(), 1u); 219 } 220 221 TEST(RANDSTRUCT_TEST, CheckAdjacentBitfieldsRemainAdjacentAfterRandomization) { 222 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 223 struct test { 224 int a; 225 int b; 226 int x : 1; 227 int y : 1; 228 int z : 1; 229 int c; 230 } __attribute__((randomize_layout)); 231 )c"); 232 233 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 234 235 const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test"); 236 const field_names Actual = getFieldNamesFromRecord(RD); 237 const field_names Subseq = {"x", "y", "z"}; 238 239 EXPECT_TRUE(RD->isRandomized()); 240 EXPECT_TRUE(isSubsequence(Actual, Subseq)); 241 } 242 243 TEST(RANDSTRUCT_TEST, CheckVariableLengthArrayMemberRemainsAtEndOfStructure) { 244 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 245 struct test { 246 int a; 247 double b; 248 short c; 249 char name[]; 250 } __attribute__((randomize_layout)); 251 )c"); 252 253 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 254 255 const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test"); 256 257 EXPECT_TRUE(RD->isRandomized()); 258 } 259 260 TEST(RANDSTRUCT_TEST, RandstructDoesNotOverrideThePackedAttr) { 261 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 262 struct test_struct { 263 char a; 264 float b[3]; 265 short c; 266 int d; 267 } __attribute__((packed, randomize_layout)); 268 269 struct another_struct { 270 char a; 271 char b[5]; 272 int c; 273 } __attribute__((packed, randomize_layout)); 274 275 struct last_struct { 276 char a; 277 long long b; 278 int c[]; 279 } __attribute__((packed, randomize_layout)); 280 )c"); 281 282 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 283 284 // FIXME (?): calling getASTRecordLayout is probably a necessary evil so that 285 // Clang's RecordBuilders can actually flesh out the information like 286 // alignment, etc. 287 { 288 const RecordDecl *RD = 289 getRecordDeclFromAST(AST->getASTContext(), "test_struct"); 290 const ASTRecordLayout *Layout = 291 &AST->getASTContext().getASTRecordLayout(RD); 292 293 EXPECT_TRUE(RD->isRandomized()); 294 EXPECT_EQ(19, Layout->getSize().getQuantity()); 295 } 296 297 { 298 const RecordDecl *RD = 299 getRecordDeclFromAST(AST->getASTContext(), "another_struct"); 300 const ASTRecordLayout *Layout = 301 &AST->getASTContext().getASTRecordLayout(RD); 302 303 EXPECT_TRUE(RD->isRandomized()); 304 EXPECT_EQ(10, Layout->getSize().getQuantity()); 305 } 306 307 { 308 const RecordDecl *RD = 309 getRecordDeclFromAST(AST->getASTContext(), "last_struct"); 310 const ASTRecordLayout *Layout = 311 &AST->getASTContext().getASTRecordLayout(RD); 312 313 EXPECT_TRUE(RD->isRandomized()); 314 EXPECT_EQ(9, Layout->getSize().getQuantity()); 315 } 316 } 317 318 TEST(RANDSTRUCT_TEST, ZeroWidthBitfieldsSeparateAllocationUnits) { 319 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 320 struct test { 321 int a : 1; 322 int : 0; 323 int b : 1; 324 } __attribute__((randomize_layout)); 325 )c"); 326 327 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 328 329 const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test"); 330 331 EXPECT_TRUE(RD->isRandomized()); 332 } 333 334 TEST(RANDSTRUCT_TEST, RandstructDoesNotRandomizeUnionFieldOrder) { 335 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 336 union test_union { 337 int a; 338 int b; 339 int c; 340 int d; 341 int e; 342 int f; 343 } __attribute__((randomize_layout)); 344 )c"); 345 346 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 347 348 const RecordDecl *RD = 349 getRecordDeclFromAST(AST->getASTContext(), "test_union"); 350 351 EXPECT_FALSE(RD->isRandomized()); 352 } 353 354 TEST(RANDSTRUCT_TEST, AnonymousStructsAndUnionsRetainFieldOrder) { 355 const std::unique_ptr<ASTUnit> AST = makeAST(R"c( 356 struct test_struct { 357 int a; 358 struct sub_struct { 359 int b; 360 int c; 361 int d; 362 int e; 363 int f; 364 } __attribute__((randomize_layout)) s; 365 int f; 366 struct { 367 int g; 368 int h; 369 int i; 370 int j; 371 int k; 372 }; 373 int l; 374 union { 375 int m; 376 int n; 377 int o; 378 int p; 379 int q; 380 }; 381 int r; 382 } __attribute__((randomize_layout)); 383 )c"); 384 385 EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred()); 386 387 const RecordDecl *RD = 388 getRecordDeclFromAST(AST->getASTContext(), "test_struct"); 389 390 EXPECT_TRUE(RD->isRandomized()); 391 392 bool AnonStructTested = false; 393 bool AnonUnionTested = false; 394 395 for (const Decl *D : RD->decls()) 396 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 397 if (const auto *Record = FD->getType()->getAs<RecordType>()) { 398 RD = Record->getDecl(); 399 if (RD->isAnonymousStructOrUnion()) { 400 // These field orders shouldn't change. 401 if (RD->isUnion()) { 402 const field_names Expected = {"m", "n", "o", "p", "q"}; 403 404 EXPECT_EQ(Expected, getFieldNamesFromRecord(RD)); 405 AnonUnionTested = true; 406 } else { 407 const field_names Expected = {"g", "h", "i", "j", "k"}; 408 409 EXPECT_EQ(Expected, getFieldNamesFromRecord(RD)); 410 AnonStructTested = true; 411 } 412 } 413 } 414 } 415 416 EXPECT_TRUE(AnonStructTested); 417 EXPECT_TRUE(AnonUnionTested); 418 } 419 420 } // namespace ast_matchers 421 } // namespace clang 422