1//===- OutputSegment.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 "OutputSegment.h"
10#include "ConcatOutputSection.h"
11#include "InputSection.h"
12#include "Symbols.h"
13#include "SyntheticSections.h"
14
15#include "lld/Common/ErrorHandler.h"
16#include "lld/Common/Memory.h"
17#include "llvm/ADT/StringSwitch.h"
18#include "llvm/BinaryFormat/MachO.h"
19
20using namespace llvm;
21using namespace llvm::MachO;
22using namespace lld;
23using namespace lld::macho;
24
25static uint32_t initProt(StringRef name) {
26  auto it = find_if(
27      config->segmentProtections,
28      [&](const SegmentProtection &segprot) { return segprot.name == name; });
29  if (it != config->segmentProtections.end())
30    return it->initProt;
31
32  if (name == segment_names::text)
33    return VM_PROT_READ | VM_PROT_EXECUTE;
34  if (name == segment_names::pageZero)
35    return 0;
36  if (name == segment_names::linkEdit)
37    return VM_PROT_READ;
38  return VM_PROT_READ | VM_PROT_WRITE;
39}
40
41static uint32_t maxProt(StringRef name) {
42  assert(config->arch() != AK_i386 &&
43         "TODO: i386 has different maxProt requirements");
44  return initProt(name);
45}
46
47static uint32_t flags(StringRef name) {
48  // If we ever implement shared cache output support, SG_READ_ONLY should not
49  // be used for dylibs that can be placed in it.
50  return name == segment_names::dataConst ? (uint32_t)SG_READ_ONLY : 0;
51}
52
53size_t OutputSegment::numNonHiddenSections() const {
54  size_t count = 0;
55  for (const OutputSection *osec : sections)
56    count += (!osec->isHidden() ? 1 : 0);
57  return count;
58}
59
60void OutputSegment::addOutputSection(OutputSection *osec) {
61  inputOrder = std::min(inputOrder, osec->inputOrder);
62
63  osec->parent = this;
64  sections.push_back(osec);
65
66  for (const SectionAlign &sectAlign : config->sectionAlignments)
67    if (sectAlign.segName == name && sectAlign.sectName == osec->name)
68      osec->align = sectAlign.align;
69}
70
71template <typename T, typename F> static auto compareByOrder(F ord) {
72  return [=](T a, T b) { return ord(a) < ord(b); };
73}
74
75static int segmentOrder(OutputSegment *seg) {
76  return StringSwitch<int>(seg->name)
77      .Case(segment_names::pageZero, -4)
78      .Case(segment_names::text, -3)
79      .Case(segment_names::dataConst, -2)
80      .Case(segment_names::data, -1)
81      .Case(segment_names::llvm, std::numeric_limits<int>::max() - 1)
82      // Make sure __LINKEDIT is the last segment (i.e. all its hidden
83      // sections must be ordered after other sections).
84      .Case(segment_names::linkEdit, std::numeric_limits<int>::max())
85      .Default(seg->inputOrder);
86}
87
88static int sectionOrder(OutputSection *osec) {
89  StringRef segname = osec->parent->name;
90  // Sections are uniquely identified by their segment + section name.
91  if (segname == segment_names::text) {
92    return StringSwitch<int>(osec->name)
93        .Case(section_names::header, -6)
94        .Case(section_names::text, -5)
95        .Case(section_names::stubs, -4)
96        .Case(section_names::stubHelper, -3)
97        .Case(section_names::objcStubs, -2)
98        .Case(section_names::initOffsets, -1)
99        .Case(section_names::unwindInfo, std::numeric_limits<int>::max() - 1)
100        .Case(section_names::ehFrame, std::numeric_limits<int>::max())
101        .Default(osec->inputOrder);
102  } else if (segname == segment_names::data ||
103             segname == segment_names::dataConst) {
104    // For each thread spawned, dyld will initialize its TLVs by copying the
105    // address range from the start of the first thread-local data section to
106    // the end of the last one. We therefore arrange these sections contiguously
107    // to minimize the amount of memory used. Additionally, since zerofill
108    // sections must be at the end of their segments, and since TLV data
109    // sections can be zerofills, we end up putting all TLV data sections at the
110    // end of the segment.
111    switch (sectionType(osec->flags)) {
112    case S_THREAD_LOCAL_VARIABLE_POINTERS:
113      return std::numeric_limits<int>::max() - 3;
114    case S_THREAD_LOCAL_REGULAR:
115      return std::numeric_limits<int>::max() - 2;
116    case S_THREAD_LOCAL_ZEROFILL:
117      return std::numeric_limits<int>::max() - 1;
118    case S_ZEROFILL:
119      return std::numeric_limits<int>::max();
120    default:
121      return StringSwitch<int>(osec->name)
122          .Case(section_names::got, -3)
123          .Case(section_names::lazySymbolPtr, -2)
124          .Case(section_names::const_, -1)
125          .Default(osec->inputOrder);
126    }
127  } else if (segname == segment_names::linkEdit) {
128    return StringSwitch<int>(osec->name)
129        .Case(section_names::chainFixups, -11)
130        .Case(section_names::rebase, -10)
131        .Case(section_names::binding, -9)
132        .Case(section_names::weakBinding, -8)
133        .Case(section_names::lazyBinding, -7)
134        .Case(section_names::export_, -6)
135        .Case(section_names::functionStarts, -5)
136        .Case(section_names::dataInCode, -4)
137        .Case(section_names::symbolTable, -3)
138        .Case(section_names::indirectSymbolTable, -2)
139        .Case(section_names::stringTable, -1)
140        .Case(section_names::codeSignature, std::numeric_limits<int>::max())
141        .Default(osec->inputOrder);
142  }
143  // ZeroFill sections must always be the at the end of their segments:
144  // dyld checks if a segment's file size is smaller than its in-memory
145  // size to detect if a segment has zerofill sections, and if so it maps
146  // the missing tail as zerofill.
147  if (sectionType(osec->flags) == S_ZEROFILL)
148    return std::numeric_limits<int>::max();
149  return osec->inputOrder;
150}
151
152void OutputSegment::sortOutputSections() {
153  // Must be stable_sort() to keep special sections such as
154  // S_THREAD_LOCAL_REGULAR in input order.
155  llvm::stable_sort(sections, compareByOrder<OutputSection *>(sectionOrder));
156}
157
158void OutputSegment::assignAddressesToStartEndSymbols() {
159  for (Defined *d : segmentStartSymbols)
160    d->value = addr;
161  for (Defined *d : segmentEndSymbols)
162    d->value = addr + vmSize;
163}
164
165void macho::sortOutputSegments() {
166  llvm::stable_sort(outputSegments,
167                    compareByOrder<OutputSegment *>(segmentOrder));
168}
169
170static DenseMap<StringRef, OutputSegment *> nameToOutputSegment;
171std::vector<OutputSegment *> macho::outputSegments;
172
173void macho::resetOutputSegments() {
174  outputSegments.clear();
175  nameToOutputSegment.clear();
176}
177
178static StringRef maybeRenameSegment(StringRef name) {
179  auto newName = config->segmentRenameMap.find(name);
180  if (newName != config->segmentRenameMap.end())
181    return newName->second;
182  return name;
183}
184
185OutputSegment *macho::getOrCreateOutputSegment(StringRef name) {
186  name = maybeRenameSegment(name);
187
188  OutputSegment *&segRef = nameToOutputSegment[name];
189  if (segRef)
190    return segRef;
191
192  segRef = make<OutputSegment>();
193  segRef->name = name;
194  segRef->maxProt = maxProt(name);
195  segRef->initProt = initProt(name);
196  segRef->flags = flags(name);
197
198  outputSegments.push_back(segRef);
199  return segRef;
200}
201