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