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 
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 
33 static uint32_t maxProt(StringRef name) {
34   assert(config->target.Arch != AK_i386 &&
35          "TODO: i386 has different maxProt requirements");
36   return initProt(name);
37 }
38 
39 size_t OutputSegment::numNonHiddenSections() const {
40   size_t count = 0;
41   for (const OutputSection *osec : sections)
42     count += (!osec->isHidden() ? 1 : 0);
43   return count;
44 }
45 
46 void OutputSegment::addOutputSection(OutputSection *osec) {
47   osec->parent = this;
48   sections.push_back(osec);
49 }
50 
51 static DenseMap<StringRef, OutputSegment *> nameToOutputSegment;
52 std::vector<OutputSegment *> macho::outputSegments;
53 
54 OutputSegment *macho::getOrCreateOutputSegment(StringRef name) {
55   OutputSegment *&segRef = nameToOutputSegment[name];
56   if (segRef)
57     return segRef;
58 
59   segRef = make<OutputSegment>();
60   segRef->name = name;
61   segRef->maxProt = maxProt(name);
62   segRef->initProt = initProt(name);
63 
64   outputSegments.push_back(segRef);
65   return segRef;
66 }
67