1 //===- ARMErrataFix.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 // This file implements Section Patching for the purpose of working around the 9 // Cortex-a8 erratum 657417 "A 32bit branch instruction that spans 2 4K regions 10 // can result in an incorrect instruction fetch or processor deadlock." The 11 // erratum affects all but r1p7, r2p5, r2p6, r3p1 and r3p2 revisions of the 12 // Cortex-A8. A high level description of the patching technique is given in 13 // the opening comment of AArch64ErrataFix.cpp. 14 //===----------------------------------------------------------------------===// 15 16 #include "ARMErrataFix.h" 17 18 #include "Config.h" 19 #include "LinkerScript.h" 20 #include "OutputSections.h" 21 #include "Relocations.h" 22 #include "Symbols.h" 23 #include "SyntheticSections.h" 24 #include "Target.h" 25 #include "lld/Common/Memory.h" 26 #include "lld/Common/Strings.h" 27 #include "llvm/Support/Endian.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include <algorithm> 30 31 using namespace llvm; 32 using namespace llvm::ELF; 33 using namespace llvm::object; 34 using namespace llvm::support; 35 using namespace llvm::support::endian; 36 37 namespace lld { 38 namespace elf { 39 40 // The documented title for Erratum 657417 is: 41 // "A 32bit branch instruction that spans two 4K regions can result in an 42 // incorrect instruction fetch or processor deadlock". Graphically using a 43 // 32-bit B.w instruction encoded as a pair of halfwords 0xf7fe 0xbfff 44 // xxxxxx000 // Memory region 1 start 45 // target: 46 // ... 47 // xxxxxxffe f7fe // First halfword of branch to target: 48 // xxxxxx000 // Memory region 2 start 49 // xxxxxx002 bfff // Second halfword of branch to target: 50 // 51 // The specific trigger conditions that can be detected at link time are: 52 // - There is a 32-bit Thumb-2 branch instruction with an address of the form 53 // xxxxxxFFE. The first 2 bytes of the instruction are in 4KiB region 1, the 54 // second 2 bytes are in region 2. 55 // - The branch instruction is one of BLX, BL, B.w BCC.w 56 // - The instruction preceding the branch is a 32-bit non-branch instruction. 57 // - The target of the branch is in region 1. 58 // 59 // The linker mitigation for the fix is to redirect any branch that meets the 60 // erratum conditions to a patch section containing a branch to the target. 61 // 62 // As adding patch sections may move branches onto region boundaries the patch 63 // must iterate until no more patches are added. 64 // 65 // Example, before: 66 // 00000FFA func: NOP.w // 32-bit Thumb function 67 // 00000FFE B.W func // 32-bit branch spanning 2 regions, dest in 1st. 68 // Example, after: 69 // 00000FFA func: NOP.w // 32-bit Thumb function 70 // 00000FFE B.w __CortexA8657417_00000FFE 71 // 00001002 2 - bytes padding 72 // 00001004 __CortexA8657417_00000FFE: B.w func 73 74 class Patch657417Section : public SyntheticSection { 75 public: 76 Patch657417Section(InputSection *p, uint64_t off, uint32_t instr, bool isARM); 77 78 void writeTo(uint8_t *buf) override; 79 80 size_t getSize() const override { return 4; } 81 82 // Get the virtual address of the branch instruction at patcheeOffset. 83 uint64_t getBranchAddr() const; 84 85 // The Section we are patching. 86 const InputSection *patchee; 87 // The offset of the instruction in the Patchee section we are patching. 88 uint64_t patcheeOffset; 89 // A label for the start of the Patch that we can use as a relocation target. 90 Symbol *patchSym; 91 // A decoding of the branch instruction at patcheeOffset. 92 uint32_t instr; 93 // True If the patch is to be written in ARM state, otherwise the patch will 94 // be written in Thumb state. 95 bool isARM; 96 }; 97 98 // Return true if the half-word, when taken as the first of a pair of halfwords 99 // is the first half of a 32-bit instruction. 100 // Reference from ARM Architecture Reference Manual ARMv7-A and ARMv7-R edition 101 // section A6.3: 32-bit Thumb instruction encoding 102 // | HW1 | HW2 | 103 // | 1 1 1 | op1 (2) | op2 (7) | x (4) |op| x (15) | 104 // With op1 == 0b00, a 16-bit instruction is encoded. 105 // 106 // We test only the first halfword, looking for op != 0b00. 107 static bool is32bitInstruction(uint16_t hw) { 108 return (hw & 0xe000) == 0xe000 && (hw & 0x1800) != 0x0000; 109 } 110 111 // Reference from ARM Architecture Reference Manual ARMv7-A and ARMv7-R edition 112 // section A6.3.4 Branches and miscellaneous control. 113 // | HW1 | HW2 | 114 // | 1 1 1 | 1 0 | op (7) | x (4) | 1 | op1 (3) | op2 (4) | imm8 (8) | 115 // op1 == 0x0 op != x111xxx | Conditional branch (Bcc.W) 116 // op1 == 0x1 | Branch (B.W) 117 // op1 == 1x0 | Branch with Link and Exchange (BLX.w) 118 // op1 == 1x1 | Branch with Link (BL.W) 119 120 static bool isBcc(uint32_t instr) { 121 return (instr & 0xf800d000) == 0xf0008000 && 122 (instr & 0x03800000) != 0x03800000; 123 } 124 125 static bool isB(uint32_t instr) { return (instr & 0xf800d000) == 0xf0009000; } 126 127 static bool isBLX(uint32_t instr) { return (instr & 0xf800d000) == 0xf000c000; } 128 129 static bool isBL(uint32_t instr) { return (instr & 0xf800d000) == 0xf000d000; } 130 131 static bool is32bitBranch(uint32_t instr) { 132 return isBcc(instr) || isB(instr) || isBL(instr) || isBLX(instr); 133 } 134 135 Patch657417Section::Patch657417Section(InputSection *p, uint64_t off, 136 uint32_t instr, bool isARM) 137 : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 4, 138 ".text.patch"), 139 patchee(p), patcheeOffset(off), instr(instr), isARM(isARM) { 140 parent = p->getParent(); 141 patchSym = addSyntheticLocal( 142 saver.save("__CortexA8657417_" + utohexstr(getBranchAddr())), STT_FUNC, 143 isARM ? 0 : 1, getSize(), *this); 144 addSyntheticLocal(saver.save(isARM ? "$a" : "$t"), STT_NOTYPE, 0, 0, *this); 145 } 146 147 uint64_t Patch657417Section::getBranchAddr() const { 148 return patchee->getVA(patcheeOffset); 149 } 150 151 // Given a branch instruction instr at sourceAddr work out its destination 152 // address. This is only used when the branch instruction has no relocation. 153 static uint64_t getThumbDestAddr(uint64_t sourceAddr, uint32_t instr) { 154 uint8_t buf[4]; 155 write16le(buf, instr >> 16); 156 write16le(buf + 2, instr & 0x0000ffff); 157 int64_t offset; 158 if (isBcc(instr)) 159 offset = target->getImplicitAddend(buf, R_ARM_THM_JUMP19); 160 else if (isB(instr)) 161 offset = target->getImplicitAddend(buf, R_ARM_THM_JUMP24); 162 else 163 offset = target->getImplicitAddend(buf, R_ARM_THM_CALL); 164 return sourceAddr + offset + 4; 165 } 166 167 void Patch657417Section::writeTo(uint8_t *buf) { 168 // The base instruction of the patch is always a 32-bit unconditional branch. 169 if (isARM) 170 write32le(buf, 0xea000000); 171 else 172 write32le(buf, 0x9000f000); 173 // If we have a relocation then apply it. For a SyntheticSection buf already 174 // has outSecOff added, but relocateAlloc also adds outSecOff so we need to 175 // subtract to avoid double counting. 176 if (!relocations.empty()) { 177 relocateAlloc(buf - outSecOff, buf - outSecOff + getSize()); 178 return; 179 } 180 181 // If we don't have a relocation then we must calculate and write the offset 182 // ourselves. 183 // Get the destination offset from the addend in the branch instruction. 184 // We cannot use the instruction in the patchee section as this will have 185 // been altered to point to us! 186 uint64_t s = getThumbDestAddr(getBranchAddr(), instr); 187 uint64_t p = getVA(4); 188 target->relocateOne(buf, isARM ? R_ARM_JUMP24 : R_ARM_THM_JUMP24, s - p); 189 } 190 191 // Given a branch instruction spanning two 4KiB regions, at offset off from the 192 // start of isec, return true if the destination of the branch is within the 193 // first of the two 4Kib regions. 194 static bool branchDestInFirstRegion(const InputSection *isec, uint64_t off, 195 uint32_t instr, const Relocation *r) { 196 uint64_t sourceAddr = isec->getVA(0) + off; 197 assert((sourceAddr & 0xfff) == 0xffe); 198 uint64_t destAddr = sourceAddr; 199 // If there is a branch relocation at the same offset we must use this to 200 // find the destination address as the branch could be indirected via a thunk 201 // or the PLT. 202 if (r) { 203 uint64_t dst = (r->expr == R_PLT_PC) ? r->sym->getPltVA() : r->sym->getVA(); 204 // Account for Thumb PC bias, usually cancelled to 0 by addend of -4. 205 destAddr = dst + r->addend + 4; 206 } else { 207 // If there is no relocation, we must have an intra-section branch 208 // We must extract the offset from the addend manually. 209 destAddr = getThumbDestAddr(sourceAddr, instr); 210 } 211 212 return (destAddr & 0xfffff000) == (sourceAddr & 0xfffff000); 213 } 214 215 // Return true if a branch can reach a patch section placed after isec. 216 // The Bcc.w instruction has a range of 1 MiB, all others have 16 MiB. 217 static bool patchInRange(const InputSection *isec, uint64_t off, 218 uint32_t instr) { 219 220 // We need the branch at source to reach a patch section placed immediately 221 // after isec. As there can be more than one patch in the patch section we 222 // add 0x100 as contingency to account for worst case of 1 branch every 4KiB 223 // for a 1 MiB range. 224 return target->inBranchRange( 225 isBcc(instr) ? R_ARM_THM_JUMP19 : R_ARM_THM_JUMP24, isec->getVA(off), 226 isec->getVA() + isec->getSize() + 0x100); 227 } 228 229 struct ScanResult { 230 // Offset of branch within its InputSection. 231 uint64_t off; 232 // Cached decoding of the branch instruction. 233 uint32_t instr; 234 // Branch relocation at off. Will be nullptr if no relocation exists. 235 Relocation *rel; 236 }; 237 238 // Detect the erratum sequence, returning the offset of the branch instruction 239 // and a decoding of the branch. If the erratum sequence is not found then 240 // return an offset of 0 for the branch. 0 is a safe value to use for no patch 241 // as there must be at least one 32-bit non-branch instruction before the 242 // branch so the minimum offset for a patch is 4. 243 static ScanResult scanCortexA8Errata657417(InputSection *isec, uint64_t &off, 244 uint64_t limit) { 245 uint64_t isecAddr = isec->getVA(0); 246 // Advance Off so that (isecAddr + off) modulo 0x1000 is at least 0xffa. We 247 // need to check for a 32-bit instruction immediately before a 32-bit branch 248 // at 0xffe modulo 0x1000. 249 off = alignTo(isecAddr + off, 0x1000, 0xffa) - isecAddr; 250 if (off >= limit || limit - off < 8) { 251 // Need at least 2 4-byte sized instructions to trigger erratum. 252 off = limit; 253 return {0, 0, nullptr}; 254 } 255 256 ScanResult scanRes = {0, 0, nullptr}; 257 const uint8_t *buf = isec->data().begin(); 258 // ARMv7-A Thumb 32-bit instructions are encoded 2 consecutive 259 // little-endian halfwords. 260 const ulittle16_t *instBuf = reinterpret_cast<const ulittle16_t *>(buf + off); 261 uint16_t hw11 = *instBuf++; 262 uint16_t hw12 = *instBuf++; 263 uint16_t hw21 = *instBuf++; 264 uint16_t hw22 = *instBuf++; 265 if (is32bitInstruction(hw11) && is32bitInstruction(hw21)) { 266 uint32_t instr1 = (hw11 << 16) | hw12; 267 uint32_t instr2 = (hw21 << 16) | hw22; 268 if (!is32bitBranch(instr1) && is32bitBranch(instr2)) { 269 // Find a relocation for the branch if it exists. This will be used 270 // to determine the target. 271 uint64_t branchOff = off + 4; 272 auto relIt = llvm::find_if(isec->relocations, [=](const Relocation &r) { 273 return r.offset == branchOff && 274 (r.type == R_ARM_THM_JUMP19 || r.type == R_ARM_THM_JUMP24 || 275 r.type == R_ARM_THM_CALL); 276 }); 277 if (relIt != isec->relocations.end()) 278 scanRes.rel = &(*relIt); 279 if (branchDestInFirstRegion(isec, branchOff, instr2, scanRes.rel)) { 280 if (patchInRange(isec, branchOff, instr2)) { 281 scanRes.off = branchOff; 282 scanRes.instr = instr2; 283 } else { 284 warn(toString(isec->file) + 285 ": skipping cortex-a8 657417 erratum sequence, section " + 286 isec->name + " is too large to patch"); 287 } 288 } 289 } 290 } 291 off += 0x1000; 292 return scanRes; 293 } 294 295 void ARMErr657417Patcher::init() { 296 // The Arm ABI permits a mix of ARM, Thumb and Data in the same 297 // InputSection. We must only scan Thumb instructions to avoid false 298 // matches. We use the mapping symbols in the InputObjects to identify this 299 // data, caching the results in sectionMap so we don't have to recalculate 300 // it each pass. 301 302 // The ABI Section 4.5.5 Mapping symbols; defines local symbols that describe 303 // half open intervals [Symbol Value, Next Symbol Value) of code and data 304 // within sections. If there is no next symbol then the half open interval is 305 // [Symbol Value, End of section). The type, code or data, is determined by 306 // the mapping symbol name, $a for Arm code, $t for Thumb code, $d for data. 307 auto isArmMapSymbol = [](const Symbol *s) { 308 return s->getName() == "$a" || s->getName().startswith("$a."); 309 }; 310 auto isThumbMapSymbol = [](const Symbol *s) { 311 return s->getName() == "$t" || s->getName().startswith("$t."); 312 }; 313 auto isDataMapSymbol = [](const Symbol *s) { 314 return s->getName() == "$d" || s->getName().startswith("$d."); 315 }; 316 317 // Collect mapping symbols for every executable InputSection. 318 for (InputFile *file : objectFiles) { 319 auto *f = cast<ObjFile<ELF32LE>>(file); 320 for (Symbol *s : f->getLocalSymbols()) { 321 auto *def = dyn_cast<Defined>(s); 322 if (!def) 323 continue; 324 if (!isArmMapSymbol(def) && !isThumbMapSymbol(def) && 325 !isDataMapSymbol(def)) 326 continue; 327 if (auto *sec = dyn_cast_or_null<InputSection>(def->section)) 328 if (sec->flags & SHF_EXECINSTR) 329 sectionMap[sec].push_back(def); 330 } 331 } 332 // For each InputSection make sure the mapping symbols are in sorted in 333 // ascending order and are in alternating Thumb, non-Thumb order. 334 for (auto &kv : sectionMap) { 335 std::vector<const Defined *> &mapSyms = kv.second; 336 llvm::stable_sort(mapSyms, [](const Defined *a, const Defined *b) { 337 return a->value < b->value; 338 }); 339 mapSyms.erase(std::unique(mapSyms.begin(), mapSyms.end(), 340 [=](const Defined *a, const Defined *b) { 341 return (isThumbMapSymbol(a) == 342 isThumbMapSymbol(b)); 343 }), 344 mapSyms.end()); 345 // Always start with a Thumb Mapping Symbol 346 if (!mapSyms.empty() && !isThumbMapSymbol(mapSyms.front())) 347 mapSyms.erase(mapSyms.begin()); 348 } 349 initialized = true; 350 } 351 352 void ARMErr657417Patcher::insertPatches( 353 InputSectionDescription &isd, std::vector<Patch657417Section *> &patches) { 354 uint64_t spacing = 0x100000 - 0x7500; 355 uint64_t isecLimit; 356 uint64_t prevIsecLimit = isd.sections.front()->outSecOff; 357 uint64_t patchUpperBound = prevIsecLimit + spacing; 358 uint64_t outSecAddr = isd.sections.front()->getParent()->addr; 359 360 // Set the outSecOff of patches to the place where we want to insert them. 361 // We use a similar strategy to initial thunk placement, using 1 MiB as the 362 // range of the Thumb-2 conditional branch with a contingency accounting for 363 // thunk generation. 364 auto patchIt = patches.begin(); 365 auto patchEnd = patches.end(); 366 for (const InputSection *isec : isd.sections) { 367 isecLimit = isec->outSecOff + isec->getSize(); 368 if (isecLimit > patchUpperBound) { 369 for (; patchIt != patchEnd; ++patchIt) { 370 if ((*patchIt)->getBranchAddr() - outSecAddr >= prevIsecLimit) 371 break; 372 (*patchIt)->outSecOff = prevIsecLimit; 373 } 374 patchUpperBound = prevIsecLimit + spacing; 375 } 376 prevIsecLimit = isecLimit; 377 } 378 for (; patchIt != patchEnd; ++patchIt) 379 (*patchIt)->outSecOff = isecLimit; 380 381 // Merge all patch sections. We use the outSecOff assigned above to 382 // determine the insertion point. This is ok as we only merge into an 383 // InputSectionDescription once per pass, and at the end of the pass 384 // assignAddresses() will recalculate all the outSecOff values. 385 std::vector<InputSection *> tmp; 386 tmp.reserve(isd.sections.size() + patches.size()); 387 auto mergeCmp = [](const InputSection *a, const InputSection *b) { 388 if (a->outSecOff != b->outSecOff) 389 return a->outSecOff < b->outSecOff; 390 return isa<Patch657417Section>(a) && !isa<Patch657417Section>(b); 391 }; 392 std::merge(isd.sections.begin(), isd.sections.end(), patches.begin(), 393 patches.end(), std::back_inserter(tmp), mergeCmp); 394 isd.sections = std::move(tmp); 395 } 396 397 // Given a branch instruction described by ScanRes redirect it to a patch 398 // section containing an unconditional branch instruction to the target. 399 // Ensure that this patch section is 4-byte aligned so that the branch cannot 400 // span two 4 KiB regions. Place the patch section so that it is always after 401 // isec so the branch we are patching always goes forwards. 402 static void implementPatch(ScanResult sr, InputSection *isec, 403 std::vector<Patch657417Section *> &patches) { 404 405 log("detected cortex-a8-657419 erratum sequence starting at " + 406 utohexstr(isec->getVA(sr.off)) + " in unpatched output."); 407 Patch657417Section *psec; 408 // We have two cases to deal with. 409 // Case 1. There is a relocation at patcheeOffset to a symbol. The 410 // unconditional branch in the patch must have a relocation so that any 411 // further redirection via the PLT or a Thunk happens as normal. At 412 // patcheeOffset we redirect the existing relocation to a Symbol defined at 413 // the start of the patch section. 414 // 415 // Case 2. There is no relocation at patcheeOffset. We are unlikely to have 416 // a symbol that we can use as a target for a relocation in the patch section. 417 // Luckily we know that the destination cannot be indirected via the PLT or 418 // a Thunk so we can just write the destination directly. 419 if (sr.rel) { 420 // Case 1. We have an existing relocation to redirect to patch and a 421 // Symbol target. 422 423 // Create a branch relocation for the unconditional branch in the patch. 424 // This can be redirected via the PLT or Thunks. 425 RelType patchRelType = R_ARM_THM_JUMP24; 426 int64_t patchRelAddend = sr.rel->addend; 427 bool destIsARM = false; 428 if (isBL(sr.instr) || isBLX(sr.instr)) { 429 // The final target of the branch may be ARM or Thumb, if the target 430 // is ARM then we write the patch in ARM state to avoid a state change 431 // Thunk from the patch to the target. 432 uint64_t dstSymAddr = (sr.rel->expr == R_PLT_PC) ? sr.rel->sym->getPltVA() 433 : sr.rel->sym->getVA(); 434 destIsARM = (dstSymAddr & 1) == 0; 435 } 436 psec = make<Patch657417Section>(isec, sr.off, sr.instr, destIsARM); 437 if (destIsARM) { 438 // The patch will be in ARM state. Use an ARM relocation and account for 439 // the larger ARM PC-bias of 8 rather than Thumb's 4. 440 patchRelType = R_ARM_JUMP24; 441 patchRelAddend -= 4; 442 } 443 psec->relocations.push_back( 444 Relocation{sr.rel->expr, patchRelType, 0, patchRelAddend, sr.rel->sym}); 445 // Redirect the existing branch relocation to the patch. 446 sr.rel->expr = R_PC; 447 sr.rel->addend = -4; 448 sr.rel->sym = psec->patchSym; 449 } else { 450 // Case 2. We do not have a relocation to the patch. Add a relocation of the 451 // appropriate type to the patch at patcheeOffset. 452 453 // The destination is ARM if we have a BLX. 454 psec = make<Patch657417Section>(isec, sr.off, sr.instr, isBLX(sr.instr)); 455 RelType type; 456 if (isBcc(sr.instr)) 457 type = R_ARM_THM_JUMP19; 458 else if (isB(sr.instr)) 459 type = R_ARM_THM_JUMP24; 460 else 461 type = R_ARM_THM_CALL; 462 isec->relocations.push_back( 463 Relocation{R_PC, type, sr.off, -4, psec->patchSym}); 464 } 465 patches.push_back(psec); 466 } 467 468 // Scan all the instructions in InputSectionDescription, for each instance of 469 // the erratum sequence create a Patch657417Section. We return the list of 470 // Patch657417Sections that need to be applied to the InputSectionDescription. 471 std::vector<Patch657417Section *> 472 ARMErr657417Patcher::patchInputSectionDescription( 473 InputSectionDescription &isd) { 474 std::vector<Patch657417Section *> patches; 475 for (InputSection *isec : isd.sections) { 476 // LLD doesn't use the erratum sequence in SyntheticSections. 477 if (isa<SyntheticSection>(isec)) 478 continue; 479 // Use sectionMap to make sure we only scan Thumb code and not Arm or inline 480 // data. We have already sorted mapSyms in ascending order and removed 481 // consecutive mapping symbols of the same type. Our range of executable 482 // instructions to scan is therefore [thumbSym->value, nonThumbSym->value) 483 // or [thumbSym->value, section size). 484 std::vector<const Defined *> &mapSyms = sectionMap[isec]; 485 486 auto thumbSym = mapSyms.begin(); 487 while (thumbSym != mapSyms.end()) { 488 auto nonThumbSym = std::next(thumbSym); 489 uint64_t off = (*thumbSym)->value; 490 uint64_t limit = (nonThumbSym == mapSyms.end()) ? isec->data().size() 491 : (*nonThumbSym)->value; 492 493 while (off < limit) { 494 ScanResult sr = scanCortexA8Errata657417(isec, off, limit); 495 if (sr.off) 496 implementPatch(sr, isec, patches); 497 } 498 if (nonThumbSym == mapSyms.end()) 499 break; 500 thumbSym = std::next(nonThumbSym); 501 } 502 } 503 return patches; 504 } 505 506 bool ARMErr657417Patcher::createFixes() { 507 if (!initialized) 508 init(); 509 510 bool addressesChanged = false; 511 for (OutputSection *os : outputSections) { 512 if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR)) 513 continue; 514 for (BaseCommand *bc : os->sectionCommands) 515 if (auto *isd = dyn_cast<InputSectionDescription>(bc)) { 516 std::vector<Patch657417Section *> patches = 517 patchInputSectionDescription(*isd); 518 if (!patches.empty()) { 519 insertPatches(*isd, patches); 520 addressesChanged = true; 521 } 522 } 523 } 524 return addressesChanged; 525 } 526 527 } // namespace elf 528 } // namespace lld 529