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 "OutputSegment.h"
11 #include "Symbols.h"
12 #include "Target.h"
13 #include "lld/Common/Memory.h"
14 #include "llvm/Support/Endian.h"
15 
16 using namespace llvm;
17 using namespace llvm::MachO;
18 using namespace llvm::support;
19 using namespace lld;
20 using namespace lld::macho;
21 
22 std::vector<InputSection *> macho::inputSections;
23 
24 uint64_t InputSection::getFileOffset() const {
25   return parent->fileOff + outSecFileOff;
26 }
27 
28 uint64_t InputSection::getVA() const { return parent->addr + outSecOff; }
29 
30 void InputSection::writeTo(uint8_t *buf) {
31   if (getFileSize() == 0)
32     return;
33 
34   memcpy(buf, data.data(), data.size());
35 
36   for (Reloc &r : relocs) {
37     uint64_t va = 0;
38     if (auto *s = r.target.dyn_cast<Symbol *>()) {
39       va = target->resolveSymbolVA(buf + r.offset, *s, r.type);
40 
41       if (isThreadLocalVariables(flags)) {
42         // References from thread-local variable sections are treated as
43         // offsets relative to the start of the target section, instead of as
44         // absolute addresses.
45         if (auto *defined = dyn_cast<Defined>(s))
46           va -= defined->isec->parent->addr;
47       }
48     } else if (auto *isec = r.target.dyn_cast<InputSection *>()) {
49       va = isec->getVA();
50     }
51 
52     uint64_t val = va + r.addend;
53     if (r.pcrel)
54       val -= getVA() + r.offset;
55     target->relocateOne(buf + r.offset, r, val);
56   }
57 }
58