1 //=== aarch64.h - Generic JITLink aarch64 edge kinds, utilities -*- C++ -*-===// 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 // Generic utilities for graphs representing aarch64 objects. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_EXECUTIONENGINE_JITLINK_AARCH64_H 14 #define LLVM_EXECUTIONENGINE_JITLINK_AARCH64_H 15 16 #include "TableManager.h" 17 #include "llvm/ExecutionEngine/JITLink/JITLink.h" 18 #include "llvm/ExecutionEngine/Orc/Shared/MemoryFlags.h" 19 20 namespace llvm { 21 namespace jitlink { 22 namespace aarch64 { 23 24 /// Represents aarch64 fixups and other aarch64-specific edge kinds. 25 enum EdgeKind_aarch64 : Edge::Kind { 26 27 /// A plain 64-bit pointer value relocation. 28 /// 29 /// Fixup expression: 30 /// Fixup <- Target + Addend : uint64 31 /// 32 Pointer64 = Edge::FirstRelocation, 33 34 /// An arm64e authenticated pointer relocation. The addend contains a 64-bit 35 /// struct containing the authentication parameters: 36 /// 37 /// Addend encoding: 38 /// int32_t addend; 39 /// uint16_t diversityData; 40 /// uint16_t hasAddressDiversity : 1; 41 /// uint16_t key : 2; 42 /// uint16_t zeroes : 12; 43 /// uint16_t authenticated : 1; 44 /// 45 /// Note: This means that the addend cannot be interpreted as a plain offset 46 /// prior to lowering. 47 /// 48 /// Authenticated pointer edges cannot be fixed up directly by JITLink as the 49 /// signing keys are held in the executing process. They can be removed from 50 /// the graph by a combination of the createEmptyPointerSigningFunction pass 51 /// (post-prune) and the lowerPointer64AuthEdgesToSigningFunction pass 52 /// (pre-fixup). Together these passes construct a signing function that will 53 /// be run in the executing process to write the signed pointers to the fixup 54 /// locations. 55 /// 56 /// Fixup expression: 57 /// NONE 58 /// 59 /// Errors: 60 /// - Failure to handle edges of this kind prior to the fixup phase will 61 /// result in an unsupported error during the fixup phase. 62 Pointer64Authenticated, 63 64 /// A plain 32-bit pointer value relocation. 65 /// 66 /// Fixup expression: 67 /// Fixup <- Target + Addend : uint32 68 /// 69 /// Errors: 70 /// - The target must reside in the low 32-bits of the address space, 71 /// otherwise an out-of-range error will be returned. 72 /// 73 Pointer32, 74 75 /// A 64-bit delta. 76 /// 77 /// Delta from the fixup to the target. 78 /// 79 /// Fixup expression: 80 /// Fixup <- Target - Fixup + Addend : int64 81 /// 82 Delta64, 83 84 /// A 32-bit delta. 85 /// 86 /// Delta from the fixup to the target. 87 /// 88 /// Fixup expression: 89 /// Fixup <- Target - Fixup + Addend : int64 90 /// 91 /// Errors: 92 /// - The result of the fixup expression must fit into an int32, otherwise 93 /// an out-of-range error will be returned. 94 /// 95 Delta32, 96 97 /// A 64-bit negative delta. 98 /// 99 /// Delta from target back to the fixup. 100 /// 101 /// Fixup expression: 102 /// Fixup <- Fixup - Target + Addend : int64 103 /// 104 NegDelta64, 105 106 /// A 32-bit negative delta. 107 /// 108 /// Delta from the target back to the fixup. 109 /// 110 /// Fixup expression: 111 /// Fixup <- Fixup - Target + Addend : int32 112 /// 113 /// Errors: 114 /// - The result of the fixup expression must fit into an int32, otherwise 115 /// an out-of-range error will be returned. 116 NegDelta32, 117 118 /// A 26-bit PC-relative branch. 119 /// 120 /// Represents a PC-relative call or branch to a target within +/-128Mb. The 121 /// target must be 32-bit aligned. 122 /// 123 /// Fixup expression: 124 /// Fixup <- (Target - Fixup + Addend) >> 2 : int26 125 /// 126 /// Notes: 127 /// The '26' in the name refers to the number operand bits and follows the 128 /// naming convention used by the corresponding ELF and MachO relocations. 129 /// Since the low two bits must be zero (because of the 32-bit alignment of 130 /// the target) the operand is effectively a signed 28-bit number. 131 /// 132 /// 133 /// Errors: 134 /// - The result of the unshifted part of the fixup expression must be 135 /// 32-bit aligned otherwise an alignment error will be returned. 136 /// - The result of the fixup expression must fit into an int26 otherwise an 137 /// out-of-range error will be returned. 138 Branch26PCRel, 139 140 /// A 14-bit PC-relative test and branch. 141 /// 142 /// Represents a PC-relative test and branch to a target within +/-32Kb. The 143 /// target must be 32-bit aligned. 144 /// 145 /// Fixup expression: 146 /// Fixup <- (Target - Fixup + Addend) >> 2 : int14 147 /// 148 /// Notes: 149 /// The '14' in the name refers to the number operand bits and follows the 150 /// naming convention used by the corresponding ELF relocation. 151 /// Since the low two bits must be zero (because of the 32-bit alignment of 152 /// the target) the operand is effectively a signed 16-bit number. 153 /// 154 /// 155 /// Errors: 156 /// - The result of the unshifted part of the fixup expression must be 157 /// 32-bit aligned otherwise an alignment error will be returned. 158 /// - The result of the fixup expression must fit into an int14 otherwise an 159 /// out-of-range error will be returned. 160 TestAndBranch14PCRel, 161 162 /// A 19-bit PC-relative conditional branch. 163 /// 164 /// Represents a PC-relative conditional branch to a target within +/-1Mb. The 165 /// target must be 32-bit aligned. 166 /// 167 /// Fixup expression: 168 /// Fixup <- (Target - Fixup + Addend) >> 2 : int19 169 /// 170 /// Notes: 171 /// The '19' in the name refers to the number operand bits and follows the 172 /// naming convention used by the corresponding ELF relocation. 173 /// Since the low two bits must be zero (because of the 32-bit alignment of 174 /// the target) the operand is effectively a signed 21-bit number. 175 /// 176 /// 177 /// Errors: 178 /// - The result of the unshifted part of the fixup expression must be 179 /// 32-bit aligned otherwise an alignment error will be returned. 180 /// - The result of the fixup expression must fit into an int19 otherwise an 181 /// out-of-range error will be returned. 182 CondBranch19PCRel, 183 184 /// A 16-bit slice of the target address (which slice depends on the 185 /// instruction at the fixup location). 186 /// 187 /// Used to fix up MOVK/MOVN/MOVZ instructions. 188 /// 189 /// Fixup expression: 190 /// 191 /// Fixup <- (Target + Addend) >> Shift : uint16 192 /// 193 /// where Shift is encoded in the instruction at the fixup location. 194 /// 195 MoveWide16, 196 197 /// The signed 21-bit delta from the fixup to the target. 198 /// 199 /// Typically used to load a pointers at a PC-relative offset of +/- 1Mb. The 200 /// target must be 32-bit aligned. 201 /// 202 /// Fixup expression: 203 /// 204 /// Fixup <- (Target - Fixup + Addend) >> 2 : int19 205 /// 206 /// Notes: 207 /// The '19' in the name refers to the number operand bits and follows the 208 /// naming convention used by the corresponding ELF relocation. 209 /// Since the low two bits must be zero (because of the 32-bit alignment of 210 /// the target) the operand is effectively a signed 21-bit number. 211 /// 212 /// 213 /// Errors: 214 /// - The result of the unshifted part of the fixup expression must be 215 /// 32-bit aligned otherwise an alignment error will be returned. 216 /// - The result of the fixup expression must fit into an int19 or an 217 /// out-of-range error will be returned. 218 LDRLiteral19, 219 220 /// The signed 21-bit delta from the fixup to the target. 221 /// 222 /// Fixup expression: 223 /// 224 /// Fixup <- Target - Fixup + Addend : int21 225 /// 226 /// Notes: 227 /// For ADR fixups. 228 /// 229 /// Errors: 230 /// - The result of the fixup expression must fit into an int21 otherwise an 231 /// out-of-range error will be returned. 232 ADRLiteral21, 233 234 /// The signed 21-bit delta from the fixup page to the page containing the 235 /// target. 236 /// 237 /// Fixup expression: 238 /// 239 /// Fixup <- (((Target + Addend) & ~0xfff) - (Fixup & ~0xfff)) >> 12 : int21 240 /// 241 /// Notes: 242 /// For ADRP fixups. 243 /// 244 /// Errors: 245 /// - The result of the fixup expression must fit into an int21 otherwise an 246 /// out-of-range error will be returned. 247 Page21, 248 249 /// The 12-bit (potentially shifted) offset of the target within its page. 250 /// 251 /// Typically used to fix up LDR immediates. 252 /// 253 /// Fixup expression: 254 /// 255 /// Fixup <- ((Target + Addend) >> Shift) & 0xfff : uint12 256 /// 257 /// where Shift is encoded in the size field of the instruction. 258 /// 259 /// Errors: 260 /// - The result of the unshifted part of the fixup expression must be 261 /// aligned otherwise an alignment error will be returned. 262 /// - The result of the fixup expression must fit into a uint12 otherwise an 263 /// out-of-range error will be returned. 264 PageOffset12, 265 266 /// The 15-bit offset of the GOT entry from the GOT table. 267 /// 268 /// Used for load/store instructions addressing a GOT entry. 269 /// 270 /// Fixup expression: 271 /// 272 /// Fixup <- ((Target + Addend - Page(GOT))) & 0x7fff) >> 3 : uint12 273 /// 274 /// Errors: 275 /// - The result of the unshifted part of the fixup expression must be 276 /// aligned otherwise an alignment error will be returned. 277 /// - The result of the fixup expression must fit into a uint12 otherwise an 278 /// out-of-range error will be returned. 279 GotPageOffset15, 280 281 /// A GOT entry getter/constructor, transformed to Page21 pointing at the GOT 282 /// entry for the original target. 283 /// 284 /// Indicates that this edge should be transformed into a Page21 targeting 285 /// the GOT entry for the edge's current target, maintaining the same addend. 286 /// A GOT entry for the target should be created if one does not already 287 /// exist. 288 /// 289 /// Edges of this kind are usually handled by a GOT builder pass inserted by 290 /// default. 291 /// 292 /// Fixup expression: 293 /// NONE 294 /// 295 /// Errors: 296 /// - *ASSERTION* Failure to handle edges of this kind prior to the fixup 297 /// phase will result in an assert/unreachable during the fixup phase. 298 /// 299 RequestGOTAndTransformToPage21, 300 301 /// A GOT entry getter/constructor, transformed to Pageoffset12 pointing at 302 /// the GOT entry for the original target. 303 /// 304 /// Indicates that this edge should be transformed into a PageOffset12 305 /// targeting the GOT entry for the edge's current target, maintaining the 306 /// same addend. A GOT entry for the target should be created if one does not 307 /// already exist. 308 /// 309 /// Edges of this kind are usually handled by a GOT builder pass inserted by 310 /// default. 311 /// 312 /// Fixup expression: 313 /// NONE 314 /// 315 /// Errors: 316 /// - *ASSERTION* Failure to handle edges of this kind prior to the fixup 317 /// phase will result in an assert/unreachable during the fixup phase. 318 /// 319 RequestGOTAndTransformToPageOffset12, 320 321 /// A GOT entry getter/constructor, transformed to Pageoffset15 pointing at 322 /// the GOT entry for the original target. 323 /// 324 /// Indicates that this edge should be transformed into a GotPageOffset15 325 /// targeting the GOT entry for the edge's current target, maintaining the 326 /// same addend. A GOT entry for the target should be created if one does not 327 /// already exist. 328 /// 329 /// Fixup expression: 330 /// NONE 331 /// 332 /// Errors: 333 /// - *ASSERTION* Failure to handle edges of this kind prior to the fixup 334 /// phase will result in an assert/unreachable during the fixup phase. 335 /// 336 RequestGOTAndTransformToPageOffset15, 337 338 /// A GOT entry getter/constructor, transformed to Delta32 pointing at the GOT 339 /// entry for the original target. 340 /// 341 /// Indicates that this edge should be transformed into a Delta32/ targeting 342 /// the GOT entry for the edge's current target, maintaining the same addend. 343 /// A GOT entry for the target should be created if one does not already 344 /// exist. 345 /// 346 /// Edges of this kind are usually handled by a GOT builder pass inserted by 347 /// default. 348 /// 349 /// Fixup expression: 350 /// NONE 351 /// 352 /// Errors: 353 /// - *ASSERTION* Failure to handle edges of this kind prior to the fixup 354 /// phase will result in an assert/unreachable during the fixup phase. 355 /// 356 RequestGOTAndTransformToDelta32, 357 358 /// A TLVP entry getter/constructor, transformed to Page21. 359 /// 360 /// Indicates that this edge should be transformed into a Page21 targeting the 361 /// TLVP entry for the edge's current target. A TLVP entry for the target 362 /// should be created if one does not already exist. 363 /// 364 /// Fixup expression: 365 /// NONE 366 /// 367 /// Errors: 368 /// - *ASSERTION* Failure to handle edges of this kind prior to the fixup 369 /// phase will result in an assert/unreachable during the fixup phase. 370 /// 371 RequestTLVPAndTransformToPage21, 372 373 /// A TLVP entry getter/constructor, transformed to PageOffset12. 374 /// 375 /// Indicates that this edge should be transformed into a PageOffset12 376 /// targeting the TLVP entry for the edge's current target. A TLVP entry for 377 /// the target should be created if one does not already exist. 378 /// 379 /// Fixup expression: 380 /// NONE 381 /// 382 /// Errors: 383 /// - *ASSERTION* Failure to handle edges of this kind prior to the fixup 384 /// phase will result in an assert/unreachable during the fixup phase. 385 /// 386 RequestTLVPAndTransformToPageOffset12, 387 388 /// A TLSDesc entry getter/constructor, transformed to Page21. 389 /// 390 /// Indicates that this edge should be transformed into a Page21 targeting the 391 /// TLSDesc entry for the edge's current target. A TLSDesc entry for the 392 /// target should be created if one does not already exist. 393 /// 394 /// Fixup expression: 395 /// NONE 396 /// 397 /// Errors: 398 /// - *ASSERTION* Failure to handle edges of this kind prior to the fixup 399 /// phase will result in an assert/unreachable during the fixup phase. 400 /// 401 RequestTLSDescEntryAndTransformToPage21, 402 403 /// A TLSDesc entry getter/constructor, transformed to PageOffset12. 404 /// 405 /// Indicates that this edge should be transformed into a PageOffset12 406 /// targeting the TLSDesc entry for the edge's current target. A TLSDesc entry 407 /// for the target should be created if one does not already exist. 408 /// 409 /// Fixup expression: 410 /// NONE 411 /// 412 /// Errors: 413 /// - *ASSERTION* Failure to handle edges of this kind prior to the fixup 414 /// phase will result in an assert/unreachable during the fixup phase. 415 /// 416 RequestTLSDescEntryAndTransformToPageOffset12, 417 }; 418 419 /// Returns a string name for the given aarch64 edge. For debugging purposes 420 /// only 421 const char *getEdgeKindName(Edge::Kind K); 422 423 // Returns whether the Instr is LD/ST (imm12) 424 inline bool isLoadStoreImm12(uint32_t Instr) { 425 constexpr uint32_t LoadStoreImm12Mask = 0x3b000000; 426 return (Instr & LoadStoreImm12Mask) == 0x39000000; 427 } 428 429 inline bool isTestAndBranchImm14(uint32_t Instr) { 430 constexpr uint32_t TestAndBranchImm14Mask = 0x7e000000; 431 return (Instr & TestAndBranchImm14Mask) == 0x36000000; 432 } 433 434 inline bool isCondBranchImm19(uint32_t Instr) { 435 constexpr uint32_t CondBranchImm19Mask = 0xfe000000; 436 return (Instr & CondBranchImm19Mask) == 0x54000000; 437 } 438 439 inline bool isCompAndBranchImm19(uint32_t Instr) { 440 constexpr uint32_t CompAndBranchImm19Mask = 0x7e000000; 441 return (Instr & CompAndBranchImm19Mask) == 0x34000000; 442 } 443 444 inline bool isADR(uint32_t Instr) { 445 constexpr uint32_t ADRMask = 0x9f000000; 446 return (Instr & ADRMask) == 0x10000000; 447 } 448 449 inline bool isLDRLiteral(uint32_t Instr) { 450 constexpr uint32_t LDRLitMask = 0x3b000000; 451 return (Instr & LDRLitMask) == 0x18000000; 452 } 453 454 // Returns the amount the address operand of LD/ST (imm12) 455 // should be shifted right by. 456 // 457 // The shift value varies by the data size of LD/ST instruction. 458 // For instance, LDH instructoin needs the address to be shifted 459 // right by 1. 460 inline unsigned getPageOffset12Shift(uint32_t Instr) { 461 constexpr uint32_t Vec128Mask = 0x04800000; 462 463 if (isLoadStoreImm12(Instr)) { 464 uint32_t ImplicitShift = Instr >> 30; 465 if (ImplicitShift == 0) 466 if ((Instr & Vec128Mask) == Vec128Mask) 467 ImplicitShift = 4; 468 469 return ImplicitShift; 470 } 471 472 return 0; 473 } 474 475 // Returns whether the Instr is MOVK/MOVZ (imm16) with a zero immediate field 476 inline bool isMoveWideImm16(uint32_t Instr) { 477 constexpr uint32_t MoveWideImm16Mask = 0x5f9fffe0; 478 return (Instr & MoveWideImm16Mask) == 0x52800000; 479 } 480 481 // Returns the amount the address operand of MOVK/MOVZ (imm16) 482 // should be shifted right by. 483 // 484 // The shift value is specfied in the assembly as LSL #<shift>. 485 inline unsigned getMoveWide16Shift(uint32_t Instr) { 486 if (isMoveWideImm16(Instr)) { 487 uint32_t ImplicitShift = (Instr >> 21) & 0b11; 488 return ImplicitShift << 4; 489 } 490 491 return 0; 492 } 493 494 /// Apply fixup expression for edge to block content. 495 inline Error applyFixup(LinkGraph &G, Block &B, const Edge &E, 496 const Symbol *GOTSymbol) { 497 using namespace support; 498 499 char *BlockWorkingMem = B.getAlreadyMutableContent().data(); 500 char *FixupPtr = BlockWorkingMem + E.getOffset(); 501 orc::ExecutorAddr FixupAddress = B.getAddress() + E.getOffset(); 502 503 switch (E.getKind()) { 504 case Pointer64: { 505 uint64_t Value = E.getTarget().getAddress().getValue() + E.getAddend(); 506 *(ulittle64_t *)FixupPtr = Value; 507 break; 508 } 509 case Pointer32: { 510 uint64_t Value = E.getTarget().getAddress().getValue() + E.getAddend(); 511 if (Value > std::numeric_limits<uint32_t>::max()) 512 return makeTargetOutOfRangeError(G, B, E); 513 *(ulittle32_t *)FixupPtr = Value; 514 break; 515 } 516 case Delta32: 517 case Delta64: 518 case NegDelta32: 519 case NegDelta64: { 520 int64_t Value; 521 if (E.getKind() == Delta32 || E.getKind() == Delta64) 522 Value = E.getTarget().getAddress() - FixupAddress + E.getAddend(); 523 else 524 Value = FixupAddress - E.getTarget().getAddress() + E.getAddend(); 525 526 if (E.getKind() == Delta32 || E.getKind() == NegDelta32) { 527 if (Value < std::numeric_limits<int32_t>::min() || 528 Value > std::numeric_limits<int32_t>::max()) 529 return makeTargetOutOfRangeError(G, B, E); 530 *(little32_t *)FixupPtr = Value; 531 } else 532 *(little64_t *)FixupPtr = Value; 533 break; 534 } 535 case Branch26PCRel: { 536 assert((FixupAddress.getValue() & 0x3) == 0 && 537 "Branch-inst is not 32-bit aligned"); 538 539 int64_t Value = E.getTarget().getAddress() - FixupAddress + E.getAddend(); 540 541 if (static_cast<uint64_t>(Value) & 0x3) 542 return make_error<JITLinkError>("BranchPCRel26 target is not 32-bit " 543 "aligned"); 544 545 if (Value < -(1 << 27) || Value > ((1 << 27) - 1)) 546 return makeTargetOutOfRangeError(G, B, E); 547 548 uint32_t RawInstr = *(little32_t *)FixupPtr; 549 assert((RawInstr & 0x7fffffff) == 0x14000000 && 550 "RawInstr isn't a B or BR immediate instruction"); 551 uint32_t Imm = (static_cast<uint32_t>(Value) & ((1 << 28) - 1)) >> 2; 552 uint32_t FixedInstr = RawInstr | Imm; 553 *(little32_t *)FixupPtr = FixedInstr; 554 break; 555 } 556 case MoveWide16: { 557 uint64_t TargetOffset = 558 (E.getTarget().getAddress() + E.getAddend()).getValue(); 559 560 uint32_t RawInstr = *(ulittle32_t *)FixupPtr; 561 assert(isMoveWideImm16(RawInstr) && 562 "RawInstr isn't a MOVK/MOVZ instruction"); 563 564 unsigned ImmShift = getMoveWide16Shift(RawInstr); 565 uint32_t Imm = (TargetOffset >> ImmShift) & 0xffff; 566 uint32_t FixedInstr = RawInstr | (Imm << 5); 567 *(ulittle32_t *)FixupPtr = FixedInstr; 568 break; 569 } 570 case LDRLiteral19: { 571 assert((FixupAddress.getValue() & 0x3) == 0 && "LDR is not 32-bit aligned"); 572 uint32_t RawInstr = *(ulittle32_t *)FixupPtr; 573 assert(isLDRLiteral(RawInstr) && "RawInstr is not an LDR Literal"); 574 int64_t Delta = E.getTarget().getAddress() + E.getAddend() - FixupAddress; 575 if (Delta & 0x3) 576 return make_error<JITLinkError>("LDR literal target is not 32-bit " 577 "aligned"); 578 if (!isInt<21>(Delta)) 579 return makeTargetOutOfRangeError(G, B, E); 580 uint32_t EncodedImm = ((static_cast<uint32_t>(Delta) >> 2) & 0x7ffff) << 5; 581 uint32_t FixedInstr = RawInstr | EncodedImm; 582 *(ulittle32_t *)FixupPtr = FixedInstr; 583 break; 584 } 585 case ADRLiteral21: { 586 assert((FixupAddress.getValue() & 0x3) == 0 && "ADR is not 32-bit aligned"); 587 uint32_t RawInstr = *(ulittle32_t *)FixupPtr; 588 assert(isADR(RawInstr) && "RawInstr is not an ADR"); 589 int64_t Delta = E.getTarget().getAddress() + E.getAddend() - FixupAddress; 590 if (!isInt<21>(Delta)) 591 return makeTargetOutOfRangeError(G, B, E); 592 auto UDelta = static_cast<uint32_t>(Delta); 593 uint32_t EncodedImmHi = ((UDelta >> 2) & 0x7ffff) << 5; 594 uint32_t EncodedImmLo = (UDelta & 0x3) << 29; 595 uint32_t FixedInstr = RawInstr | EncodedImmHi | EncodedImmLo; 596 *(ulittle32_t *)FixupPtr = FixedInstr; 597 break; 598 } 599 case TestAndBranch14PCRel: { 600 assert((FixupAddress.getValue() & 0x3) == 0 && 601 "Test and branch is not 32-bit aligned"); 602 uint32_t RawInstr = *(ulittle32_t *)FixupPtr; 603 assert(isTestAndBranchImm14(RawInstr) && 604 "RawInstr is not a test and branch"); 605 int64_t Delta = E.getTarget().getAddress() + E.getAddend() - FixupAddress; 606 if (Delta & 0x3) 607 return make_error<JITLinkError>( 608 "Test and branch literal target is not 32-bit aligned"); 609 if (!isInt<16>(Delta)) 610 return makeTargetOutOfRangeError(G, B, E); 611 uint32_t EncodedImm = ((static_cast<uint32_t>(Delta) >> 2) & 0x3fff) << 5; 612 uint32_t FixedInstr = RawInstr | EncodedImm; 613 *(ulittle32_t *)FixupPtr = FixedInstr; 614 break; 615 } 616 case CondBranch19PCRel: { 617 assert((FixupAddress.getValue() & 0x3) == 0 && 618 "Conditional branch is not 32-bit aligned"); 619 uint32_t RawInstr = *(ulittle32_t *)FixupPtr; 620 assert((isCondBranchImm19(RawInstr) || isCompAndBranchImm19(RawInstr)) && 621 "RawInstr is not a conditional branch"); 622 int64_t Delta = E.getTarget().getAddress() + E.getAddend() - FixupAddress; 623 if (Delta & 0x3) 624 return make_error<JITLinkError>( 625 "Conditional branch literal target is not 32-bit " 626 "aligned"); 627 if (!isInt<21>(Delta)) 628 return makeTargetOutOfRangeError(G, B, E); 629 uint32_t EncodedImm = ((static_cast<uint32_t>(Delta) >> 2) & 0x7ffff) << 5; 630 uint32_t FixedInstr = RawInstr | EncodedImm; 631 *(ulittle32_t *)FixupPtr = FixedInstr; 632 break; 633 } 634 case Page21: { 635 uint64_t TargetPage = 636 (E.getTarget().getAddress().getValue() + E.getAddend()) & 637 ~static_cast<uint64_t>(4096 - 1); 638 uint64_t PCPage = 639 FixupAddress.getValue() & ~static_cast<uint64_t>(4096 - 1); 640 641 int64_t PageDelta = TargetPage - PCPage; 642 if (!isInt<33>(PageDelta)) 643 return makeTargetOutOfRangeError(G, B, E); 644 645 uint32_t RawInstr = *(ulittle32_t *)FixupPtr; 646 assert((RawInstr & 0xffffffe0) == 0x90000000 && 647 "RawInstr isn't an ADRP instruction"); 648 uint32_t ImmLo = (static_cast<uint64_t>(PageDelta) >> 12) & 0x3; 649 uint32_t ImmHi = (static_cast<uint64_t>(PageDelta) >> 14) & 0x7ffff; 650 uint32_t FixedInstr = RawInstr | (ImmLo << 29) | (ImmHi << 5); 651 *(ulittle32_t *)FixupPtr = FixedInstr; 652 break; 653 } 654 case PageOffset12: { 655 uint64_t TargetOffset = 656 (E.getTarget().getAddress() + E.getAddend()).getValue() & 0xfff; 657 658 uint32_t RawInstr = *(ulittle32_t *)FixupPtr; 659 unsigned ImmShift = getPageOffset12Shift(RawInstr); 660 661 if (TargetOffset & ((1 << ImmShift) - 1)) 662 return make_error<JITLinkError>("PAGEOFF12 target is not aligned"); 663 664 uint32_t EncodedImm = (TargetOffset >> ImmShift) << 10; 665 uint32_t FixedInstr = RawInstr | EncodedImm; 666 *(ulittle32_t *)FixupPtr = FixedInstr; 667 break; 668 } 669 case GotPageOffset15: { 670 assert(GOTSymbol && "No GOT section symbol"); 671 uint64_t TargetOffset = 672 (E.getTarget().getAddress() + E.getAddend()).getValue() - 673 (GOTSymbol->getAddress().getValue() & ~static_cast<uint64_t>(4096 - 1)); 674 if (TargetOffset > 0x7fff) 675 return make_error<JITLinkError>("PAGEOFF15 target is out of range"); 676 677 uint32_t RawInstr = *(ulittle32_t *)FixupPtr; 678 const unsigned ImmShift = 3; 679 if (TargetOffset & ((1 << ImmShift) - 1)) 680 return make_error<JITLinkError>("PAGEOFF15 target is not aligned"); 681 682 uint32_t EncodedImm = (TargetOffset >> ImmShift) << 10; 683 uint32_t FixedInstr = RawInstr | EncodedImm; 684 *(ulittle32_t *)FixupPtr = FixedInstr; 685 break; 686 } 687 default: 688 return make_error<JITLinkError>( 689 "In graph " + G.getName() + ", section " + B.getSection().getName() + 690 " unsupported edge kind " + getEdgeKindName(E.getKind())); 691 } 692 693 return Error::success(); 694 } 695 696 /// aarch64 pointer size. 697 constexpr uint64_t PointerSize = 8; 698 699 /// AArch64 null pointer content. 700 extern const char NullPointerContent[PointerSize]; 701 702 /// AArch64 pointer jump stub content. 703 /// 704 /// Contains the instruction sequence for an indirect jump via an in-memory 705 /// pointer: 706 /// ADRP x16, ptr@page21 707 /// LDR x16, [x16, ptr@pageoff12] 708 /// BR x16 709 extern const char PointerJumpStubContent[12]; 710 711 /// Creates a new pointer block in the given section and returns an 712 /// Anonymous symbol pointing to it. 713 /// 714 /// If InitialTarget is given then an Pointer64 relocation will be added to the 715 /// block pointing at InitialTarget. 716 /// 717 /// The pointer block will have the following default values: 718 /// alignment: 64-bit 719 /// alignment-offset: 0 720 /// address: highest allowable (~7U) 721 inline Symbol &createAnonymousPointer(LinkGraph &G, Section &PointerSection, 722 Symbol *InitialTarget = nullptr, 723 uint64_t InitialAddend = 0) { 724 auto &B = G.createContentBlock(PointerSection, NullPointerContent, 725 orc::ExecutorAddr(~uint64_t(7)), 8, 0); 726 if (InitialTarget) 727 B.addEdge(Pointer64, 0, *InitialTarget, InitialAddend); 728 return G.addAnonymousSymbol(B, 0, 8, false, false); 729 } 730 731 /// Create a jump stub block that jumps via the pointer at the given symbol. 732 /// 733 /// The stub block will have the following default values: 734 /// alignment: 32-bit 735 /// alignment-offset: 0 736 /// address: highest allowable: (~11U) 737 inline Block &createPointerJumpStubBlock(LinkGraph &G, Section &StubSection, 738 Symbol &PointerSymbol) { 739 auto &B = G.createContentBlock(StubSection, PointerJumpStubContent, 740 orc::ExecutorAddr(~uint64_t(11)), 4, 0); 741 B.addEdge(Page21, 0, PointerSymbol, 0); 742 B.addEdge(PageOffset12, 4, PointerSymbol, 0); 743 return B; 744 } 745 746 /// Create a jump stub that jumps via the pointer at the given symbol and 747 /// an anonymous symbol pointing to it. Return the anonymous symbol. 748 /// 749 /// The stub block will be created by createPointerJumpStubBlock. 750 inline Symbol &createAnonymousPointerJumpStub(LinkGraph &G, 751 Section &StubSection, 752 Symbol &PointerSymbol) { 753 return G.addAnonymousSymbol( 754 createPointerJumpStubBlock(G, StubSection, PointerSymbol), 0, 755 sizeof(PointerJumpStubContent), true, false); 756 } 757 758 /// AArch64 reentry trampoline. 759 /// 760 /// Contains the instruction sequence for a trampoline that stores its return 761 /// address (and stack pointer) on the stack and calls the given reentry symbol: 762 /// STP x29, x30, [sp, #-16]! 763 /// BL <reentry-symbol> 764 extern const char ReentryTrampolineContent[8]; 765 766 /// Create a block of N reentry trampolines. 767 inline Block &createReentryTrampolineBlock(LinkGraph &G, 768 Section &TrampolineSection, 769 Symbol &ReentrySymbol) { 770 auto &B = G.createContentBlock(TrampolineSection, ReentryTrampolineContent, 771 orc::ExecutorAddr(~uint64_t(7)), 4, 0); 772 B.addEdge(Branch26PCRel, 4, ReentrySymbol, 0); 773 return B; 774 } 775 776 inline Symbol &createAnonymousReentryTrampoline(LinkGraph &G, 777 Section &TrampolineSection, 778 Symbol &ReentrySymbol) { 779 return G.addAnonymousSymbol( 780 createReentryTrampolineBlock(G, TrampolineSection, ReentrySymbol), 0, 781 sizeof(ReentryTrampolineContent), true, false); 782 } 783 784 /// Global Offset Table Builder. 785 class GOTTableManager : public TableManager<GOTTableManager> { 786 public: 787 static StringRef getSectionName() { return "$__GOT"; } 788 789 GOTTableManager(LinkGraph &G) { 790 if ((GOTSection = G.findSectionByName(getSectionName()))) 791 registerExistingEntries(); 792 } 793 794 bool visitEdge(LinkGraph &G, Block *B, Edge &E) { 795 Edge::Kind KindToSet = Edge::Invalid; 796 const char *BlockWorkingMem = B->getContent().data(); 797 const char *FixupPtr = BlockWorkingMem + E.getOffset(); 798 799 switch (E.getKind()) { 800 case aarch64::RequestGOTAndTransformToPage21: 801 case aarch64::RequestTLVPAndTransformToPage21: { 802 KindToSet = aarch64::Page21; 803 break; 804 } 805 case aarch64::RequestGOTAndTransformToPageOffset12: 806 case aarch64::RequestTLVPAndTransformToPageOffset12: { 807 KindToSet = aarch64::PageOffset12; 808 uint32_t RawInstr = *(const support::ulittle32_t *)FixupPtr; 809 (void)RawInstr; 810 assert(E.getAddend() == 0 && 811 "GOTPageOffset12/TLVPageOffset12 with non-zero addend"); 812 assert((RawInstr & 0xfffffc00) == 0xf9400000 && 813 "RawInstr isn't a 64-bit LDR immediate"); 814 break; 815 } 816 case aarch64::RequestGOTAndTransformToPageOffset15: { 817 KindToSet = aarch64::GotPageOffset15; 818 uint32_t RawInstr = *(const support::ulittle32_t *)FixupPtr; 819 (void)RawInstr; 820 assert(E.getAddend() == 0 && "GOTPageOffset15 with non-zero addend"); 821 assert((RawInstr & 0xfffffc00) == 0xf9400000 && 822 "RawInstr isn't a 64-bit LDR immediate"); 823 break; 824 } 825 case aarch64::RequestGOTAndTransformToDelta32: { 826 KindToSet = aarch64::Delta32; 827 break; 828 } 829 default: 830 return false; 831 } 832 assert(KindToSet != Edge::Invalid && 833 "Fell through switch, but no new kind to set"); 834 DEBUG_WITH_TYPE("jitlink", { 835 dbgs() << " Fixing " << G.getEdgeKindName(E.getKind()) << " edge at " 836 << B->getFixupAddress(E) << " (" << B->getAddress() << " + " 837 << formatv("{0:x}", E.getOffset()) << ")\n"; 838 }); 839 E.setKind(KindToSet); 840 E.setTarget(getEntryForTarget(G, E.getTarget())); 841 return true; 842 } 843 844 Symbol &createEntry(LinkGraph &G, Symbol &Target) { 845 return createAnonymousPointer(G, getGOTSection(G), &Target); 846 } 847 848 private: 849 Section &getGOTSection(LinkGraph &G) { 850 if (!GOTSection) 851 GOTSection = &G.createSection(getSectionName(), 852 orc::MemProt::Read | orc::MemProt::Exec); 853 return *GOTSection; 854 } 855 856 void registerExistingEntries(); 857 858 Section *GOTSection = nullptr; 859 }; 860 861 /// Procedure Linkage Table Builder. 862 class PLTTableManager : public TableManager<PLTTableManager> { 863 public: 864 static StringRef getSectionName() { return "$__STUBS"; } 865 866 PLTTableManager(LinkGraph &G, GOTTableManager &GOT) : GOT(GOT) { 867 if ((StubsSection = G.findSectionByName(getSectionName()))) 868 registerExistingEntries(); 869 } 870 871 bool visitEdge(LinkGraph &G, Block *B, Edge &E) { 872 if (E.getKind() == aarch64::Branch26PCRel && !E.getTarget().isDefined()) { 873 DEBUG_WITH_TYPE("jitlink", { 874 dbgs() << " Fixing " << G.getEdgeKindName(E.getKind()) << " edge at " 875 << B->getFixupAddress(E) << " (" << B->getAddress() << " + " 876 << formatv("{0:x}", E.getOffset()) << ")\n"; 877 }); 878 E.setTarget(getEntryForTarget(G, E.getTarget())); 879 return true; 880 } 881 return false; 882 } 883 884 Symbol &createEntry(LinkGraph &G, Symbol &Target) { 885 return createAnonymousPointerJumpStub(G, getStubsSection(G), 886 GOT.getEntryForTarget(G, Target)); 887 } 888 889 public: 890 Section &getStubsSection(LinkGraph &G) { 891 if (!StubsSection) 892 StubsSection = &G.createSection(getSectionName(), 893 orc::MemProt::Read | orc::MemProt::Exec); 894 return *StubsSection; 895 } 896 897 void registerExistingEntries(); 898 899 GOTTableManager &GOT; 900 Section *StubsSection = nullptr; 901 }; 902 903 /// Returns the name of the pointer signing function section. 904 const char *getPointerSigningFunctionSectionName(); 905 906 /// Creates a pointer signing function section, block, and symbol to reserve 907 /// space for a signing function for this LinkGraph. Clients should insert this 908 /// pass in the post-prune phase, and add the paired 909 /// lowerPointer64AuthEdgesToSigningFunction pass to the pre-fixup phase. 910 /// 911 /// No new Pointer64Auth edges can be inserted into the graph between when this 912 /// pass is run and when the pass below runs (since there will not be sufficient 913 /// space reserved in the signing function to write the signing code for them). 914 Error createEmptyPointerSigningFunction(LinkGraph &G); 915 916 /// Given a LinkGraph containing Pointer64Authenticated edges, transform those 917 /// edges to Pointer64 and add signing code to the pointer signing function 918 /// (which must already have been created by the 919 /// createEmptyPointerSigningFunction pass above). 920 /// 921 /// This function will add a $__ptrauth_sign section with finalization-lifetime 922 /// containing an anonymous function that will sign all pointers in the graph. 923 /// An allocation action will be added to run this function during finalization. 924 Error lowerPointer64AuthEdgesToSigningFunction(LinkGraph &G); 925 926 } // namespace aarch64 927 } // namespace jitlink 928 } // namespace llvm 929 930 #endif // LLVM_EXECUTIONENGINE_JITLINK_AARCH64_H 931