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 va = 0;
39     if (auto *s = r.target.dyn_cast<Symbol *>()) {
40       va = target->resolveSymbolVA(buf + r.offset, *s, r.type);
41 
42       if (isThreadLocalVariables(flags)) {
43         // References from thread-local variable sections are treated as
44         // offsets relative to the start of the target section, instead of as
45         // absolute addresses.
46         if (auto *defined = dyn_cast<Defined>(s))
47           va -= defined->isec->parent->addr;
48       }
49     } else if (auto *isec = r.target.dyn_cast<InputSection *>()) {
50       va = isec->getVA();
51     }
52 
53     uint64_t val = va + r.addend;
54     if (r.pcrel)
55       val -= getVA() + r.offset;
56     target->relocateOne(buf + r.offset, r, val);
57   }
58 }
59 
60 std::string lld::toString(const InputSection *isec) {
61   return (toString(isec->file) + ":(" + isec->name + ")").str();
62 }
63