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 "SyntheticSections.h"
13 #include "Target.h"
14 #include "lld/Common/Memory.h"
15 #include "llvm/Support/Endian.h"
16 
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 + addr - parent->firstSection()->addr;
26 }
27 
28 void InputSection::writeTo(uint8_t *buf) {
29   if (!data.empty())
30     memcpy(buf, data.data(), data.size());
31 
32   for (Reloc &r : relocs) {
33     uint64_t va = 0;
34     if (auto *s = r.target.dyn_cast<Symbol *>()) {
35       if (auto *dylibSymbol = dyn_cast<DylibSymbol>(s)) {
36         va = in.got->addr - ImageBase + dylibSymbol->gotIndex * WordSize;
37       } else {
38         va = s->getVA();
39       }
40     } else if (auto *isec = r.target.dyn_cast<InputSection *>()) {
41       va = isec->addr;
42     } else {
43       llvm_unreachable("Unknown relocation target");
44     }
45 
46     uint64_t val = va + r.addend;
47     if (1) // TODO: handle non-pcrel relocations
48       val -= addr - ImageBase + r.offset;
49     target->relocateOne(buf + r.offset, r.type, val);
50   }
51 }
52