1 //===- InputSection.cpp ---------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "InputSection.h" 10 #include "InputFiles.h" 11 #include "OutputSegment.h" 12 #include "Symbols.h" 13 #include "Target.h" 14 #include "lld/Common/Memory.h" 15 #include "llvm/Support/Endian.h" 16 17 using namespace llvm; 18 using namespace llvm::MachO; 19 using namespace llvm::support; 20 using namespace lld; 21 using namespace lld::macho; 22 23 std::vector<InputSection *> macho::inputSections; 24 25 uint64_t InputSection::getFileOffset() const { 26 return parent->fileOff + outSecFileOff; 27 } 28 29 uint64_t InputSection::getVA() const { return parent->addr + outSecOff; } 30 31 void InputSection::writeTo(uint8_t *buf) { 32 if (getFileSize() == 0) 33 return; 34 35 memcpy(buf, data.data(), data.size()); 36 37 for (Reloc &r : relocs) { 38 uint64_t referentVA = 0; 39 if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) { 40 referentVA = 41 target->resolveSymbolVA(buf + r.offset, *referentSym, r.type); 42 43 if (isThreadLocalVariables(flags)) { 44 // References from thread-local variable sections are treated 45 // as offsets relative to the start of the referent section, 46 // instead of as absolute addresses. 47 if (auto *defined = dyn_cast<Defined>(referentSym)) 48 referentVA -= defined->isec->parent->addr; 49 } 50 } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) { 51 referentVA = referentIsec->getVA(); 52 } 53 54 uint64_t referentVal = referentVA + r.addend; 55 if (r.pcrel) 56 referentVal -= getVA() + r.offset; 57 target->relocateOne(buf + r.offset, r, referentVal); 58 } 59 } 60 61 bool macho::isCodeSection(InputSection *isec) { 62 uint32_t type = isec->flags & MachO::SECTION_TYPE; 63 if (type != S_REGULAR && type != S_COALESCED) 64 return false; 65 66 uint32_t attr = isec->flags & MachO::SECTION_ATTRIBUTES_USR; 67 if (attr == S_ATTR_PURE_INSTRUCTIONS) 68 return true; 69 70 if (isec->segname == segment_names::text) 71 return StringSwitch<bool>(isec->name) 72 .Cases("__textcoal_nt", "__StaticInit", true) 73 .Default(false); 74 75 return false; 76 } 77 78 std::string lld::toString(const InputSection *isec) { 79 return (toString(isec->file) + ":(" + isec->name + ")").str(); 80 } 81