| 1 | //===------ MachOPlatform.cpp - Utilities for executing MachO in Orc ------===// |
| 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 | #include "llvm/ExecutionEngine/Orc/MachOPlatform.h" |
| 10 | |
| 11 | #include "llvm/BinaryFormat/MachO.h" |
| 12 | #include "llvm/ExecutionEngine/JITLink/EHFrameSupport.h" |
| 13 | #include "llvm/ExecutionEngine/JITLink/MachO.h" |
| 14 | #include "llvm/ExecutionEngine/JITLink/aarch64.h" |
| 15 | #include "llvm/ExecutionEngine/JITLink/x86_64.h" |
| 16 | #include "llvm/ExecutionEngine/Orc/AbsoluteSymbols.h" |
| 17 | #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" |
| 18 | #include "llvm/ExecutionEngine/Orc/MachOBuilder.h" |
| 19 | #include "llvm/ExecutionEngine/Orc/Shared/OrcRTBridge.h" |
| 20 | #include "llvm/Support/Debug.h" |
| 21 | #include <optional> |
| 22 | |
| 23 | #define DEBUG_TYPE "orc" |
| 24 | |
| 25 | using namespace llvm; |
| 26 | using namespace llvm::orc; |
| 27 | using namespace llvm::orc::shared; |
| 28 | |
| 29 | namespace llvm { |
| 30 | namespace orc { |
| 31 | namespace shared { |
| 32 | |
| 33 | using SPSMachOJITDylibDepInfo = SPSTuple<bool, SPSSequence<SPSExecutorAddr>>; |
| 34 | using SPSMachOJITDylibDepInfoMap = |
| 35 | SPSSequence<SPSTuple<SPSExecutorAddr, SPSMachOJITDylibDepInfo>>; |
| 36 | |
| 37 | class SPSMachOExecutorSymbolFlags; |
| 38 | |
| 39 | template <> |
| 40 | class SPSSerializationTraits<SPSMachOJITDylibDepInfo, |
| 41 | MachOPlatform::MachOJITDylibDepInfo> { |
| 42 | public: |
| 43 | static size_t size(const MachOPlatform::MachOJITDylibDepInfo &DDI) { |
| 44 | return SPSMachOJITDylibDepInfo::AsArgList::size(Arg: DDI.Sealed, Args: DDI.DepHeaders); |
| 45 | } |
| 46 | |
| 47 | static bool serialize(SPSOutputBuffer &OB, |
| 48 | const MachOPlatform::MachOJITDylibDepInfo &DDI) { |
| 49 | return SPSMachOJITDylibDepInfo::AsArgList::serialize(OB, Arg: DDI.Sealed, |
| 50 | Args: DDI.DepHeaders); |
| 51 | } |
| 52 | |
| 53 | static bool deserialize(SPSInputBuffer &IB, |
| 54 | MachOPlatform::MachOJITDylibDepInfo &DDI) { |
| 55 | return SPSMachOJITDylibDepInfo::AsArgList::deserialize(IB, Arg&: DDI.Sealed, |
| 56 | Args&: DDI.DepHeaders); |
| 57 | } |
| 58 | }; |
| 59 | |
| 60 | template <> |
| 61 | class SPSSerializationTraits<SPSMachOExecutorSymbolFlags, |
| 62 | MachOPlatform::MachOExecutorSymbolFlags> { |
| 63 | private: |
| 64 | using UT = std::underlying_type_t<MachOPlatform::MachOExecutorSymbolFlags>; |
| 65 | |
| 66 | public: |
| 67 | static size_t size(const MachOPlatform::MachOExecutorSymbolFlags &SF) { |
| 68 | return sizeof(UT); |
| 69 | } |
| 70 | |
| 71 | static bool serialize(SPSOutputBuffer &OB, |
| 72 | const MachOPlatform::MachOExecutorSymbolFlags &SF) { |
| 73 | return SPSArgList<UT>::serialize(OB, Arg: static_cast<UT>(SF)); |
| 74 | } |
| 75 | |
| 76 | static bool deserialize(SPSInputBuffer &IB, |
| 77 | MachOPlatform::MachOExecutorSymbolFlags &SF) { |
| 78 | UT Tmp; |
| 79 | if (!SPSArgList<UT>::deserialize(IB, Arg&: Tmp)) |
| 80 | return false; |
| 81 | SF = static_cast<MachOPlatform::MachOExecutorSymbolFlags>(Tmp); |
| 82 | return true; |
| 83 | } |
| 84 | }; |
| 85 | |
| 86 | } // namespace shared |
| 87 | } // namespace orc |
| 88 | } // namespace llvm |
| 89 | |
| 90 | namespace { |
| 91 | |
| 92 | using SPSRegisterSymbolsArgs = |
| 93 | SPSArgList<SPSExecutorAddr, |
| 94 | SPSSequence<SPSTuple<SPSExecutorAddr, SPSExecutorAddr, |
| 95 | SPSMachOExecutorSymbolFlags>>>; |
| 96 | |
| 97 | std::unique_ptr<jitlink::LinkGraph> createPlatformGraph(MachOPlatform &MOP, |
| 98 | std::string Name) { |
| 99 | auto &ES = MOP.getExecutionSession(); |
| 100 | return std::make_unique<jitlink::LinkGraph>( |
| 101 | args: std::move(Name), args: ES.getSymbolStringPool(), args: ES.getTargetTriple(), |
| 102 | args: SubtargetFeatures(), args&: jitlink::getGenericEdgeKindName); |
| 103 | } |
| 104 | |
| 105 | // Creates a Bootstrap-Complete LinkGraph to run deferred actions. |
| 106 | class MachOPlatformCompleteBootstrapMaterializationUnit |
| 107 | : public MaterializationUnit { |
| 108 | public: |
| 109 | using SymbolTableVector = |
| 110 | SmallVector<std::tuple<ExecutorAddr, ExecutorAddr, |
| 111 | MachOPlatform::MachOExecutorSymbolFlags>>; |
| 112 | |
| 113 | MachOPlatformCompleteBootstrapMaterializationUnit( |
| 114 | MachOPlatform &MOP, StringRef PlatformJDName, |
| 115 | SymbolStringPtr CompleteBootstrapSymbol, SymbolTableVector SymTab, |
| 116 | shared::AllocActions DeferredAAs, ExecutorAddr , |
| 117 | ExecutorAddr PlatformBootstrap, ExecutorAddr PlatformShutdown, |
| 118 | ExecutorAddr RegisterJITDylib, ExecutorAddr DeregisterJITDylib, |
| 119 | ExecutorAddr RegisterObjectSymbolTable, |
| 120 | ExecutorAddr DeregisterObjectSymbolTable) |
| 121 | : MaterializationUnit( |
| 122 | {{{CompleteBootstrapSymbol, JITSymbolFlags::None}}, nullptr}), |
| 123 | MOP(MOP), PlatformJDName(PlatformJDName), |
| 124 | CompleteBootstrapSymbol(std::move(CompleteBootstrapSymbol)), |
| 125 | SymTab(std::move(SymTab)), DeferredAAs(std::move(DeferredAAs)), |
| 126 | MachOHeaderAddr(MachOHeaderAddr), PlatformBootstrap(PlatformBootstrap), |
| 127 | PlatformShutdown(PlatformShutdown), RegisterJITDylib(RegisterJITDylib), |
| 128 | DeregisterJITDylib(DeregisterJITDylib), |
| 129 | RegisterObjectSymbolTable(RegisterObjectSymbolTable), |
| 130 | DeregisterObjectSymbolTable(DeregisterObjectSymbolTable) {} |
| 131 | |
| 132 | StringRef getName() const override { |
| 133 | return "MachOPlatformCompleteBootstrap" ; |
| 134 | } |
| 135 | |
| 136 | void materialize(std::unique_ptr<MaterializationResponsibility> R) override { |
| 137 | using namespace jitlink; |
| 138 | auto G = createPlatformGraph(MOP, Name: "<OrcRTCompleteBootstrap>" ); |
| 139 | auto &PlaceholderSection = |
| 140 | G->createSection(Name: "__orc_rt_cplt_bs" , Prot: MemProt::Read); |
| 141 | auto &PlaceholderBlock = |
| 142 | G->createZeroFillBlock(Parent&: PlaceholderSection, Size: 1, Address: ExecutorAddr(), Alignment: 1, AlignmentOffset: 0); |
| 143 | G->addDefinedSymbol(Content&: PlaceholderBlock, Offset: 0, Name: *CompleteBootstrapSymbol, Size: 1, |
| 144 | L: Linkage::Strong, S: Scope::Hidden, IsCallable: false, IsLive: true); |
| 145 | |
| 146 | // Reserve space for the stolen actions, plus two extras. |
| 147 | G->allocActions().reserve(n: DeferredAAs.size() + 3); |
| 148 | |
| 149 | // 1. Bootstrap the platform support code. |
| 150 | G->allocActions().push_back( |
| 151 | x: {.Finalize: cantFail(ValOrErr: WrapperFunctionCall::Create<SPSArgList<>>(FnAddr: PlatformBootstrap)), |
| 152 | .Dealloc: cantFail( |
| 153 | ValOrErr: WrapperFunctionCall::Create<SPSArgList<>>(FnAddr: PlatformShutdown))}); |
| 154 | |
| 155 | // 2. Register the platform JITDylib. |
| 156 | G->allocActions().push_back( |
| 157 | x: {.Finalize: cantFail(ValOrErr: WrapperFunctionCall::Create< |
| 158 | SPSArgList<SPSString, SPSExecutorAddr>>( |
| 159 | FnAddr: RegisterJITDylib, Args: PlatformJDName, Args: MachOHeaderAddr)), |
| 160 | .Dealloc: cantFail(ValOrErr: WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>( |
| 161 | FnAddr: DeregisterJITDylib, Args: MachOHeaderAddr))}); |
| 162 | |
| 163 | // 3. Register deferred symbols. |
| 164 | G->allocActions().push_back( |
| 165 | x: {.Finalize: cantFail(ValOrErr: WrapperFunctionCall::Create<SPSRegisterSymbolsArgs>( |
| 166 | FnAddr: RegisterObjectSymbolTable, Args: MachOHeaderAddr, Args: SymTab)), |
| 167 | .Dealloc: cantFail(ValOrErr: WrapperFunctionCall::Create<SPSRegisterSymbolsArgs>( |
| 168 | FnAddr: DeregisterObjectSymbolTable, Args: MachOHeaderAddr, Args: SymTab))}); |
| 169 | |
| 170 | // 4. Add the deferred actions to the graph. |
| 171 | std::move(first: DeferredAAs.begin(), last: DeferredAAs.end(), |
| 172 | result: std::back_inserter(x&: G->allocActions())); |
| 173 | |
| 174 | MOP.getObjectLinkingLayer().emit(R: std::move(R), G: std::move(G)); |
| 175 | } |
| 176 | |
| 177 | void discard(const JITDylib &JD, const SymbolStringPtr &Sym) override {} |
| 178 | |
| 179 | private: |
| 180 | MachOPlatform &MOP; |
| 181 | StringRef PlatformJDName; |
| 182 | SymbolStringPtr CompleteBootstrapSymbol; |
| 183 | SymbolTableVector SymTab; |
| 184 | shared::AllocActions DeferredAAs; |
| 185 | ExecutorAddr ; |
| 186 | ExecutorAddr PlatformBootstrap; |
| 187 | ExecutorAddr PlatformShutdown; |
| 188 | ExecutorAddr RegisterJITDylib; |
| 189 | ExecutorAddr DeregisterJITDylib; |
| 190 | ExecutorAddr RegisterObjectSymbolTable; |
| 191 | ExecutorAddr DeregisterObjectSymbolTable; |
| 192 | }; |
| 193 | |
| 194 | static StringRef ObjCRuntimeObjectSectionsData[] = { |
| 195 | MachOObjCCatListSectionName, MachOObjCCatList2SectionName, |
| 196 | MachOObjCClassListSectionName, MachOObjCClassRefsSectionName, |
| 197 | MachOObjCConstSectionName, MachOObjCDataSectionName, |
| 198 | MachOObjCProtoListSectionName, MachOObjCProtoRefsSectionName, |
| 199 | MachOObjCNLCatListSectionName, MachOObjCNLClassListSectionName, |
| 200 | MachOObjCSelRefsSectionName}; |
| 201 | |
| 202 | static StringRef ObjCRuntimeObjectSectionsText[] = { |
| 203 | MachOObjCClassNameSectionName, MachOObjCMethNameSectionName, |
| 204 | MachOObjCMethTypeSectionName, MachOSwift5TypesSectionName, |
| 205 | MachOSwift5TypeRefSectionName, MachOSwift5FieldMetadataSectionName, |
| 206 | MachOSwift5EntrySectionName, MachOSwift5ProtoSectionName, |
| 207 | MachOSwift5ProtosSectionName}; |
| 208 | |
| 209 | static StringRef ObjCRuntimeObjectSectionName = |
| 210 | "__llvm_jitlink_ObjCRuntimeRegistrationObject" ; |
| 211 | |
| 212 | static StringRef ObjCImageInfoSymbolName = |
| 213 | "__llvm_jitlink_macho_objc_imageinfo" ; |
| 214 | |
| 215 | struct ObjCImageInfoFlags { |
| 216 | uint16_t SwiftABIVersion; |
| 217 | uint16_t SwiftVersion; |
| 218 | bool HasCategoryClassProperties; |
| 219 | bool HasSignedObjCClassROs; |
| 220 | |
| 221 | static constexpr uint32_t SIGNED_CLASS_RO = (1 << 4); |
| 222 | static constexpr uint32_t HAS_CATEGORY_CLASS_PROPERTIES = (1 << 6); |
| 223 | |
| 224 | explicit ObjCImageInfoFlags(uint32_t RawFlags) { |
| 225 | HasSignedObjCClassROs = RawFlags & SIGNED_CLASS_RO; |
| 226 | HasCategoryClassProperties = RawFlags & HAS_CATEGORY_CLASS_PROPERTIES; |
| 227 | SwiftABIVersion = (RawFlags >> 8) & 0xFF; |
| 228 | SwiftVersion = (RawFlags >> 16) & 0xFFFF; |
| 229 | } |
| 230 | |
| 231 | uint32_t rawFlags() const { |
| 232 | uint32_t Result = 0; |
| 233 | if (HasCategoryClassProperties) |
| 234 | Result |= HAS_CATEGORY_CLASS_PROPERTIES; |
| 235 | if (HasSignedObjCClassROs) |
| 236 | Result |= SIGNED_CLASS_RO; |
| 237 | Result |= (SwiftABIVersion << 8); |
| 238 | Result |= (SwiftVersion << 16); |
| 239 | return Result; |
| 240 | } |
| 241 | }; |
| 242 | } // end anonymous namespace |
| 243 | |
| 244 | namespace llvm { |
| 245 | namespace orc { |
| 246 | |
| 247 | std::optional<MachOPlatform::HeaderOptions::BuildVersionOpts> |
| 248 | MachOPlatform::HeaderOptions::BuildVersionOpts::(const Triple &TT, |
| 249 | uint32_t MinOS, |
| 250 | uint32_t SDK) { |
| 251 | |
| 252 | uint32_t Platform; |
| 253 | switch (TT.getOS()) { |
| 254 | case Triple::IOS: |
| 255 | Platform = TT.isSimulatorEnvironment() ? MachO::PLATFORM_IOSSIMULATOR |
| 256 | : MachO::PLATFORM_IOS; |
| 257 | break; |
| 258 | case Triple::MacOSX: |
| 259 | Platform = MachO::PLATFORM_MACOS; |
| 260 | break; |
| 261 | case Triple::TvOS: |
| 262 | Platform = TT.isSimulatorEnvironment() ? MachO::PLATFORM_TVOSSIMULATOR |
| 263 | : MachO::PLATFORM_TVOS; |
| 264 | break; |
| 265 | case Triple::WatchOS: |
| 266 | Platform = TT.isSimulatorEnvironment() ? MachO::PLATFORM_WATCHOSSIMULATOR |
| 267 | : MachO::PLATFORM_WATCHOS; |
| 268 | break; |
| 269 | case Triple::XROS: |
| 270 | Platform = TT.isSimulatorEnvironment() ? MachO::PLATFORM_XROS_SIMULATOR |
| 271 | : MachO::PLATFORM_XROS; |
| 272 | break; |
| 273 | default: |
| 274 | return std::nullopt; |
| 275 | } |
| 276 | |
| 277 | return MachOPlatform::HeaderOptions::BuildVersionOpts{.Platform: Platform, .MinOS: MinOS, .SDK: SDK}; |
| 278 | } |
| 279 | |
| 280 | Expected<std::unique_ptr<MachOPlatform>> |
| 281 | MachOPlatform::Create(ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD, |
| 282 | std::unique_ptr<DefinitionGenerator> OrcRuntime, |
| 283 | HeaderOptionsBuilder , |
| 284 | HeaderOptions PlatformJDOpts, |
| 285 | MachOHeaderMUBuilder , |
| 286 | std::optional<SymbolAliasMap> RuntimeAliases) { |
| 287 | |
| 288 | auto &ES = ObjLinkingLayer.getExecutionSession(); |
| 289 | |
| 290 | // If the target is not supported then bail out immediately. |
| 291 | if (!supportedTarget(TT: ES.getTargetTriple())) |
| 292 | return make_error<StringError>(Args: "Unsupported MachOPlatform triple: " + |
| 293 | ES.getTargetTriple().str(), |
| 294 | Args: inconvertibleErrorCode()); |
| 295 | |
| 296 | // Create default aliases if the caller didn't supply any. |
| 297 | if (!RuntimeAliases) |
| 298 | RuntimeAliases = standardPlatformAliases(ES); |
| 299 | |
| 300 | // Define the aliases. |
| 301 | if (auto Err = PlatformJD.define(MU: symbolAliases(Aliases: std::move(*RuntimeAliases)))) |
| 302 | return std::move(Err); |
| 303 | |
| 304 | { |
| 305 | // Add JIT dispatch reexports from bootstrap JITDylib. |
| 306 | if (auto Err = PlatformJD.define(MU: reexports( |
| 307 | SourceJD&: ES.getBootstrapJITDylib(), |
| 308 | Aliases: {{ES.intern(SymName: "___orc_rt_jit_dispatch" ), |
| 309 | {ES.intern(SymName: rt::DispatchName), |
| 310 | JITSymbolFlags::Exported | JITSymbolFlags::Callable}}, |
| 311 | {ES.intern(SymName: "___orc_rt_jit_dispatch_ctx" ), |
| 312 | {ES.intern(SymName: rt::DispatchCtxName), JITSymbolFlags::Exported}}}))) |
| 313 | return Err; |
| 314 | } |
| 315 | |
| 316 | // Create the instance. |
| 317 | Error Err = Error::success(); |
| 318 | auto P = std::unique_ptr<MachOPlatform>( |
| 319 | new MachOPlatform(ObjLinkingLayer, PlatformJD, std::move(OrcRuntime), |
| 320 | std::move(BuildHeaderOpts), std::move(PlatformJDOpts), |
| 321 | std::move(BuildMachOHeaderMU), Err)); |
| 322 | if (Err) |
| 323 | return std::move(Err); |
| 324 | return std::move(P); |
| 325 | } |
| 326 | |
| 327 | Expected<std::unique_ptr<MachOPlatform>> MachOPlatform::( |
| 328 | ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD, |
| 329 | const char *OrcRuntimePath, HeaderOptionsBuilder , |
| 330 | HeaderOptions PlatformJDOpts, MachOHeaderMUBuilder , |
| 331 | std::optional<SymbolAliasMap> RuntimeAliases) { |
| 332 | |
| 333 | // Create a generator for the ORC runtime archive. |
| 334 | auto OrcRuntimeArchiveGenerator = |
| 335 | StaticLibraryDefinitionGenerator::Load(L&: ObjLinkingLayer, FileName: OrcRuntimePath); |
| 336 | if (!OrcRuntimeArchiveGenerator) |
| 337 | return OrcRuntimeArchiveGenerator.takeError(); |
| 338 | |
| 339 | return Create(ObjLinkingLayer, PlatformJD, |
| 340 | OrcRuntime: std::move(*OrcRuntimeArchiveGenerator), |
| 341 | BuildHeaderOpts: std::move(BuildHeaderOpts), PlatformJDOpts: std::move(PlatformJDOpts), |
| 342 | BuildMachOHeaderMU: std::move(BuildMachOHeaderMU), RuntimeAliases: std::move(RuntimeAliases)); |
| 343 | } |
| 344 | |
| 345 | Error MachOPlatform::setupJITDylib(JITDylib &JD) { |
| 346 | return setupJITDylib(JD, Opts: BuildHeaderOpts(JD)); |
| 347 | } |
| 348 | |
| 349 | Error MachOPlatform::(JITDylib &JD, HeaderOptions Opts) { |
| 350 | if (auto Err = JD.define(MU: BuildMachOHeaderMU(*this, std::move(Opts)))) |
| 351 | return Err; |
| 352 | |
| 353 | return ES.lookup(SearchOrder: {&JD}, Symbol: MachOHeaderStartSymbol).takeError(); |
| 354 | } |
| 355 | |
| 356 | Error MachOPlatform::teardownJITDylib(JITDylib &JD) { |
| 357 | std::lock_guard<std::mutex> Lock(PlatformMutex); |
| 358 | auto I = JITDylibToHeaderAddr.find(Val: &JD); |
| 359 | if (I != JITDylibToHeaderAddr.end()) { |
| 360 | assert(HeaderAddrToJITDylib.count(I->second) && |
| 361 | "HeaderAddrToJITDylib missing entry" ); |
| 362 | HeaderAddrToJITDylib.erase(Val: I->second); |
| 363 | JITDylibToHeaderAddr.erase(I); |
| 364 | } |
| 365 | JITDylibToPThreadKey.erase(Val: &JD); |
| 366 | return Error::success(); |
| 367 | } |
| 368 | |
| 369 | Error MachOPlatform::notifyAdding(ResourceTracker &RT, |
| 370 | const MaterializationUnit &MU) { |
| 371 | auto &JD = RT.getJITDylib(); |
| 372 | const auto &InitSym = MU.getInitializerSymbol(); |
| 373 | if (!InitSym) |
| 374 | return Error::success(); |
| 375 | |
| 376 | RegisteredInitSymbols[&JD].add(Name: InitSym, |
| 377 | Flags: SymbolLookupFlags::WeaklyReferencedSymbol); |
| 378 | LLVM_DEBUG({ |
| 379 | dbgs() << "MachOPlatform: Registered init symbol " << *InitSym << " for MU " |
| 380 | << MU.getName() << "\n" ; |
| 381 | }); |
| 382 | return Error::success(); |
| 383 | } |
| 384 | |
| 385 | Error MachOPlatform::notifyRemoving(ResourceTracker &RT) { |
| 386 | llvm_unreachable("Not supported yet" ); |
| 387 | } |
| 388 | |
| 389 | static void addAliases(ExecutionSession &ES, SymbolAliasMap &Aliases, |
| 390 | ArrayRef<std::pair<const char *, const char *>> AL) { |
| 391 | for (auto &KV : AL) { |
| 392 | auto AliasName = ES.intern(SymName: KV.first); |
| 393 | assert(!Aliases.count(AliasName) && "Duplicate symbol name in alias map" ); |
| 394 | Aliases[std::move(AliasName)] = {ES.intern(SymName: KV.second), |
| 395 | JITSymbolFlags::Exported}; |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | SymbolAliasMap MachOPlatform::standardPlatformAliases(ExecutionSession &ES) { |
| 400 | SymbolAliasMap Aliases; |
| 401 | addAliases(ES, Aliases, AL: requiredCXXAliases()); |
| 402 | addAliases(ES, Aliases, AL: standardRuntimeUtilityAliases()); |
| 403 | addAliases(ES, Aliases, AL: standardLazyCompilationAliases()); |
| 404 | return Aliases; |
| 405 | } |
| 406 | |
| 407 | ArrayRef<std::pair<const char *, const char *>> |
| 408 | MachOPlatform::requiredCXXAliases() { |
| 409 | static const std::pair<const char *, const char *> RequiredCXXAliases[] = { |
| 410 | {"___cxa_atexit" , "___orc_rt_macho_cxa_atexit" }}; |
| 411 | |
| 412 | return ArrayRef<std::pair<const char *, const char *>>(RequiredCXXAliases); |
| 413 | } |
| 414 | |
| 415 | ArrayRef<std::pair<const char *, const char *>> |
| 416 | MachOPlatform::standardRuntimeUtilityAliases() { |
| 417 | static const std::pair<const char *, const char *> |
| 418 | StandardRuntimeUtilityAliases[] = { |
| 419 | {"___orc_rt_run_program" , "___orc_rt_macho_run_program" }, |
| 420 | {"___orc_rt_jit_dlerror" , "___orc_rt_macho_jit_dlerror" }, |
| 421 | {"___orc_rt_jit_dlopen" , "___orc_rt_macho_jit_dlopen" }, |
| 422 | {"___orc_rt_jit_dlupdate" , "___orc_rt_macho_jit_dlupdate" }, |
| 423 | {"___orc_rt_jit_dlclose" , "___orc_rt_macho_jit_dlclose" }, |
| 424 | {"___orc_rt_jit_dlsym" , "___orc_rt_macho_jit_dlsym" }, |
| 425 | {"___orc_rt_log_error" , "___orc_rt_log_error_to_stderr" }}; |
| 426 | |
| 427 | return ArrayRef<std::pair<const char *, const char *>>( |
| 428 | StandardRuntimeUtilityAliases); |
| 429 | } |
| 430 | |
| 431 | ArrayRef<std::pair<const char *, const char *>> |
| 432 | MachOPlatform::standardLazyCompilationAliases() { |
| 433 | static const std::pair<const char *, const char *> |
| 434 | StandardLazyCompilationAliases[] = { |
| 435 | {"__orc_rt_reenter" , "__orc_rt_sysv_reenter" }, |
| 436 | {"__orc_rt_resolve_tag" , "___orc_rt_resolve_tag" }}; |
| 437 | |
| 438 | return ArrayRef<std::pair<const char *, const char *>>( |
| 439 | StandardLazyCompilationAliases); |
| 440 | } |
| 441 | |
| 442 | MachOPlatform::HeaderOptions MachOPlatform::(JITDylib &JD) { |
| 443 | return {}; |
| 444 | } |
| 445 | |
| 446 | bool MachOPlatform::supportedTarget(const Triple &TT) { |
| 447 | switch (TT.getArch()) { |
| 448 | case Triple::aarch64: |
| 449 | case Triple::x86_64: |
| 450 | return true; |
| 451 | default: |
| 452 | return false; |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | jitlink::Edge::Kind MachOPlatform::getPointerEdgeKind(jitlink::LinkGraph &G) { |
| 457 | switch (G.getTargetTriple().getArch()) { |
| 458 | case Triple::aarch64: |
| 459 | return jitlink::aarch64::Pointer64; |
| 460 | case Triple::x86_64: |
| 461 | return jitlink::x86_64::Pointer64; |
| 462 | default: |
| 463 | llvm_unreachable("Unsupported architecture" ); |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | MachOPlatform::MachOExecutorSymbolFlags |
| 468 | MachOPlatform::flagsForSymbol(jitlink::Symbol &Sym) { |
| 469 | MachOPlatform::MachOExecutorSymbolFlags Flags{}; |
| 470 | if (Sym.getLinkage() == jitlink::Linkage::Weak) |
| 471 | Flags |= MachOExecutorSymbolFlags::Weak; |
| 472 | |
| 473 | if (Sym.isCallable()) |
| 474 | Flags |= MachOExecutorSymbolFlags::Callable; |
| 475 | |
| 476 | return Flags; |
| 477 | } |
| 478 | |
| 479 | MachOPlatform::MachOPlatform( |
| 480 | ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD, |
| 481 | std::unique_ptr<DefinitionGenerator> OrcRuntimeGenerator, |
| 482 | HeaderOptionsBuilder , HeaderOptions PlatformJDOpts, |
| 483 | MachOHeaderMUBuilder , Error &Err) |
| 484 | : ES(ObjLinkingLayer.getExecutionSession()), PlatformJD(PlatformJD), |
| 485 | ObjLinkingLayer(ObjLinkingLayer), |
| 486 | BuildHeaderOpts(std::move(BuildHeaderOpts)), |
| 487 | BuildMachOHeaderMU(std::move(BuildMachOHeaderMU)) { |
| 488 | ErrorAsOutParameter _(Err); |
| 489 | ObjLinkingLayer.addPlugin(P: std::make_unique<MachOPlatformPlugin>(args&: *this)); |
| 490 | PlatformJD.addGenerator(DefGenerator: std::move(OrcRuntimeGenerator)); |
| 491 | |
| 492 | { |
| 493 | // Check for force-eh-frame |
| 494 | std::optional<bool> ForceEHFrames; |
| 495 | if ((Err = ES.getBootstrapMapValue<bool, bool>(Key: "darwin-use-ehframes-only" , |
| 496 | Val&: ForceEHFrames))) |
| 497 | return; |
| 498 | this->ForceEHFrames = ForceEHFrames.value_or(u: false); |
| 499 | } |
| 500 | |
| 501 | BootstrapInfo BI; |
| 502 | Bootstrap = &BI; |
| 503 | |
| 504 | // Bootstrap process -- here be phase-ordering dragons. |
| 505 | // |
| 506 | // The MachOPlatform class uses allocation actions to register metadata |
| 507 | // sections with the ORC runtime, however the runtime contains metadata |
| 508 | // registration functions that have their own metadata that they need to |
| 509 | // register (e.g. the frame-info registration functions have frame-info). |
| 510 | // We can't use an ordinary lookup to find these registration functions |
| 511 | // because their address is needed during the link of the containing graph |
| 512 | // itself (to build the allocation actions that will call the registration |
| 513 | // functions). Further complicating the situation (a) the graph containing |
| 514 | // the registration functions is allowed to depend on other graphs (e.g. the |
| 515 | // graph containing the ORC runtime RTTI support) so we need to handle an |
| 516 | // unknown set of dependencies during bootstrap, and (b) these graphs may |
| 517 | // be linked concurrently if the user has installed a concurrent dispatcher. |
| 518 | // |
| 519 | // We satisfy these constraints by implementing a bootstrap phase during which |
| 520 | // allocation actions generated by MachOPlatform are appended to a list of |
| 521 | // deferred allocation actions, rather than to the graphs themselves. At the |
| 522 | // end of the bootstrap process the deferred actions are attached to a final |
| 523 | // "complete-bootstrap" graph that causes them to be run. |
| 524 | // |
| 525 | // The bootstrap steps are as follows: |
| 526 | // |
| 527 | // 1. Request the graph containing the mach header. This graph is guaranteed |
| 528 | // not to have any metadata so the fact that the registration functions |
| 529 | // are not available yet is not a problem. |
| 530 | // |
| 531 | // 2. Look up the registration functions and discard the results. This will |
| 532 | // trigger linking of the graph containing these functions, and |
| 533 | // consequently any graphs that it depends on. We do not use the lookup |
| 534 | // result to find the addresses of the functions requested (as described |
| 535 | // above the lookup will return too late for that), instead we capture the |
| 536 | // addresses in a post-allocation pass injected by the platform runtime |
| 537 | // during bootstrap only. |
| 538 | // |
| 539 | // 3. During bootstrap the MachOPlatformPlugin keeps a count of the number of |
| 540 | // graphs being linked (potentially concurrently), and we block until all |
| 541 | // of these graphs have completed linking. This is to avoid a race on the |
| 542 | // deferred-actions vector: the lookup for the runtime registration |
| 543 | // functions may return while some functions (those that are being |
| 544 | // incidentally linked in, but aren't reachable via the runtime functions) |
| 545 | // are still being linked, and we need to capture any allocation actions |
| 546 | // for this incidental code before we proceed. |
| 547 | // |
| 548 | // 4. Once all active links are complete we transfer the deferred actions to |
| 549 | // a newly added CompleteBootstrap graph and then request a symbol from |
| 550 | // the CompleteBootstrap graph to trigger materialization. This will cause |
| 551 | // all deferred actions to be run, and once this lookup returns we can |
| 552 | // proceed. |
| 553 | // |
| 554 | // 5. Finally, we associate runtime support methods in MachOPlatform with |
| 555 | // the corresponding jit-dispatch tag variables in the ORC runtime to make |
| 556 | // the support methods callable. The bootstrap is now complete. |
| 557 | |
| 558 | // Step (1) Add header materialization unit and request. |
| 559 | if ((Err = PlatformJD.define( |
| 560 | MU: this->BuildMachOHeaderMU(*this, std::move(PlatformJDOpts))))) |
| 561 | return; |
| 562 | if ((Err = ES.lookup(SearchOrder: &PlatformJD, Symbol: MachOHeaderStartSymbol).takeError())) |
| 563 | return; |
| 564 | |
| 565 | // Step (2) Request runtime registration functions to trigger |
| 566 | // materialization.. |
| 567 | if ((Err = ES.lookup(SearchOrder: makeJITDylibSearchOrder(JDs: &PlatformJD), |
| 568 | Symbols: SymbolLookupSet( |
| 569 | {PlatformBootstrap.Name, PlatformShutdown.Name, |
| 570 | RegisterJITDylib.Name, DeregisterJITDylib.Name, |
| 571 | RegisterObjectSymbolTable.Name, |
| 572 | DeregisterObjectSymbolTable.Name, |
| 573 | RegisterObjectPlatformSections.Name, |
| 574 | DeregisterObjectPlatformSections.Name, |
| 575 | CreatePThreadKey.Name})) |
| 576 | .takeError())) |
| 577 | return; |
| 578 | |
| 579 | // Step (3) Wait for any incidental linker work to complete. |
| 580 | { |
| 581 | std::unique_lock<std::mutex> Lock(PlatformMutex); |
| 582 | BI.CV.wait(lock&: Lock, p: [&]() { return BI.ActiveGraphs == 0; }); |
| 583 | Bootstrap = nullptr; |
| 584 | } |
| 585 | |
| 586 | // Step (4) Add complete-bootstrap materialization unit and request. |
| 587 | auto BootstrapCompleteSymbol = ES.intern(SymName: "__orc_rt_macho_complete_bootstrap" ); |
| 588 | if ((Err = PlatformJD.define( |
| 589 | MU: std::make_unique<MachOPlatformCompleteBootstrapMaterializationUnit>( |
| 590 | args&: *this, args: PlatformJD.getName(), args&: BootstrapCompleteSymbol, |
| 591 | args: std::move(BI.SymTab), args: std::move(BI.DeferredAAs), |
| 592 | args&: BI.MachOHeaderAddr, args&: PlatformBootstrap.Addr, |
| 593 | args&: PlatformShutdown.Addr, args&: RegisterJITDylib.Addr, |
| 594 | args&: DeregisterJITDylib.Addr, args&: RegisterObjectSymbolTable.Addr, |
| 595 | args&: DeregisterObjectSymbolTable.Addr)))) |
| 596 | return; |
| 597 | if ((Err = ES.lookup(SearchOrder: makeJITDylibSearchOrder( |
| 598 | JDs: &PlatformJD, Flags: JITDylibLookupFlags::MatchAllSymbols), |
| 599 | Symbol: std::move(BootstrapCompleteSymbol)) |
| 600 | .takeError())) |
| 601 | return; |
| 602 | |
| 603 | // (5) Associate runtime support functions. |
| 604 | // TODO: Consider moving this above (4) to make runtime support functions |
| 605 | // available to the bootstrap completion graph. We'd just need to be |
| 606 | // sure that the runtime support functions are fully usable before any |
| 607 | // bootstrap completion actions use them (e.g. the ORC runtime |
| 608 | // macho_platform object would have to have been created and |
| 609 | // initialized). |
| 610 | if ((Err = associateRuntimeSupportFunctions())) |
| 611 | return; |
| 612 | } |
| 613 | |
| 614 | Error MachOPlatform::associateRuntimeSupportFunctions() { |
| 615 | ExecutionSession::JITDispatchHandlerAssociationMap WFs; |
| 616 | |
| 617 | using = |
| 618 | SPSExpected<SPSMachOJITDylibDepInfoMap>(SPSExecutorAddr); |
| 619 | WFs[ES.intern(SymName: "___orc_rt_macho_push_initializers_tag" )] = |
| 620 | ES.wrapAsyncWithSPS<PushInitializersSPSSig>( |
| 621 | Instance: this, Method: &MachOPlatform::rt_pushInitializers); |
| 622 | |
| 623 | using PushSymbolsSPSSig = |
| 624 | SPSError(SPSExecutorAddr, SPSSequence<SPSTuple<SPSString, bool>>); |
| 625 | WFs[ES.intern(SymName: "___orc_rt_macho_push_symbols_tag" )] = |
| 626 | ES.wrapAsyncWithSPS<PushSymbolsSPSSig>(Instance: this, |
| 627 | Method: &MachOPlatform::rt_pushSymbols); |
| 628 | |
| 629 | return ES.registerJITDispatchHandlers(JD&: PlatformJD, WFs: std::move(WFs)); |
| 630 | } |
| 631 | |
| 632 | void MachOPlatform::pushInitializersLoop( |
| 633 | PushInitializersSendResultFn SendResult, JITDylibSP JD) { |
| 634 | DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols; |
| 635 | DenseMap<JITDylib *, SmallVector<JITDylib *>> JDDepMap; |
| 636 | SmallVector<JITDylib *, 16> Worklist({JD.get()}); |
| 637 | |
| 638 | ES.runSessionLocked(F: [&]() { |
| 639 | while (!Worklist.empty()) { |
| 640 | // FIXME: Check for defunct dylibs. |
| 641 | |
| 642 | auto DepJD = Worklist.back(); |
| 643 | Worklist.pop_back(); |
| 644 | |
| 645 | // If we've already visited this JITDylib on this iteration then continue. |
| 646 | auto [It, Inserted] = JDDepMap.try_emplace(Key: DepJD); |
| 647 | if (!Inserted) |
| 648 | continue; |
| 649 | |
| 650 | // Add dep info. |
| 651 | auto &DM = It->second; |
| 652 | DepJD->withLinkOrderDo(F: [&](const JITDylibSearchOrder &O) { |
| 653 | for (auto &KV : O) { |
| 654 | if (KV.first == DepJD) |
| 655 | continue; |
| 656 | DM.push_back(Elt: KV.first); |
| 657 | Worklist.push_back(Elt: KV.first); |
| 658 | } |
| 659 | }); |
| 660 | |
| 661 | // Add any registered init symbols. |
| 662 | auto RISItr = RegisteredInitSymbols.find(Val: DepJD); |
| 663 | if (RISItr != RegisteredInitSymbols.end()) { |
| 664 | NewInitSymbols[DepJD] = std::move(RISItr->second); |
| 665 | RegisteredInitSymbols.erase(I: RISItr); |
| 666 | } |
| 667 | } |
| 668 | }); |
| 669 | |
| 670 | // If there are no further init symbols to look up then send the link order |
| 671 | // (as a list of header addresses) to the caller. |
| 672 | if (NewInitSymbols.empty()) { |
| 673 | |
| 674 | // To make the list intelligible to the runtime we need to convert all |
| 675 | // JITDylib pointers to their header addresses. Only include JITDylibs |
| 676 | // that appear in the JITDylibToHeaderAddr map (i.e. those that have been |
| 677 | // through setupJITDylib) -- bare JITDylibs aren't managed by the platform. |
| 678 | DenseMap<JITDylib *, ExecutorAddr> ; |
| 679 | HeaderAddrs.reserve(NumEntries: JDDepMap.size()); |
| 680 | { |
| 681 | std::lock_guard<std::mutex> Lock(PlatformMutex); |
| 682 | for (auto &KV : JDDepMap) { |
| 683 | auto I = JITDylibToHeaderAddr.find(Val: KV.first); |
| 684 | if (I != JITDylibToHeaderAddr.end()) |
| 685 | HeaderAddrs[KV.first] = I->second; |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | // Build the dep info map to return. |
| 690 | MachOJITDylibDepInfoMap DIM; |
| 691 | DIM.reserve(n: JDDepMap.size()); |
| 692 | for (auto &KV : JDDepMap) { |
| 693 | auto HI = HeaderAddrs.find(Val: KV.first); |
| 694 | // Skip unmanaged JITDylibs. |
| 695 | if (HI == HeaderAddrs.end()) |
| 696 | continue; |
| 697 | auto H = HI->second; |
| 698 | MachOJITDylibDepInfo DepInfo; |
| 699 | for (auto &Dep : KV.second) { |
| 700 | auto HJ = HeaderAddrs.find(Val: Dep); |
| 701 | if (HJ != HeaderAddrs.end()) |
| 702 | DepInfo.DepHeaders.push_back(x: HJ->second); |
| 703 | } |
| 704 | DIM.push_back(x: std::make_pair(x&: H, y: std::move(DepInfo))); |
| 705 | } |
| 706 | SendResult(DIM); |
| 707 | return; |
| 708 | } |
| 709 | |
| 710 | // Otherwise issue a lookup and re-run this phase when it completes. |
| 711 | lookupInitSymbolsAsync( |
| 712 | OnComplete: [this, SendResult = std::move(SendResult), JD](Error Err) mutable { |
| 713 | if (Err) |
| 714 | SendResult(std::move(Err)); |
| 715 | else |
| 716 | pushInitializersLoop(SendResult: std::move(SendResult), JD); |
| 717 | }, |
| 718 | ES, InitSyms: std::move(NewInitSymbols)); |
| 719 | } |
| 720 | |
| 721 | void MachOPlatform::rt_pushInitializers(PushInitializersSendResultFn SendResult, |
| 722 | ExecutorAddr ) { |
| 723 | JITDylibSP JD; |
| 724 | { |
| 725 | std::lock_guard<std::mutex> Lock(PlatformMutex); |
| 726 | auto I = HeaderAddrToJITDylib.find(Val: JDHeaderAddr); |
| 727 | if (I != HeaderAddrToJITDylib.end()) |
| 728 | JD = I->second; |
| 729 | } |
| 730 | |
| 731 | LLVM_DEBUG({ |
| 732 | dbgs() << "MachOPlatform::rt_pushInitializers(" << JDHeaderAddr << ") " ; |
| 733 | if (JD) |
| 734 | dbgs() << "pushing initializers for " << JD->getName() << "\n" ; |
| 735 | else |
| 736 | dbgs() << "No JITDylib for header address.\n" ; |
| 737 | }); |
| 738 | |
| 739 | if (!JD) { |
| 740 | SendResult(make_error<StringError>(Args: "No JITDylib with header addr " + |
| 741 | formatv(Fmt: "{0:x}" , Vals&: JDHeaderAddr), |
| 742 | Args: inconvertibleErrorCode())); |
| 743 | return; |
| 744 | } |
| 745 | |
| 746 | pushInitializersLoop(SendResult: std::move(SendResult), JD); |
| 747 | } |
| 748 | |
| 749 | void MachOPlatform::rt_pushSymbols( |
| 750 | PushSymbolsInSendResultFn SendResult, ExecutorAddr Handle, |
| 751 | const std::vector<std::pair<StringRef, bool>> &SymbolNames) { |
| 752 | |
| 753 | JITDylib *JD = nullptr; |
| 754 | |
| 755 | { |
| 756 | std::lock_guard<std::mutex> Lock(PlatformMutex); |
| 757 | auto I = HeaderAddrToJITDylib.find(Val: Handle); |
| 758 | if (I != HeaderAddrToJITDylib.end()) |
| 759 | JD = I->second; |
| 760 | } |
| 761 | LLVM_DEBUG({ |
| 762 | dbgs() << "MachOPlatform::rt_pushSymbols(" ; |
| 763 | if (JD) |
| 764 | dbgs() << "\"" << JD->getName() << "\", [ " ; |
| 765 | else |
| 766 | dbgs() << "<invalid handle " << Handle << ">, [ " ; |
| 767 | for (auto &Name : SymbolNames) |
| 768 | dbgs() << "\"" << Name.first << "\" " ; |
| 769 | dbgs() << "])\n" ; |
| 770 | }); |
| 771 | |
| 772 | if (!JD) { |
| 773 | SendResult(make_error<StringError>(Args: "No JITDylib associated with handle " + |
| 774 | formatv(Fmt: "{0:x}" , Vals&: Handle), |
| 775 | Args: inconvertibleErrorCode())); |
| 776 | return; |
| 777 | } |
| 778 | |
| 779 | SymbolLookupSet LS; |
| 780 | for (auto &[Name, Required] : SymbolNames) |
| 781 | LS.add(Name: ES.intern(SymName: Name), Flags: Required |
| 782 | ? SymbolLookupFlags::RequiredSymbol |
| 783 | : SymbolLookupFlags::WeaklyReferencedSymbol); |
| 784 | |
| 785 | ES.lookup( |
| 786 | K: LookupKind::DLSym, SearchOrder: {{JD, JITDylibLookupFlags::MatchExportedSymbolsOnly}}, |
| 787 | Symbols: std::move(LS), RequiredState: SymbolState::Ready, |
| 788 | NotifyComplete: [SendResult = std::move(SendResult)](Expected<SymbolMap> Result) mutable { |
| 789 | SendResult(Result.takeError()); |
| 790 | }, |
| 791 | RegisterDependencies: NoDependenciesToRegister); |
| 792 | } |
| 793 | |
| 794 | Expected<uint64_t> MachOPlatform::createPThreadKey() { |
| 795 | if (!CreatePThreadKey.Addr) |
| 796 | return make_error<StringError>( |
| 797 | Args: "Attempting to create pthread key in target, but runtime support has " |
| 798 | "not been loaded yet" , |
| 799 | Args: inconvertibleErrorCode()); |
| 800 | |
| 801 | Expected<uint64_t> Result(0); |
| 802 | if (auto Err = ES.callSPSWrapper<SPSExpected<uint64_t>(void)>( |
| 803 | WrapperFnAddr: CreatePThreadKey.Addr, WrapperCallArgs&: Result)) |
| 804 | return std::move(Err); |
| 805 | return Result; |
| 806 | } |
| 807 | |
| 808 | void MachOPlatform::MachOPlatformPlugin::modifyPassConfig( |
| 809 | MaterializationResponsibility &MR, jitlink::LinkGraph &LG, |
| 810 | jitlink::PassConfiguration &Config) { |
| 811 | |
| 812 | using namespace jitlink; |
| 813 | |
| 814 | bool InBootstrapPhase = false; |
| 815 | |
| 816 | ExecutorAddr ; |
| 817 | { |
| 818 | std::lock_guard<std::mutex> Lock(MP.PlatformMutex); |
| 819 | if (LLVM_UNLIKELY(&MR.getTargetJITDylib() == &MP.PlatformJD)) { |
| 820 | if (MP.Bootstrap) { |
| 821 | InBootstrapPhase = true; |
| 822 | ++MP.Bootstrap->ActiveGraphs; |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | // Get the dso-base address if available. |
| 827 | auto I = MP.JITDylibToHeaderAddr.find(Val: &MR.getTargetJITDylib()); |
| 828 | if (I != MP.JITDylibToHeaderAddr.end()) |
| 829 | HeaderAddr = I->second; |
| 830 | } |
| 831 | |
| 832 | // If we're forcing eh-frame use then discard the compact-unwind section |
| 833 | // immediately to prevent FDEs from being stripped. |
| 834 | if (MP.ForceEHFrames) |
| 835 | if (auto *CUSec = LG.findSectionByName(Name: MachOCompactUnwindSectionName)) |
| 836 | LG.removeSection(Sec&: *CUSec); |
| 837 | |
| 838 | // Point the libunwind dso-base absolute symbol at the header for the |
| 839 | // JITDylib. This will prevent us from synthesizing a new header for |
| 840 | // every object. |
| 841 | if (HeaderAddr) |
| 842 | LG.addAbsoluteSymbol(Name: "__jitlink$libunwind_dso_base" , Address: HeaderAddr, Size: 0, |
| 843 | L: Linkage::Strong, S: Scope::Local, IsLive: true); |
| 844 | |
| 845 | // If we're in the bootstrap phase then increment the active graphs. |
| 846 | if (LLVM_UNLIKELY(InBootstrapPhase)) |
| 847 | Config.PostAllocationPasses.push_back(x: [this](LinkGraph &G) { |
| 848 | return bootstrapPipelineRecordRuntimeFunctions(G); |
| 849 | }); |
| 850 | |
| 851 | // --- Handle Initializers --- |
| 852 | if (auto InitSymbol = MR.getInitializerSymbol()) { |
| 853 | |
| 854 | // If the initializer symbol is the MachOHeader start symbol then just |
| 855 | // register it and then bail out -- the header materialization unit |
| 856 | // definitely doesn't need any other passes. |
| 857 | if (InitSymbol == MP.MachOHeaderStartSymbol && !InBootstrapPhase) { |
| 858 | Config.PostAllocationPasses.push_back(x: [this, &MR](LinkGraph &G) { |
| 859 | return associateJITDylibHeaderSymbol(G, MR); |
| 860 | }); |
| 861 | return; |
| 862 | } |
| 863 | |
| 864 | // If the object contains an init symbol other than the header start symbol |
| 865 | // then add passes to preserve, process and register the init |
| 866 | // sections/symbols. |
| 867 | Config.PrePrunePasses.push_back(x: [this, &MR](LinkGraph &G) { |
| 868 | if (auto Err = preserveImportantSections(G, MR)) |
| 869 | return Err; |
| 870 | return processObjCImageInfo(G, MR); |
| 871 | }); |
| 872 | Config.PostPrunePasses.push_back( |
| 873 | x: [this](LinkGraph &G) { return createObjCRuntimeObject(G); }); |
| 874 | Config.PostAllocationPasses.push_back( |
| 875 | x: [this, &MR](LinkGraph &G) { return populateObjCRuntimeObject(G, MR); }); |
| 876 | } |
| 877 | |
| 878 | // Insert TLV lowering at the start of the PostPrunePasses, since we want |
| 879 | // it to run before GOT/PLT lowering. |
| 880 | Config.PostPrunePasses.insert( |
| 881 | position: Config.PostPrunePasses.begin(), |
| 882 | x: [this, &JD = MR.getTargetJITDylib()](LinkGraph &G) { |
| 883 | return fixTLVSectionsAndEdges(G, JD); |
| 884 | }); |
| 885 | |
| 886 | // Add symbol table prepare and register passes: These will add strings for |
| 887 | // all symbols to the c-strings section, and build a symbol table registration |
| 888 | // call. |
| 889 | auto JITSymTabInfo = std::make_shared<JITSymTabVector>(); |
| 890 | Config.PostPrunePasses.push_back(x: [this, JITSymTabInfo](LinkGraph &G) { |
| 891 | return prepareSymbolTableRegistration(G, JITSymTabInfo&: *JITSymTabInfo); |
| 892 | }); |
| 893 | Config.PostFixupPasses.push_back(x: [this, &MR, JITSymTabInfo, |
| 894 | InBootstrapPhase](LinkGraph &G) { |
| 895 | return addSymbolTableRegistration(G, MR, JITSymTabInfo&: *JITSymTabInfo, InBootstrapPhase); |
| 896 | }); |
| 897 | |
| 898 | // Add a pass to register the final addresses of any special sections in the |
| 899 | // object with the runtime. |
| 900 | Config.PostAllocationPasses.push_back(x: [this, &JD = MR.getTargetJITDylib(), |
| 901 | HeaderAddr, |
| 902 | InBootstrapPhase](LinkGraph &G) { |
| 903 | return registerObjectPlatformSections(G, JD, HeaderAddr, InBootstrapPhase); |
| 904 | }); |
| 905 | |
| 906 | // If we're in the bootstrap phase then steal allocation actions and then |
| 907 | // decrement the active graphs. |
| 908 | if (InBootstrapPhase) |
| 909 | Config.PostFixupPasses.push_back( |
| 910 | x: [this](LinkGraph &G) { return bootstrapPipelineEnd(G); }); |
| 911 | } |
| 912 | |
| 913 | Error MachOPlatform::MachOPlatformPlugin:: |
| 914 | bootstrapPipelineRecordRuntimeFunctions(jitlink::LinkGraph &G) { |
| 915 | // Record bootstrap function names. |
| 916 | std::pair<StringRef, ExecutorAddr *> RuntimeSymbols[] = { |
| 917 | {*MP.MachOHeaderStartSymbol, &MP.Bootstrap->MachOHeaderAddr}, |
| 918 | {*MP.PlatformBootstrap.Name, &MP.PlatformBootstrap.Addr}, |
| 919 | {*MP.PlatformShutdown.Name, &MP.PlatformShutdown.Addr}, |
| 920 | {*MP.RegisterJITDylib.Name, &MP.RegisterJITDylib.Addr}, |
| 921 | {*MP.DeregisterJITDylib.Name, &MP.DeregisterJITDylib.Addr}, |
| 922 | {*MP.RegisterObjectSymbolTable.Name, &MP.RegisterObjectSymbolTable.Addr}, |
| 923 | {*MP.DeregisterObjectSymbolTable.Name, |
| 924 | &MP.DeregisterObjectSymbolTable.Addr}, |
| 925 | {*MP.RegisterObjectPlatformSections.Name, |
| 926 | &MP.RegisterObjectPlatformSections.Addr}, |
| 927 | {*MP.DeregisterObjectPlatformSections.Name, |
| 928 | &MP.DeregisterObjectPlatformSections.Addr}, |
| 929 | {*MP.CreatePThreadKey.Name, &MP.CreatePThreadKey.Addr}, |
| 930 | {*MP.RegisterObjCRuntimeObject.Name, &MP.RegisterObjCRuntimeObject.Addr}, |
| 931 | {*MP.DeregisterObjCRuntimeObject.Name, |
| 932 | &MP.DeregisterObjCRuntimeObject.Addr}}; |
| 933 | |
| 934 | bool = false; |
| 935 | |
| 936 | for (auto *Sym : G.defined_symbols()) { |
| 937 | for (auto &RTSym : RuntimeSymbols) { |
| 938 | if (Sym->hasName() && *Sym->getName() == RTSym.first) { |
| 939 | if (*RTSym.second) |
| 940 | return make_error<StringError>( |
| 941 | Args: "Duplicate " + RTSym.first + |
| 942 | " detected during MachOPlatform bootstrap" , |
| 943 | Args: inconvertibleErrorCode()); |
| 944 | |
| 945 | if (Sym->getName() == MP.MachOHeaderStartSymbol) |
| 946 | RegisterMachOHeader = true; |
| 947 | |
| 948 | *RTSym.second = Sym->getAddress(); |
| 949 | } |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | if (RegisterMachOHeader) { |
| 954 | // If this graph defines the macho header symbol then create the internal |
| 955 | // mapping between it and PlatformJD. |
| 956 | std::lock_guard<std::mutex> Lock(MP.PlatformMutex); |
| 957 | MP.JITDylibToHeaderAddr[&MP.PlatformJD] = MP.Bootstrap->MachOHeaderAddr; |
| 958 | MP.HeaderAddrToJITDylib[MP.Bootstrap->MachOHeaderAddr] = &MP.PlatformJD; |
| 959 | } |
| 960 | |
| 961 | return Error::success(); |
| 962 | } |
| 963 | |
| 964 | Error MachOPlatform::MachOPlatformPlugin::bootstrapPipelineEnd( |
| 965 | jitlink::LinkGraph &G) { |
| 966 | std::lock_guard<std::mutex> Lock(MP.PlatformMutex); |
| 967 | |
| 968 | --MP.Bootstrap->ActiveGraphs; |
| 969 | // Notify Bootstrap->CV while holding the mutex because the mutex is |
| 970 | // also keeping Bootstrap->CV alive. |
| 971 | if (MP.Bootstrap->ActiveGraphs == 0) |
| 972 | MP.Bootstrap->CV.notify_all(); |
| 973 | return Error::success(); |
| 974 | } |
| 975 | |
| 976 | Error MachOPlatform::MachOPlatformPlugin::( |
| 977 | jitlink::LinkGraph &G, MaterializationResponsibility &MR) { |
| 978 | auto I = llvm::find_if(Range: G.defined_symbols(), P: [this](jitlink::Symbol *Sym) { |
| 979 | return Sym->getName() == MP.MachOHeaderStartSymbol; |
| 980 | }); |
| 981 | assert(I != G.defined_symbols().end() && "Missing MachO header start symbol" ); |
| 982 | |
| 983 | auto &JD = MR.getTargetJITDylib(); |
| 984 | std::lock_guard<std::mutex> Lock(MP.PlatformMutex); |
| 985 | auto = (*I)->getAddress(); |
| 986 | MP.JITDylibToHeaderAddr[&JD] = HeaderAddr; |
| 987 | MP.HeaderAddrToJITDylib[HeaderAddr] = &JD; |
| 988 | // We can unconditionally add these actions to the Graph because this pass |
| 989 | // isn't used during bootstrap. |
| 990 | G.allocActions().push_back( |
| 991 | x: {.Finalize: cantFail( |
| 992 | ValOrErr: WrapperFunctionCall::Create<SPSArgList<SPSString, SPSExecutorAddr>>( |
| 993 | FnAddr: MP.RegisterJITDylib.Addr, Args: JD.getName(), Args: HeaderAddr)), |
| 994 | .Dealloc: cantFail(ValOrErr: WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>( |
| 995 | FnAddr: MP.DeregisterJITDylib.Addr, Args: HeaderAddr))}); |
| 996 | return Error::success(); |
| 997 | } |
| 998 | |
| 999 | Error MachOPlatform::MachOPlatformPlugin::preserveImportantSections( |
| 1000 | jitlink::LinkGraph &G, MaterializationResponsibility &MR) { |
| 1001 | // __objc_imageinfo is "important": we want to preserve it and record its |
| 1002 | // address in the first graph that it appears in, then verify and discard it |
| 1003 | // in all subsequent graphs. In this pass we preserve unconditionally -- we'll |
| 1004 | // manually throw it away in the processObjCImageInfo pass. |
| 1005 | if (auto *ObjCImageInfoSec = |
| 1006 | G.findSectionByName(Name: MachOObjCImageInfoSectionName)) { |
| 1007 | if (ObjCImageInfoSec->blocks_size() != 1) |
| 1008 | return make_error<StringError>( |
| 1009 | Args: "In " + G.getName() + |
| 1010 | "__DATA,__objc_imageinfo contains multiple blocks" , |
| 1011 | Args: inconvertibleErrorCode()); |
| 1012 | G.addAnonymousSymbol(Content&: **ObjCImageInfoSec->blocks().begin(), Offset: 0, Size: 0, IsCallable: false, |
| 1013 | IsLive: true); |
| 1014 | |
| 1015 | for (auto *B : ObjCImageInfoSec->blocks()) |
| 1016 | if (!B->edges_empty()) |
| 1017 | return make_error<StringError>(Args: "In " + G.getName() + ", " + |
| 1018 | MachOObjCImageInfoSectionName + |
| 1019 | " contains references to symbols" , |
| 1020 | Args: inconvertibleErrorCode()); |
| 1021 | } |
| 1022 | |
| 1023 | // Init sections are important: We need to preserve them and so that their |
| 1024 | // addresses can be captured and reported to the ORC runtime in |
| 1025 | // registerObjectPlatformSections. |
| 1026 | if (const auto &InitSymName = MR.getInitializerSymbol()) { |
| 1027 | |
| 1028 | jitlink::Symbol *InitSym = nullptr; |
| 1029 | for (auto &InitSectionName : MachOInitSectionNames) { |
| 1030 | // Skip ObjCImageInfo -- this shouldn't have any dependencies, and we may |
| 1031 | // remove it later. |
| 1032 | if (InitSectionName == MachOObjCImageInfoSectionName) |
| 1033 | continue; |
| 1034 | |
| 1035 | // Skip non-init sections. |
| 1036 | auto *InitSection = G.findSectionByName(Name: InitSectionName); |
| 1037 | if (!InitSection || InitSection->empty()) |
| 1038 | continue; |
| 1039 | |
| 1040 | // Create the init symbol if it has not been created already and attach it |
| 1041 | // to the first block. |
| 1042 | if (!InitSym) { |
| 1043 | auto &B = **InitSection->blocks().begin(); |
| 1044 | InitSym = &G.addDefinedSymbol( |
| 1045 | Content&: B, Offset: 0, Name: *InitSymName, Size: B.getSize(), L: jitlink::Linkage::Strong, |
| 1046 | S: jitlink::Scope::SideEffectsOnly, IsCallable: false, IsLive: true); |
| 1047 | } |
| 1048 | |
| 1049 | // Add keep-alive edges to anonymous symbols in all other init blocks. |
| 1050 | for (auto *B : InitSection->blocks()) { |
| 1051 | if (B == &InitSym->getBlock()) |
| 1052 | continue; |
| 1053 | |
| 1054 | auto &S = G.addAnonymousSymbol(Content&: *B, Offset: 0, Size: B->getSize(), IsCallable: false, IsLive: true); |
| 1055 | InitSym->getBlock().addEdge(K: jitlink::Edge::KeepAlive, Offset: 0, Target&: S, Addend: 0); |
| 1056 | } |
| 1057 | } |
| 1058 | } |
| 1059 | |
| 1060 | return Error::success(); |
| 1061 | } |
| 1062 | |
| 1063 | Error MachOPlatform::MachOPlatformPlugin::processObjCImageInfo( |
| 1064 | jitlink::LinkGraph &G, MaterializationResponsibility &MR) { |
| 1065 | |
| 1066 | // If there's an ObjC imagine info then either |
| 1067 | // (1) It's the first __objc_imageinfo we've seen in this JITDylib. In |
| 1068 | // this case we name and record it. |
| 1069 | // OR |
| 1070 | // (2) We already have a recorded __objc_imageinfo for this JITDylib, |
| 1071 | // in which case we just verify it. |
| 1072 | auto *ObjCImageInfo = G.findSectionByName(Name: MachOObjCImageInfoSectionName); |
| 1073 | if (!ObjCImageInfo) |
| 1074 | return Error::success(); |
| 1075 | |
| 1076 | auto ObjCImageInfoBlocks = ObjCImageInfo->blocks(); |
| 1077 | |
| 1078 | // Check that the section is not empty if present. |
| 1079 | if (ObjCImageInfoBlocks.empty()) |
| 1080 | return make_error<StringError>(Args: "Empty " + MachOObjCImageInfoSectionName + |
| 1081 | " section in " + G.getName(), |
| 1082 | Args: inconvertibleErrorCode()); |
| 1083 | |
| 1084 | // Check that there's only one block in the section. |
| 1085 | if (std::next(x: ObjCImageInfoBlocks.begin()) != ObjCImageInfoBlocks.end()) |
| 1086 | return make_error<StringError>(Args: "Multiple blocks in " + |
| 1087 | MachOObjCImageInfoSectionName + |
| 1088 | " section in " + G.getName(), |
| 1089 | Args: inconvertibleErrorCode()); |
| 1090 | |
| 1091 | // Check that the __objc_imageinfo section is unreferenced. |
| 1092 | // FIXME: We could optimize this check if Symbols had a ref-count. |
| 1093 | for (auto &Sec : G.sections()) { |
| 1094 | if (&Sec != ObjCImageInfo) |
| 1095 | for (auto *B : Sec.blocks()) |
| 1096 | for (auto &E : B->edges()) |
| 1097 | if (E.getTarget().isDefined() && |
| 1098 | &E.getTarget().getSection() == ObjCImageInfo) |
| 1099 | return make_error<StringError>(Args: MachOObjCImageInfoSectionName + |
| 1100 | " is referenced within file " + |
| 1101 | G.getName(), |
| 1102 | Args: inconvertibleErrorCode()); |
| 1103 | } |
| 1104 | |
| 1105 | auto &ObjCImageInfoBlock = **ObjCImageInfoBlocks.begin(); |
| 1106 | auto *ObjCImageInfoData = ObjCImageInfoBlock.getContent().data(); |
| 1107 | auto Version = support::endian::read32(P: ObjCImageInfoData, E: G.getEndianness()); |
| 1108 | auto Flags = |
| 1109 | support::endian::read32(P: ObjCImageInfoData + 4, E: G.getEndianness()); |
| 1110 | |
| 1111 | // Lock the mutex while we verify / update the ObjCImageInfos map. |
| 1112 | std::lock_guard<std::mutex> Lock(PluginMutex); |
| 1113 | |
| 1114 | auto ObjCImageInfoItr = ObjCImageInfos.find(Val: &MR.getTargetJITDylib()); |
| 1115 | if (ObjCImageInfoItr != ObjCImageInfos.end()) { |
| 1116 | // We've already registered an __objc_imageinfo section. Verify the |
| 1117 | // content of this new section matches, then delete it. |
| 1118 | if (ObjCImageInfoItr->second.Version != Version) |
| 1119 | return make_error<StringError>( |
| 1120 | Args: "ObjC version in " + G.getName() + |
| 1121 | " does not match first registered version" , |
| 1122 | Args: inconvertibleErrorCode()); |
| 1123 | if (ObjCImageInfoItr->second.Flags != Flags) |
| 1124 | if (Error E = mergeImageInfoFlags(G, MR, Info&: ObjCImageInfoItr->second, NewFlags: Flags)) |
| 1125 | return E; |
| 1126 | |
| 1127 | // __objc_imageinfo is valid. Delete the block. |
| 1128 | while (ObjCImageInfo->symbols_size() != 0) |
| 1129 | G.removeDefinedSymbol(Sym&: **ObjCImageInfo->symbols().begin()); |
| 1130 | G.removeBlock(B&: ObjCImageInfoBlock); |
| 1131 | } else { |
| 1132 | LLVM_DEBUG({ |
| 1133 | dbgs() << "MachOPlatform: Registered __objc_imageinfo for " |
| 1134 | << MR.getTargetJITDylib().getName() << " in " << G.getName() |
| 1135 | << "; flags = " << formatv("{0:x4}" , Flags) << "\n" ; |
| 1136 | }); |
| 1137 | // We haven't registered an __objc_imageinfo section yet. Register and |
| 1138 | // move on. The section should already be marked no-dead-strip. |
| 1139 | G.addDefinedSymbol(Content&: ObjCImageInfoBlock, Offset: 0, Name: ObjCImageInfoSymbolName, |
| 1140 | Size: ObjCImageInfoBlock.getSize(), L: jitlink::Linkage::Strong, |
| 1141 | S: jitlink::Scope::Hidden, IsCallable: false, IsLive: true); |
| 1142 | if (auto Err = MR.defineMaterializing( |
| 1143 | SymbolFlags: {{MR.getExecutionSession().intern(SymName: ObjCImageInfoSymbolName), |
| 1144 | JITSymbolFlags()}})) |
| 1145 | return Err; |
| 1146 | ObjCImageInfos[&MR.getTargetJITDylib()] = {.Version: Version, .Flags: Flags, .Finalized: false}; |
| 1147 | } |
| 1148 | |
| 1149 | return Error::success(); |
| 1150 | } |
| 1151 | |
| 1152 | Error MachOPlatform::MachOPlatformPlugin::mergeImageInfoFlags( |
| 1153 | jitlink::LinkGraph &G, MaterializationResponsibility &MR, |
| 1154 | ObjCImageInfo &Info, uint32_t NewFlags) { |
| 1155 | if (Info.Flags == NewFlags) |
| 1156 | return Error::success(); |
| 1157 | |
| 1158 | ObjCImageInfoFlags Old(Info.Flags); |
| 1159 | ObjCImageInfoFlags New(NewFlags); |
| 1160 | |
| 1161 | // Check for incompatible flags. |
| 1162 | if (Old.SwiftABIVersion && New.SwiftABIVersion && |
| 1163 | Old.SwiftABIVersion != New.SwiftABIVersion) |
| 1164 | return make_error<StringError>(Args: "Swift ABI version in " + G.getName() + |
| 1165 | " does not match first registered flags" , |
| 1166 | Args: inconvertibleErrorCode()); |
| 1167 | |
| 1168 | // HasCategoryClassProperties and HasSignedObjCClassROs can be disabled before |
| 1169 | // they are registered, if necessary, but once they are in use must be |
| 1170 | // supported by subsequent objects. |
| 1171 | if (Info.Finalized && Old.HasCategoryClassProperties && |
| 1172 | !New.HasCategoryClassProperties) |
| 1173 | return make_error<StringError>(Args: "ObjC category class property support in " + |
| 1174 | G.getName() + |
| 1175 | " does not match first registered flags" , |
| 1176 | Args: inconvertibleErrorCode()); |
| 1177 | if (Info.Finalized && Old.HasSignedObjCClassROs && !New.HasSignedObjCClassROs) |
| 1178 | return make_error<StringError>(Args: "ObjC class_ro_t pointer signing in " + |
| 1179 | G.getName() + |
| 1180 | " does not match first registered flags" , |
| 1181 | Args: inconvertibleErrorCode()); |
| 1182 | |
| 1183 | // If we cannot change the flags, ignore any remaining differences. Adding |
| 1184 | // Swift or changing its version are unlikely to cause problems in practice. |
| 1185 | if (Info.Finalized) |
| 1186 | return Error::success(); |
| 1187 | |
| 1188 | // Use the minimum Swift version. |
| 1189 | if (Old.SwiftVersion && New.SwiftVersion) |
| 1190 | New.SwiftVersion = std::min(a: Old.SwiftVersion, b: New.SwiftVersion); |
| 1191 | else if (Old.SwiftVersion) |
| 1192 | New.SwiftVersion = Old.SwiftVersion; |
| 1193 | // Add a Swift ABI version if it was pure objc before. |
| 1194 | if (!New.SwiftABIVersion) |
| 1195 | New.SwiftABIVersion = Old.SwiftABIVersion; |
| 1196 | // Disable class properties if any object does not support it. |
| 1197 | if (Old.HasCategoryClassProperties != New.HasCategoryClassProperties) |
| 1198 | New.HasCategoryClassProperties = false; |
| 1199 | // Disable signed class ro data if any object does not support it. |
| 1200 | if (Old.HasSignedObjCClassROs != New.HasSignedObjCClassROs) |
| 1201 | New.HasSignedObjCClassROs = false; |
| 1202 | |
| 1203 | LLVM_DEBUG({ |
| 1204 | dbgs() << "MachOPlatform: Merging __objc_imageinfo flags for " |
| 1205 | << MR.getTargetJITDylib().getName() << " (was " |
| 1206 | << formatv("{0:x4}" , Old.rawFlags()) << ")" |
| 1207 | << " with " << G.getName() << " (" << formatv("{0:x4}" , NewFlags) |
| 1208 | << ")" |
| 1209 | << " -> " << formatv("{0:x4}" , New.rawFlags()) << "\n" ; |
| 1210 | }); |
| 1211 | |
| 1212 | Info.Flags = New.rawFlags(); |
| 1213 | return Error::success(); |
| 1214 | } |
| 1215 | |
| 1216 | Error MachOPlatform::MachOPlatformPlugin::fixTLVSectionsAndEdges( |
| 1217 | jitlink::LinkGraph &G, JITDylib &JD) { |
| 1218 | auto TLVBootStrapSymbolName = G.intern(SymbolName: "__tlv_bootstrap" ); |
| 1219 | // Rename external references to __tlv_bootstrap to ___orc_rt_tlv_get_addr. |
| 1220 | for (auto *Sym : G.external_symbols()) |
| 1221 | if (Sym->getName() == TLVBootStrapSymbolName) { |
| 1222 | auto TLSGetADDR = |
| 1223 | MP.getExecutionSession().intern(SymName: "___orc_rt_macho_tlv_get_addr" ); |
| 1224 | Sym->setName(std::move(TLSGetADDR)); |
| 1225 | break; |
| 1226 | } |
| 1227 | |
| 1228 | // Store key in __thread_vars struct fields. |
| 1229 | if (auto *ThreadDataSec = G.findSectionByName(Name: MachOThreadVarsSectionName)) { |
| 1230 | std::optional<uint64_t> Key; |
| 1231 | { |
| 1232 | std::lock_guard<std::mutex> Lock(MP.PlatformMutex); |
| 1233 | auto I = MP.JITDylibToPThreadKey.find(Val: &JD); |
| 1234 | if (I != MP.JITDylibToPThreadKey.end()) |
| 1235 | Key = I->second; |
| 1236 | } |
| 1237 | |
| 1238 | if (!Key) { |
| 1239 | if (auto KeyOrErr = MP.createPThreadKey()) |
| 1240 | Key = *KeyOrErr; |
| 1241 | else |
| 1242 | return KeyOrErr.takeError(); |
| 1243 | } |
| 1244 | |
| 1245 | uint64_t PlatformKeyBits = |
| 1246 | support::endian::byte_swap(value: *Key, endian: G.getEndianness()); |
| 1247 | |
| 1248 | for (auto *B : ThreadDataSec->blocks()) { |
| 1249 | if (B->getSize() != 3 * G.getPointerSize()) |
| 1250 | return make_error<StringError>(Args: "__thread_vars block at " + |
| 1251 | formatv(Fmt: "{0:x}" , Vals: B->getAddress()) + |
| 1252 | " has unexpected size" , |
| 1253 | Args: inconvertibleErrorCode()); |
| 1254 | |
| 1255 | auto NewBlockContent = G.allocateBuffer(Size: B->getSize()); |
| 1256 | llvm::copy(Range: B->getContent(), Out: NewBlockContent.data()); |
| 1257 | memcpy(dest: NewBlockContent.data() + G.getPointerSize(), src: &PlatformKeyBits, |
| 1258 | n: G.getPointerSize()); |
| 1259 | B->setContent(NewBlockContent); |
| 1260 | } |
| 1261 | } |
| 1262 | |
| 1263 | // Transform any TLV edges into GOT edges. |
| 1264 | for (auto *B : G.blocks()) |
| 1265 | for (auto &E : B->edges()) |
| 1266 | if (E.getKind() == |
| 1267 | jitlink::x86_64::RequestTLVPAndTransformToPCRel32TLVPLoadREXRelaxable) |
| 1268 | E.setKind(jitlink::x86_64:: |
| 1269 | RequestGOTAndTransformToPCRel32GOTLoadREXRelaxable); |
| 1270 | |
| 1271 | return Error::success(); |
| 1272 | } |
| 1273 | |
| 1274 | std::optional<MachOPlatform::MachOPlatformPlugin::UnwindSections> |
| 1275 | MachOPlatform::MachOPlatformPlugin::findUnwindSectionInfo( |
| 1276 | jitlink::LinkGraph &G) { |
| 1277 | using namespace jitlink; |
| 1278 | |
| 1279 | UnwindSections US; |
| 1280 | |
| 1281 | // ScanSection records a section range and adds any executable blocks that |
| 1282 | // that section points to to the CodeBlocks vector. |
| 1283 | SmallVector<Block *> CodeBlocks; |
| 1284 | auto ScanUnwindInfoSection = [&](Section &Sec, ExecutorAddrRange &SecRange, |
| 1285 | auto AddCodeBlocks) { |
| 1286 | if (Sec.blocks().empty()) |
| 1287 | return; |
| 1288 | SecRange = (*Sec.blocks().begin())->getRange(); |
| 1289 | for (auto *B : Sec.blocks()) { |
| 1290 | auto R = B->getRange(); |
| 1291 | SecRange.Start = std::min(a: SecRange.Start, b: R.Start); |
| 1292 | SecRange.End = std::max(a: SecRange.End, b: R.End); |
| 1293 | AddCodeBlocks(*B); |
| 1294 | } |
| 1295 | }; |
| 1296 | |
| 1297 | if (Section *EHFrameSec = G.findSectionByName(Name: MachOEHFrameSectionName)) { |
| 1298 | ScanUnwindInfoSection(*EHFrameSec, US.DwarfSection, [&](Block &B) { |
| 1299 | if (auto *Fn = jitlink::EHFrameCFIBlockInspector::FromEdgeScan(B) |
| 1300 | .getPCBeginEdge()) |
| 1301 | if (Fn->getTarget().isDefined()) |
| 1302 | CodeBlocks.push_back(Elt: &Fn->getTarget().getBlock()); |
| 1303 | }); |
| 1304 | } |
| 1305 | |
| 1306 | if (Section *CUInfoSec = G.findSectionByName(Name: MachOUnwindInfoSectionName)) { |
| 1307 | ScanUnwindInfoSection( |
| 1308 | *CUInfoSec, US.CompactUnwindSection, [&](Block &B) { |
| 1309 | for (auto &E : B.edges()) { |
| 1310 | assert(E.getTarget().isDefined() && |
| 1311 | "unwind-info record edge has external target" ); |
| 1312 | assert(E.getKind() == Edge::KeepAlive && |
| 1313 | "unwind-info record has unexpected edge kind" ); |
| 1314 | CodeBlocks.push_back(Elt: &E.getTarget().getBlock()); |
| 1315 | } |
| 1316 | }); |
| 1317 | } |
| 1318 | |
| 1319 | // If we didn't find any pointed-to code-blocks then there's no need to |
| 1320 | // register any info. |
| 1321 | if (CodeBlocks.empty()) |
| 1322 | return std::nullopt; |
| 1323 | |
| 1324 | // We have info to register. Sort the code blocks into address order and |
| 1325 | // build a list of contiguous address ranges covering them all. |
| 1326 | llvm::sort(C&: CodeBlocks, Comp: [](const Block *LHS, const Block *RHS) { |
| 1327 | return LHS->getAddress() < RHS->getAddress(); |
| 1328 | }); |
| 1329 | for (auto *B : CodeBlocks) { |
| 1330 | if (US.CodeRanges.empty() || US.CodeRanges.back().End != B->getAddress()) |
| 1331 | US.CodeRanges.push_back(Elt: B->getRange()); |
| 1332 | else |
| 1333 | US.CodeRanges.back().End = B->getRange().End; |
| 1334 | } |
| 1335 | |
| 1336 | LLVM_DEBUG({ |
| 1337 | dbgs() << "MachOPlatform identified unwind info in " << G.getName() << ":\n" |
| 1338 | << " DWARF: " ; |
| 1339 | if (US.DwarfSection.Start) |
| 1340 | dbgs() << US.DwarfSection << "\n" ; |
| 1341 | else |
| 1342 | dbgs() << "none\n" ; |
| 1343 | dbgs() << " Compact-unwind: " ; |
| 1344 | if (US.CompactUnwindSection.Start) |
| 1345 | dbgs() << US.CompactUnwindSection << "\n" ; |
| 1346 | else |
| 1347 | dbgs() << "none\n" |
| 1348 | << "for code ranges:\n" ; |
| 1349 | for (auto &CR : US.CodeRanges) |
| 1350 | dbgs() << " " << CR << "\n" ; |
| 1351 | if (US.CodeRanges.size() >= G.sections_size()) |
| 1352 | dbgs() << "WARNING: High number of discontiguous code ranges! " |
| 1353 | "Padding may be interfering with coalescing.\n" ; |
| 1354 | }); |
| 1355 | |
| 1356 | return US; |
| 1357 | } |
| 1358 | |
| 1359 | Error MachOPlatform::MachOPlatformPlugin::registerObjectPlatformSections( |
| 1360 | jitlink::LinkGraph &G, JITDylib &JD, ExecutorAddr , |
| 1361 | bool InBootstrapPhase) { |
| 1362 | |
| 1363 | // Get a pointer to the thread data section if there is one. It will be used |
| 1364 | // below. |
| 1365 | jitlink::Section *ThreadDataSection = |
| 1366 | G.findSectionByName(Name: MachOThreadDataSectionName); |
| 1367 | |
| 1368 | // Handle thread BSS section if there is one. |
| 1369 | if (auto *ThreadBSSSection = G.findSectionByName(Name: MachOThreadBSSSectionName)) { |
| 1370 | // If there's already a thread data section in this graph then merge the |
| 1371 | // thread BSS section content into it, otherwise just treat the thread |
| 1372 | // BSS section as the thread data section. |
| 1373 | if (ThreadDataSection) |
| 1374 | G.mergeSections(DstSection&: *ThreadDataSection, SrcSection&: *ThreadBSSSection); |
| 1375 | else |
| 1376 | ThreadDataSection = ThreadBSSSection; |
| 1377 | } |
| 1378 | |
| 1379 | SmallVector<std::pair<StringRef, ExecutorAddrRange>, 8> MachOPlatformSecs; |
| 1380 | |
| 1381 | // Collect data sections to register. |
| 1382 | StringRef DataSections[] = {MachODataDataSectionName, |
| 1383 | MachODataCommonSectionName, |
| 1384 | MachOEHFrameSectionName}; |
| 1385 | for (auto &SecName : DataSections) { |
| 1386 | if (auto *Sec = G.findSectionByName(Name: SecName)) { |
| 1387 | jitlink::SectionRange R(*Sec); |
| 1388 | if (!R.empty()) |
| 1389 | MachOPlatformSecs.push_back(Elt: {SecName, R.getRange()}); |
| 1390 | } |
| 1391 | } |
| 1392 | |
| 1393 | // Having merged thread BSS (if present) and thread data (if present), |
| 1394 | // record the resulting section range. |
| 1395 | if (ThreadDataSection) { |
| 1396 | jitlink::SectionRange R(*ThreadDataSection); |
| 1397 | if (!R.empty()) |
| 1398 | MachOPlatformSecs.push_back(Elt: {MachOThreadDataSectionName, R.getRange()}); |
| 1399 | } |
| 1400 | |
| 1401 | // If any platform sections were found then add an allocation action to call |
| 1402 | // the registration function. |
| 1403 | StringRef PlatformSections[] = {MachOModInitFuncSectionName, |
| 1404 | ObjCRuntimeObjectSectionName}; |
| 1405 | |
| 1406 | for (auto &SecName : PlatformSections) { |
| 1407 | auto *Sec = G.findSectionByName(Name: SecName); |
| 1408 | if (!Sec) |
| 1409 | continue; |
| 1410 | jitlink::SectionRange R(*Sec); |
| 1411 | if (R.empty()) |
| 1412 | continue; |
| 1413 | |
| 1414 | MachOPlatformSecs.push_back(Elt: {SecName, R.getRange()}); |
| 1415 | } |
| 1416 | |
| 1417 | std::optional<std::tuple<SmallVector<ExecutorAddrRange>, ExecutorAddrRange, |
| 1418 | ExecutorAddrRange>> |
| 1419 | UnwindInfo; |
| 1420 | if (auto UI = findUnwindSectionInfo(G)) |
| 1421 | UnwindInfo = std::make_tuple(args: std::move(UI->CodeRanges), args&: UI->DwarfSection, |
| 1422 | args&: UI->CompactUnwindSection); |
| 1423 | |
| 1424 | if (!MachOPlatformSecs.empty() || UnwindInfo) { |
| 1425 | // Dump the scraped inits. |
| 1426 | LLVM_DEBUG({ |
| 1427 | dbgs() << "MachOPlatform: Scraped " << G.getName() << " init sections:\n" ; |
| 1428 | for (auto &KV : MachOPlatformSecs) |
| 1429 | dbgs() << " " << KV.first << ": " << KV.second << "\n" ; |
| 1430 | }); |
| 1431 | |
| 1432 | assert(HeaderAddr && "Null header registered for JD" ); |
| 1433 | using SPSRegisterObjectPlatformSectionsArgs = SPSArgList< |
| 1434 | SPSExecutorAddr, |
| 1435 | SPSOptional<SPSTuple<SPSSequence<SPSExecutorAddrRange>, |
| 1436 | SPSExecutorAddrRange, SPSExecutorAddrRange>>, |
| 1437 | SPSSequence<SPSTuple<SPSString, SPSExecutorAddrRange>>>; |
| 1438 | |
| 1439 | AllocActionCallPair AllocActions = { |
| 1440 | .Finalize: cantFail( |
| 1441 | ValOrErr: WrapperFunctionCall::Create<SPSRegisterObjectPlatformSectionsArgs>( |
| 1442 | FnAddr: MP.RegisterObjectPlatformSections.Addr, Args: HeaderAddr, Args: UnwindInfo, |
| 1443 | Args: MachOPlatformSecs)), |
| 1444 | .Dealloc: cantFail( |
| 1445 | ValOrErr: WrapperFunctionCall::Create<SPSRegisterObjectPlatformSectionsArgs>( |
| 1446 | FnAddr: MP.DeregisterObjectPlatformSections.Addr, Args: HeaderAddr, |
| 1447 | Args: UnwindInfo, Args: MachOPlatformSecs))}; |
| 1448 | |
| 1449 | if (LLVM_LIKELY(!InBootstrapPhase)) |
| 1450 | G.allocActions().push_back(x: std::move(AllocActions)); |
| 1451 | else { |
| 1452 | std::lock_guard<std::mutex> Lock(MP.PlatformMutex); |
| 1453 | MP.Bootstrap->DeferredAAs.push_back(x: std::move(AllocActions)); |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | return Error::success(); |
| 1458 | } |
| 1459 | |
| 1460 | Error MachOPlatform::MachOPlatformPlugin::createObjCRuntimeObject( |
| 1461 | jitlink::LinkGraph &G) { |
| 1462 | |
| 1463 | bool NeedTextSegment = false; |
| 1464 | size_t NumRuntimeSections = 0; |
| 1465 | |
| 1466 | for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsData) |
| 1467 | if (G.findSectionByName(Name: ObjCRuntimeSectionName)) |
| 1468 | ++NumRuntimeSections; |
| 1469 | |
| 1470 | for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsText) { |
| 1471 | if (G.findSectionByName(Name: ObjCRuntimeSectionName)) { |
| 1472 | ++NumRuntimeSections; |
| 1473 | NeedTextSegment = true; |
| 1474 | } |
| 1475 | } |
| 1476 | |
| 1477 | // Early out for no runtime sections. |
| 1478 | if (NumRuntimeSections == 0) |
| 1479 | return Error::success(); |
| 1480 | |
| 1481 | // If there were any runtime sections then we need to add an __objc_imageinfo |
| 1482 | // section. |
| 1483 | ++NumRuntimeSections; |
| 1484 | |
| 1485 | size_t MachOSize = sizeof(MachO::mach_header_64) + |
| 1486 | (NeedTextSegment + 1) * sizeof(MachO::segment_command_64) + |
| 1487 | NumRuntimeSections * sizeof(MachO::section_64); |
| 1488 | |
| 1489 | auto &Sec = G.createSection(Name: ObjCRuntimeObjectSectionName, |
| 1490 | Prot: MemProt::Read | MemProt::Write); |
| 1491 | G.createMutableContentBlock(Parent&: Sec, ContentSize: MachOSize, Address: ExecutorAddr(), Alignment: 16, AlignmentOffset: 0, ZeroInitialize: true); |
| 1492 | |
| 1493 | return Error::success(); |
| 1494 | } |
| 1495 | |
| 1496 | Error MachOPlatform::MachOPlatformPlugin::populateObjCRuntimeObject( |
| 1497 | jitlink::LinkGraph &G, MaterializationResponsibility &MR) { |
| 1498 | |
| 1499 | auto *ObjCRuntimeObjectSec = |
| 1500 | G.findSectionByName(Name: ObjCRuntimeObjectSectionName); |
| 1501 | |
| 1502 | if (!ObjCRuntimeObjectSec) |
| 1503 | return Error::success(); |
| 1504 | |
| 1505 | switch (G.getTargetTriple().getArch()) { |
| 1506 | case Triple::aarch64: |
| 1507 | case Triple::x86_64: |
| 1508 | // Supported. |
| 1509 | break; |
| 1510 | default: |
| 1511 | return make_error<StringError>(Args: "Unrecognized MachO arch in triple " + |
| 1512 | G.getTargetTriple().str(), |
| 1513 | Args: inconvertibleErrorCode()); |
| 1514 | } |
| 1515 | |
| 1516 | auto &SecBlock = **ObjCRuntimeObjectSec->blocks().begin(); |
| 1517 | |
| 1518 | struct SecDesc { |
| 1519 | MachO::section_64 Sec; |
| 1520 | unique_function<void(size_t RecordOffset)> AddFixups; |
| 1521 | }; |
| 1522 | |
| 1523 | std::vector<SecDesc> TextSections, DataSections; |
| 1524 | auto AddSection = [&](SecDesc &SD, jitlink::Section &GraphSec) { |
| 1525 | jitlink::SectionRange SR(GraphSec); |
| 1526 | StringRef FQName = GraphSec.getName(); |
| 1527 | memset(s: &SD.Sec, c: 0, n: sizeof(MachO::section_64)); |
| 1528 | memcpy(dest: SD.Sec.sectname, src: FQName.drop_front(N: 7).data(), n: FQName.size() - 7); |
| 1529 | memcpy(dest: SD.Sec.segname, src: FQName.data(), n: 6); |
| 1530 | SD.Sec.addr = SR.getStart() - SecBlock.getAddress(); |
| 1531 | SD.Sec.size = SR.getSize(); |
| 1532 | SD.Sec.flags = MachO::S_REGULAR; |
| 1533 | }; |
| 1534 | |
| 1535 | // Add the __objc_imageinfo section. |
| 1536 | { |
| 1537 | DataSections.push_back(x: {}); |
| 1538 | auto &SD = DataSections.back(); |
| 1539 | memset(s: &SD.Sec, c: 0, n: sizeof(SD.Sec)); |
| 1540 | memcpy(dest: SD.Sec.sectname, src: "__objc_imageinfo" , n: 16); |
| 1541 | strcpy(dest: SD.Sec.segname, src: "__DATA" ); |
| 1542 | SD.Sec.size = 8; |
| 1543 | jitlink::Symbol *ObjCImageInfoSym = nullptr; |
| 1544 | SD.AddFixups = [&, ObjCImageInfoSym](size_t RecordOffset) mutable { |
| 1545 | auto PointerEdge = getPointerEdgeKind(G); |
| 1546 | |
| 1547 | // Look for an existing __objc_imageinfo symbol. |
| 1548 | if (!ObjCImageInfoSym) { |
| 1549 | auto Name = G.intern(SymbolName: ObjCImageInfoSymbolName); |
| 1550 | ObjCImageInfoSym = G.findExternalSymbolByName(Name); |
| 1551 | if (!ObjCImageInfoSym) |
| 1552 | ObjCImageInfoSym = G.findAbsoluteSymbolByName(Name); |
| 1553 | if (!ObjCImageInfoSym) { |
| 1554 | ObjCImageInfoSym = G.findDefinedSymbolByName(Name); |
| 1555 | if (ObjCImageInfoSym) { |
| 1556 | std::optional<uint32_t> Flags; |
| 1557 | { |
| 1558 | std::lock_guard<std::mutex> Lock(PluginMutex); |
| 1559 | auto It = ObjCImageInfos.find(Val: &MR.getTargetJITDylib()); |
| 1560 | if (It != ObjCImageInfos.end()) { |
| 1561 | It->second.Finalized = true; |
| 1562 | Flags = It->second.Flags; |
| 1563 | } |
| 1564 | } |
| 1565 | |
| 1566 | if (Flags) { |
| 1567 | // We own the definition of __objc_image_info; write the final |
| 1568 | // merged flags value. |
| 1569 | auto Content = ObjCImageInfoSym->getBlock().getMutableContent(G); |
| 1570 | assert( |
| 1571 | Content.size() == 8 && |
| 1572 | "__objc_image_info size should have been verified already" ); |
| 1573 | support::endian::write32(P: &Content[4], V: *Flags, E: G.getEndianness()); |
| 1574 | } |
| 1575 | } |
| 1576 | } |
| 1577 | if (!ObjCImageInfoSym) |
| 1578 | ObjCImageInfoSym = &G.addExternalSymbol(Name: std::move(Name), Size: 8, IsWeaklyReferenced: false); |
| 1579 | } |
| 1580 | |
| 1581 | SecBlock.addEdge(K: PointerEdge, |
| 1582 | Offset: RecordOffset + ((char *)&SD.Sec.addr - (char *)&SD.Sec), |
| 1583 | Target&: *ObjCImageInfoSym, Addend: -SecBlock.getAddress().getValue()); |
| 1584 | }; |
| 1585 | } |
| 1586 | |
| 1587 | for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsData) { |
| 1588 | if (auto *GraphSec = G.findSectionByName(Name: ObjCRuntimeSectionName)) { |
| 1589 | DataSections.push_back(x: {}); |
| 1590 | AddSection(DataSections.back(), *GraphSec); |
| 1591 | } |
| 1592 | } |
| 1593 | |
| 1594 | for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsText) { |
| 1595 | if (auto *GraphSec = G.findSectionByName(Name: ObjCRuntimeSectionName)) { |
| 1596 | TextSections.push_back(x: {}); |
| 1597 | AddSection(TextSections.back(), *GraphSec); |
| 1598 | } |
| 1599 | } |
| 1600 | |
| 1601 | assert(ObjCRuntimeObjectSec->blocks_size() == 1 && |
| 1602 | "Unexpected number of blocks in runtime sections object" ); |
| 1603 | |
| 1604 | // Build the header struct up-front. This also gives us a chance to check |
| 1605 | // that the triple is supported, which we'll assume below. |
| 1606 | MachO::mach_header_64 Hdr; |
| 1607 | Hdr.magic = MachO::MH_MAGIC_64; |
| 1608 | switch (G.getTargetTriple().getArch()) { |
| 1609 | case Triple::aarch64: |
| 1610 | Hdr.cputype = MachO::CPU_TYPE_ARM64; |
| 1611 | Hdr.cpusubtype = MachO::CPU_SUBTYPE_ARM64_ALL; |
| 1612 | break; |
| 1613 | case Triple::x86_64: |
| 1614 | Hdr.cputype = MachO::CPU_TYPE_X86_64; |
| 1615 | Hdr.cpusubtype = MachO::CPU_SUBTYPE_X86_64_ALL; |
| 1616 | break; |
| 1617 | default: |
| 1618 | llvm_unreachable("Unsupported architecture" ); |
| 1619 | } |
| 1620 | |
| 1621 | Hdr.filetype = MachO::MH_DYLIB; |
| 1622 | Hdr.ncmds = 1 + !TextSections.empty(); |
| 1623 | Hdr.sizeofcmds = |
| 1624 | Hdr.ncmds * sizeof(MachO::segment_command_64) + |
| 1625 | (TextSections.size() + DataSections.size()) * sizeof(MachO::section_64); |
| 1626 | Hdr.flags = 0; |
| 1627 | Hdr.reserved = 0; |
| 1628 | |
| 1629 | auto SecContent = SecBlock.getAlreadyMutableContent(); |
| 1630 | char *P = SecContent.data(); |
| 1631 | auto WriteMachOStruct = [&](auto S) { |
| 1632 | if (G.getEndianness() != llvm::endianness::native) |
| 1633 | MachO::swapStruct(S); |
| 1634 | memcpy(P, &S, sizeof(S)); |
| 1635 | P += sizeof(S); |
| 1636 | }; |
| 1637 | |
| 1638 | auto WriteSegment = [&](StringRef Name, std::vector<SecDesc> &Secs) { |
| 1639 | MachO::segment_command_64 SegLC; |
| 1640 | memset(s: &SegLC, c: 0, n: sizeof(SegLC)); |
| 1641 | memcpy(dest: SegLC.segname, src: Name.data(), n: Name.size()); |
| 1642 | SegLC.cmd = MachO::LC_SEGMENT_64; |
| 1643 | SegLC.cmdsize = sizeof(MachO::segment_command_64) + |
| 1644 | Secs.size() * sizeof(MachO::section_64); |
| 1645 | SegLC.nsects = Secs.size(); |
| 1646 | WriteMachOStruct(SegLC); |
| 1647 | for (auto &SD : Secs) { |
| 1648 | if (SD.AddFixups) |
| 1649 | SD.AddFixups(P - SecContent.data()); |
| 1650 | WriteMachOStruct(SD.Sec); |
| 1651 | } |
| 1652 | }; |
| 1653 | |
| 1654 | WriteMachOStruct(Hdr); |
| 1655 | if (!TextSections.empty()) |
| 1656 | WriteSegment("__TEXT" , TextSections); |
| 1657 | if (!DataSections.empty()) |
| 1658 | WriteSegment("__DATA" , DataSections); |
| 1659 | |
| 1660 | assert(P == SecContent.end() && "Underflow writing ObjC runtime object" ); |
| 1661 | return Error::success(); |
| 1662 | } |
| 1663 | |
| 1664 | Error MachOPlatform::MachOPlatformPlugin::prepareSymbolTableRegistration( |
| 1665 | jitlink::LinkGraph &G, JITSymTabVector &JITSymTabInfo) { |
| 1666 | |
| 1667 | auto *CStringSec = G.findSectionByName(Name: MachOCStringSectionName); |
| 1668 | if (!CStringSec) |
| 1669 | CStringSec = &G.createSection(Name: MachOCStringSectionName, |
| 1670 | Prot: MemProt::Read | MemProt::Exec); |
| 1671 | |
| 1672 | // Make a map of existing strings so that we can re-use them: |
| 1673 | DenseMap<StringRef, jitlink::Symbol *> ExistingStrings; |
| 1674 | for (auto *Sym : CStringSec->symbols()) { |
| 1675 | |
| 1676 | // The LinkGraph builder should have created single strings blocks, and all |
| 1677 | // plugins should have maintained this invariant. |
| 1678 | auto Content = Sym->getBlock().getContent(); |
| 1679 | ExistingStrings.insert( |
| 1680 | KV: std::make_pair(x: StringRef(Content.data(), Content.size()), y&: Sym)); |
| 1681 | } |
| 1682 | |
| 1683 | // Add all symbol names to the string section, and record the symbols for |
| 1684 | // those names. |
| 1685 | { |
| 1686 | SmallVector<jitlink::Symbol *> SymsToProcess; |
| 1687 | llvm::append_range(C&: SymsToProcess, R: G.defined_symbols()); |
| 1688 | llvm::append_range(C&: SymsToProcess, R: G.absolute_symbols()); |
| 1689 | |
| 1690 | for (auto *Sym : SymsToProcess) { |
| 1691 | if (!Sym->hasName()) |
| 1692 | continue; |
| 1693 | |
| 1694 | auto I = ExistingStrings.find(Val: *Sym->getName()); |
| 1695 | if (I == ExistingStrings.end()) { |
| 1696 | auto &NameBlock = G.createMutableContentBlock( |
| 1697 | Parent&: *CStringSec, MutableContent: G.allocateCString(Source: *Sym->getName()), |
| 1698 | Address: orc::ExecutorAddr(), Alignment: 1, AlignmentOffset: 0); |
| 1699 | auto &SymbolNameSym = G.addAnonymousSymbol( |
| 1700 | Content&: NameBlock, Offset: 0, Size: NameBlock.getSize(), IsCallable: false, IsLive: true); |
| 1701 | JITSymTabInfo.push_back(Elt: {.OriginalSym: Sym, .NameSym: &SymbolNameSym}); |
| 1702 | } else |
| 1703 | JITSymTabInfo.push_back(Elt: {.OriginalSym: Sym, .NameSym: I->second}); |
| 1704 | } |
| 1705 | } |
| 1706 | |
| 1707 | return Error::success(); |
| 1708 | } |
| 1709 | |
| 1710 | Error MachOPlatform::MachOPlatformPlugin::addSymbolTableRegistration( |
| 1711 | jitlink::LinkGraph &G, MaterializationResponsibility &MR, |
| 1712 | JITSymTabVector &JITSymTabInfo, bool InBootstrapPhase) { |
| 1713 | |
| 1714 | ExecutorAddr ; |
| 1715 | { |
| 1716 | std::lock_guard<std::mutex> Lock(MP.PlatformMutex); |
| 1717 | auto I = MP.JITDylibToHeaderAddr.find(Val: &MR.getTargetJITDylib()); |
| 1718 | assert(I != MP.JITDylibToHeaderAddr.end() && "No header registered for JD" ); |
| 1719 | assert(I->second && "Null header registered for JD" ); |
| 1720 | HeaderAddr = I->second; |
| 1721 | } |
| 1722 | |
| 1723 | if (LLVM_UNLIKELY(InBootstrapPhase)) { |
| 1724 | // If we're in the bootstrap phase then just record these symbols in the |
| 1725 | // bootstrap object and then bail out -- registration will be attached to |
| 1726 | // the bootstrap graph. |
| 1727 | std::lock_guard<std::mutex> Lock(MP.PlatformMutex); |
| 1728 | auto &SymTab = MP.Bootstrap->SymTab; |
| 1729 | for (auto &[OriginalSymbol, NameSym] : JITSymTabInfo) |
| 1730 | SymTab.push_back(Elt: {NameSym->getAddress(), OriginalSymbol->getAddress(), |
| 1731 | flagsForSymbol(Sym&: *OriginalSymbol)}); |
| 1732 | return Error::success(); |
| 1733 | } |
| 1734 | |
| 1735 | SymbolTableVector SymTab; |
| 1736 | for (auto &[OriginalSymbol, NameSym] : JITSymTabInfo) |
| 1737 | SymTab.push_back(Elt: {NameSym->getAddress(), OriginalSymbol->getAddress(), |
| 1738 | flagsForSymbol(Sym&: *OriginalSymbol)}); |
| 1739 | |
| 1740 | G.allocActions().push_back( |
| 1741 | x: {.Finalize: cantFail(ValOrErr: WrapperFunctionCall::Create<SPSRegisterSymbolsArgs>( |
| 1742 | FnAddr: MP.RegisterObjectSymbolTable.Addr, Args: HeaderAddr, Args: SymTab)), |
| 1743 | .Dealloc: cantFail(ValOrErr: WrapperFunctionCall::Create<SPSRegisterSymbolsArgs>( |
| 1744 | FnAddr: MP.DeregisterObjectSymbolTable.Addr, Args: HeaderAddr, Args: SymTab))}); |
| 1745 | |
| 1746 | return Error::success(); |
| 1747 | } |
| 1748 | |
| 1749 | template <typename MachOTraits> |
| 1750 | jitlink::Block &(MachOPlatform &MOP, |
| 1751 | const MachOPlatform::HeaderOptions &Opts, |
| 1752 | JITDylib &JD, jitlink::LinkGraph &G, |
| 1753 | jitlink::Section &) { |
| 1754 | auto HdrInfo = |
| 1755 | getMachOHeaderInfoFromTriple(TT: MOP.getExecutionSession().getTargetTriple()); |
| 1756 | MachOBuilder<MachOTraits> B(HdrInfo.PageSize); |
| 1757 | |
| 1758 | B.Header.filetype = MachO::MH_DYLIB; |
| 1759 | B.Header.cputype = HdrInfo.CPUType; |
| 1760 | B.Header.cpusubtype = HdrInfo.CPUSubType; |
| 1761 | |
| 1762 | if (Opts.IDDylib) |
| 1763 | B.template addLoadCommand<MachO::LC_ID_DYLIB>( |
| 1764 | Opts.IDDylib->Name, Opts.IDDylib->Timestamp, |
| 1765 | Opts.IDDylib->CurrentVersion, Opts.IDDylib->CompatibilityVersion); |
| 1766 | else |
| 1767 | B.template addLoadCommand<MachO::LC_ID_DYLIB>(JD.getName(), 0, 0, 0); |
| 1768 | |
| 1769 | if (Opts.UUID) |
| 1770 | B.template addLoadCommand<MachO::LC_UUID>(*Opts.UUID); |
| 1771 | |
| 1772 | for (auto &BV : Opts.BuildVersions) |
| 1773 | B.template addLoadCommand<MachO::LC_BUILD_VERSION>( |
| 1774 | BV.Platform, BV.MinOS, BV.SDK, static_cast<uint32_t>(0)); |
| 1775 | |
| 1776 | if (Opts.TargetTriple) |
| 1777 | B.template addLoadCommand<MachO::LC_TARGET_TRIPLE>(*Opts.TargetTriple); |
| 1778 | |
| 1779 | using LoadKind = MachOPlatform::HeaderOptions::LoadDylibCmd::LoadKind; |
| 1780 | for (auto &LD : Opts.LoadDylibs) { |
| 1781 | switch (LD.K) { |
| 1782 | case LoadKind::Default: |
| 1783 | B.template addLoadCommand<MachO::LC_LOAD_DYLIB>( |
| 1784 | LD.D.Name, LD.D.Timestamp, LD.D.CurrentVersion, |
| 1785 | LD.D.CompatibilityVersion); |
| 1786 | break; |
| 1787 | case LoadKind::Weak: |
| 1788 | B.template addLoadCommand<MachO::LC_LOAD_WEAK_DYLIB>( |
| 1789 | LD.D.Name, LD.D.Timestamp, LD.D.CurrentVersion, |
| 1790 | LD.D.CompatibilityVersion); |
| 1791 | break; |
| 1792 | } |
| 1793 | } |
| 1794 | for (auto &P : Opts.RPaths) |
| 1795 | B.template addLoadCommand<MachO::LC_RPATH>(P); |
| 1796 | |
| 1797 | auto = G.allocateBuffer(Size: B.layout()); |
| 1798 | B.write(HeaderContent); |
| 1799 | |
| 1800 | return G.createContentBlock(Parent&: HeaderSection, Content: HeaderContent, Address: ExecutorAddr(), Alignment: 8, |
| 1801 | AlignmentOffset: 0); |
| 1802 | } |
| 1803 | |
| 1804 | SimpleMachOHeaderMU::(MachOPlatform &MOP, |
| 1805 | SymbolStringPtr , |
| 1806 | MachOPlatform::HeaderOptions Opts) |
| 1807 | : MaterializationUnit( |
| 1808 | createHeaderInterface(MOP, HeaderStartSymbol: std::move(HeaderStartSymbol))), |
| 1809 | MOP(MOP), Opts(std::move(Opts)) {} |
| 1810 | |
| 1811 | void SimpleMachOHeaderMU::( |
| 1812 | std::unique_ptr<MaterializationResponsibility> R) { |
| 1813 | auto G = createPlatformGraph(MOP, Name: "<MachOHeaderMU>" ); |
| 1814 | addMachOHeader(JD&: R->getTargetJITDylib(), G&: *G, InitializerSymbol: R->getInitializerSymbol()); |
| 1815 | MOP.getObjectLinkingLayer().emit(R: std::move(R), G: std::move(G)); |
| 1816 | } |
| 1817 | |
| 1818 | void SimpleMachOHeaderMU::(const JITDylib &JD, |
| 1819 | const SymbolStringPtr &Sym) {} |
| 1820 | |
| 1821 | void SimpleMachOHeaderMU::( |
| 1822 | JITDylib &JD, jitlink::LinkGraph &G, |
| 1823 | const SymbolStringPtr &InitializerSymbol) { |
| 1824 | auto & = G.createSection(Name: "__header" , Prot: MemProt::Read); |
| 1825 | auto & = createHeaderBlock(JD, G, HeaderSection); |
| 1826 | |
| 1827 | // Init symbol is header-start symbol. |
| 1828 | G.addDefinedSymbol(Content&: HeaderBlock, Offset: 0, Name: *InitializerSymbol, Size: HeaderBlock.getSize(), |
| 1829 | L: jitlink::Linkage::Strong, S: jitlink::Scope::Default, IsCallable: false, |
| 1830 | IsLive: true); |
| 1831 | for (auto &HS : AdditionalHeaderSymbols) |
| 1832 | G.addDefinedSymbol(Content&: HeaderBlock, Offset: HS.Offset, Name: HS.Name, Size: HeaderBlock.getSize(), |
| 1833 | L: jitlink::Linkage::Strong, S: jitlink::Scope::Default, IsCallable: false, |
| 1834 | IsLive: true); |
| 1835 | } |
| 1836 | |
| 1837 | jitlink::Block & |
| 1838 | SimpleMachOHeaderMU::(JITDylib &JD, jitlink::LinkGraph &G, |
| 1839 | jitlink::Section &) { |
| 1840 | switch (MOP.getExecutionSession().getTargetTriple().getArch()) { |
| 1841 | case Triple::aarch64: |
| 1842 | case Triple::x86_64: |
| 1843 | return ::createHeaderBlock<MachO64LE>(MOP, Opts, JD, G, HeaderSection); |
| 1844 | default: |
| 1845 | llvm_unreachable("Unsupported architecture" ); |
| 1846 | } |
| 1847 | } |
| 1848 | |
| 1849 | MaterializationUnit::Interface SimpleMachOHeaderMU::( |
| 1850 | MachOPlatform &MOP, const SymbolStringPtr &) { |
| 1851 | SymbolFlagsMap ; |
| 1852 | |
| 1853 | HeaderSymbolFlags[HeaderStartSymbol] = JITSymbolFlags::Exported; |
| 1854 | for (auto &HS : AdditionalHeaderSymbols) |
| 1855 | HeaderSymbolFlags[MOP.getExecutionSession().intern(SymName: HS.Name)] = |
| 1856 | JITSymbolFlags::Exported; |
| 1857 | |
| 1858 | return MaterializationUnit::Interface(std::move(HeaderSymbolFlags), |
| 1859 | HeaderStartSymbol); |
| 1860 | } |
| 1861 | |
| 1862 | MachOHeaderInfo (const Triple &TT) { |
| 1863 | switch (TT.getArch()) { |
| 1864 | case Triple::aarch64: |
| 1865 | return {/* PageSize = */ 16 * 1024, |
| 1866 | /* CPUType = */ MachO::CPU_TYPE_ARM64, |
| 1867 | /* CPUSubType = */ MachO::CPU_SUBTYPE_ARM64_ALL}; |
| 1868 | case Triple::x86_64: |
| 1869 | return {/* PageSize = */ 4 * 1024, |
| 1870 | /* CPUType = */ MachO::CPU_TYPE_X86_64, |
| 1871 | /* CPUSubType = */ MachO::CPU_SUBTYPE_X86_64_ALL}; |
| 1872 | default: |
| 1873 | llvm_unreachable("Unrecognized architecture" ); |
| 1874 | } |
| 1875 | } |
| 1876 | |
| 1877 | } // End namespace orc. |
| 1878 | } // End namespace llvm. |
| 1879 | |