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 "InputSection.h"
11 #include "MergedOutputSection.h"
12 #include "SyntheticSections.h"
13 
14 #include "lld/Common/ErrorHandler.h"
15 #include "lld/Common/Memory.h"
16 #include "llvm/BinaryFormat/MachO.h"
17 
18 using namespace llvm;
19 using namespace llvm::MachO;
20 using namespace lld;
21 using namespace lld::macho;
22 
initProt(StringRef name)23 static uint32_t initProt(StringRef name) {
24   if (name == segment_names::text)
25     return VM_PROT_READ | VM_PROT_EXECUTE;
26   if (name == segment_names::pageZero)
27     return 0;
28   if (name == segment_names::linkEdit)
29     return VM_PROT_READ;
30   return VM_PROT_READ | VM_PROT_WRITE;
31 }
32 
maxProt(StringRef name)33 static uint32_t maxProt(StringRef name) {
34   assert(config->arch != AK_i386 &&
35          "TODO: i386 has different maxProt requirements");
36   return initProt(name);
37 }
38 
numNonHiddenSections() const39 size_t OutputSegment::numNonHiddenSections() const {
40   size_t count = 0;
41   for (const OutputSection *osec : sections) {
42     count += (!osec->isHidden() ? 1 : 0);
43   }
44   return count;
45 }
46 
addOutputSection(OutputSection * osec)47 void OutputSegment::addOutputSection(OutputSection *osec) {
48   osec->parent = this;
49   sections.push_back(osec);
50 }
51 
52 static llvm::DenseMap<StringRef, OutputSegment *> nameToOutputSegment;
53 std::vector<OutputSegment *> macho::outputSegments;
54 
getOrCreateOutputSegment(StringRef name)55 OutputSegment *macho::getOrCreateOutputSegment(StringRef name) {
56   OutputSegment *&segRef = nameToOutputSegment[name];
57   if (segRef)
58     return segRef;
59 
60   segRef = make<OutputSegment>();
61   segRef->name = name;
62   segRef->maxProt = maxProt(name);
63   segRef->initProt = initProt(name);
64 
65   outputSegments.push_back(segRef);
66   return segRef;
67 }
68