Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/MC/MachObjectWriter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
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 "llvm/ADT/DenseMap.h"
10
#include "llvm/ADT/Twine.h"
11
#include "llvm/ADT/iterator_range.h"
12
#include "llvm/BinaryFormat/MachO.h"
13
#include "llvm/MC/MCAsmBackend.h"
14
#include "llvm/MC/MCAsmLayout.h"
15
#include "llvm/MC/MCAssembler.h"
16
#include "llvm/MC/MCContext.h"
17
#include "llvm/MC/MCDirectives.h"
18
#include "llvm/MC/MCExpr.h"
19
#include "llvm/MC/MCFixupKindInfo.h"
20
#include "llvm/MC/MCFragment.h"
21
#include "llvm/MC/MCMachObjectWriter.h"
22
#include "llvm/MC/MCObjectWriter.h"
23
#include "llvm/MC/MCSection.h"
24
#include "llvm/MC/MCSectionMachO.h"
25
#include "llvm/MC/MCSymbol.h"
26
#include "llvm/MC/MCSymbolMachO.h"
27
#include "llvm/MC/MCValue.h"
28
#include "llvm/Support/Casting.h"
29
#include "llvm/Support/Debug.h"
30
#include "llvm/Support/ErrorHandling.h"
31
#include "llvm/Support/MathExtras.h"
32
#include "llvm/Support/raw_ostream.h"
33
#include <algorithm>
34
#include <cassert>
35
#include <cstdint>
36
#include <string>
37
#include <utility>
38
#include <vector>
39
40
using namespace llvm;
41
42
#define DEBUG_TYPE "mc"
43
44
12.7k
void MachObjectWriter::reset() {
45
12.7k
  Relocations.clear();
46
12.7k
  IndirectSymBase.clear();
47
12.7k
  StringTable.clear();
48
12.7k
  LocalSymbolData.clear();
49
12.7k
  ExternalSymbolData.clear();
50
12.7k
  UndefinedSymbolData.clear();
51
12.7k
  MCObjectWriter::reset();
52
12.7k
}
53
54
177k
bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) {
55
177k
  // Undefined symbols are always extern.
56
177k
  if (S.isUndefined())
57
59.3k
    return true;
58
117k
59
117k
  // References to weak definitions require external relocation entries; the
60
117k
  // definition may not always be the one in the same object file.
61
117k
  if (cast<MCSymbolMachO>(S).isWeakDefinition())
62
3.33k
    return true;
63
114k
64
114k
  // Otherwise, we can use an internal relocation.
65
114k
  return false;
66
114k
}
67
68
bool MachObjectWriter::
69
3.59M
MachSymbolData::operator<(const MachSymbolData &RHS) const {
70
3.59M
  return Symbol->getName() < RHS.Symbol->getName();
71
3.59M
}
72
73
3.60M
bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
74
3.60M
  const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
75
3.60M
    (MCFixupKind) Kind);
76
3.60M
77
3.60M
  return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
78
3.60M
}
79
80
uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
81
576k
                                              const MCAsmLayout &Layout) const {
82
576k
  return getSectionAddress(Fragment->getParent()) +
83
576k
         Layout.getFragmentOffset(Fragment);
84
576k
}
85
86
uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S,
87
4.03M
                                            const MCAsmLayout &Layout) const {
88
4.03M
  // If this is a variable, then recursively evaluate now.
89
4.03M
  if (S.isVariable()) {
90
285
    if (const MCConstantExpr *C =
91
5
          dyn_cast<const MCConstantExpr>(S.getVariableValue()))
92
5
      return C->getValue();
93
280
94
280
    MCValue Target;
95
280
    if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
96
0
      report_fatal_error("unable to evaluate offset for variable '" +
97
0
                         S.getName() + "'");
98
280
99
280
    // Verify that any used symbols are defined.
100
280
    if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
101
0
      report_fatal_error("unable to evaluate offset to undefined symbol '" +
102
0
                         Target.getSymA()->getSymbol().getName() + "'");
103
280
    if (Target.getSymB() && 
Target.getSymB()->getSymbol().isUndefined()3
)
104
0
      report_fatal_error("unable to evaluate offset to undefined symbol '" +
105
0
                         Target.getSymB()->getSymbol().getName() + "'");
106
280
107
280
    uint64_t Address = Target.getConstant();
108
280
    if (Target.getSymA())
109
280
      Address += getSymbolAddress(Target.getSymA()->getSymbol(), Layout);
110
280
    if (Target.getSymB())
111
3
      Address += getSymbolAddress(Target.getSymB()->getSymbol(), Layout);
112
280
    return Address;
113
280
  }
114
4.03M
115
4.03M
  return getSectionAddress(S.getFragment()->getParent()) +
116
4.03M
         Layout.getSymbolOffset(S);
117
4.03M
}
118
119
uint64_t MachObjectWriter::getPaddingSize(const MCSection *Sec,
120
215k
                                          const MCAsmLayout &Layout) const {
121
215k
  uint64_t EndAddr = getSectionAddress(Sec) + Layout.getSectionAddressSize(Sec);
122
215k
  unsigned Next = Sec->getLayoutOrder() + 1;
123
215k
  if (Next >= Layout.getSectionOrder().size())
124
41.6k
    return 0;
125
174k
126
174k
  const MCSection &NextSec = *Layout.getSectionOrder()[Next];
127
174k
  if (NextSec.isVirtualSection())
128
10.6k
    return 0;
129
163k
  return OffsetToAlignment(EndAddr, NextSec.getAlignment());
130
163k
}
131
132
void MachObjectWriter::writeHeader(MachO::HeaderFileType Type,
133
                                   unsigned NumLoadCommands,
134
                                   unsigned LoadCommandsSize,
135
13.9k
                                   bool SubsectionsViaSymbols) {
136
13.9k
  uint32_t Flags = 0;
137
13.9k
138
13.9k
  if (SubsectionsViaSymbols)
139
13.5k
    Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
140
13.9k
141
13.9k
  // struct mach_header (28 bytes) or
142
13.9k
  // struct mach_header_64 (32 bytes)
143
13.9k
144
13.9k
  uint64_t Start = W.OS.tell();
145
13.9k
  (void) Start;
146
13.9k
147
13.9k
  W.write<uint32_t>(is64Bit() ? 
MachO::MH_MAGIC_6410.4k
:
MachO::MH_MAGIC3.51k
);
148
13.9k
149
13.9k
  W.write<uint32_t>(TargetObjectWriter->getCPUType());
150
13.9k
  W.write<uint32_t>(TargetObjectWriter->getCPUSubtype());
151
13.9k
152
13.9k
  W.write<uint32_t>(Type);
153
13.9k
  W.write<uint32_t>(NumLoadCommands);
154
13.9k
  W.write<uint32_t>(LoadCommandsSize);
155
13.9k
  W.write<uint32_t>(Flags);
156
13.9k
  if (is64Bit())
157
10.4k
    W.write<uint32_t>(0); // reserved
158
13.9k
159
13.9k
  assert(W.OS.tell() - Start == (is64Bit() ? sizeof(MachO::mach_header_64)
160
13.9k
                                           : sizeof(MachO::mach_header)));
161
13.9k
}
162
163
158k
void MachObjectWriter::writeWithPadding(StringRef Str, uint64_t Size) {
164
158k
  assert(Size >= Str.size());
165
158k
  W.OS << Str;
166
158k
  W.OS.write_zeros(Size - Str.size());
167
158k
}
168
169
/// writeSegmentLoadCommand - Write a segment load command.
170
///
171
/// \param NumSections The number of sections in this segment.
172
/// \param SectionDataSize The total size of the sections.
173
void MachObjectWriter::writeSegmentLoadCommand(
174
    StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize,
175
    uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt,
176
13.9k
    uint32_t InitProt) {
177
13.9k
  // struct segment_command (56 bytes) or
178
13.9k
  // struct segment_command_64 (72 bytes)
179
13.9k
180
13.9k
  uint64_t Start = W.OS.tell();
181
13.9k
  (void) Start;
182
13.9k
183
13.9k
  unsigned SegmentLoadCommandSize =
184
13.9k
    is64Bit() ? 
sizeof(MachO::segment_command_64)10.4k
:
185
13.9k
    
sizeof(MachO::segment_command)3.51k
;
186
13.9k
  W.write<uint32_t>(is64Bit() ? 
MachO::LC_SEGMENT_6410.4k
:
MachO::LC_SEGMENT3.51k
);
187
13.9k
  W.write<uint32_t>(SegmentLoadCommandSize +
188
13.9k
          NumSections * (is64Bit() ? 
sizeof(MachO::section_64)10.4k
:
189
13.9k
                         
sizeof(MachO::section)3.51k
));
190
13.9k
191
13.9k
  writeWithPadding(Name, 16);
192
13.9k
  if (is64Bit()) {
193
10.4k
    W.write<uint64_t>(VMAddr);                 // vmaddr
194
10.4k
    W.write<uint64_t>(VMSize); // vmsize
195
10.4k
    W.write<uint64_t>(SectionDataStartOffset); // file offset
196
10.4k
    W.write<uint64_t>(SectionDataSize); // file size
197
10.4k
  } else {
198
3.51k
    W.write<uint32_t>(VMAddr);                 // vmaddr
199
3.51k
    W.write<uint32_t>(VMSize); // vmsize
200
3.51k
    W.write<uint32_t>(SectionDataStartOffset); // file offset
201
3.51k
    W.write<uint32_t>(SectionDataSize); // file size
202
3.51k
  }
203
13.9k
  // maxprot
204
13.9k
  W.write<uint32_t>(MaxProt);
205
13.9k
  // initprot
206
13.9k
  W.write<uint32_t>(InitProt);
207
13.9k
  W.write<uint32_t>(NumSections);
208
13.9k
  W.write<uint32_t>(0); // flags
209
13.9k
210
13.9k
  assert(W.OS.tell() - Start == SegmentLoadCommandSize);
211
13.9k
}
212
213
void MachObjectWriter::writeSection(const MCAsmLayout &Layout,
214
                                    const MCSection &Sec, uint64_t VMAddr,
215
                                    uint64_t FileOffset, unsigned Flags,
216
                                    uint64_t RelocationsStart,
217
72.4k
                                    unsigned NumRelocations) {
218
72.4k
  uint64_t SectionSize = Layout.getSectionAddressSize(&Sec);
219
72.4k
  const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
220
72.4k
221
72.4k
  // The offset is unused for virtual sections.
222
72.4k
  if (Section.isVirtualSection()) {
223
3.56k
    assert(Layout.getSectionFileSize(&Sec) == 0 && "Invalid file size!");
224
3.56k
    FileOffset = 0;
225
3.56k
  }
226
72.4k
227
72.4k
  // struct section (68 bytes) or
228
72.4k
  // struct section_64 (80 bytes)
229
72.4k
230
72.4k
  uint64_t Start = W.OS.tell();
231
72.4k
  (void) Start;
232
72.4k
233
72.4k
  writeWithPadding(Section.getSectionName(), 16);
234
72.4k
  writeWithPadding(Section.getSegmentName(), 16);
235
72.4k
  if (is64Bit()) {
236
57.5k
    W.write<uint64_t>(VMAddr);      // address
237
57.5k
    W.write<uint64_t>(SectionSize); // size
238
57.5k
  } else {
239
14.8k
    W.write<uint32_t>(VMAddr);      // address
240
14.8k
    W.write<uint32_t>(SectionSize); // size
241
14.8k
  }
242
72.4k
  W.write<uint32_t>(FileOffset);
243
72.4k
244
72.4k
  assert(isPowerOf2_32(Section.getAlignment()) && "Invalid alignment!");
245
72.4k
  W.write<uint32_t>(Log2_32(Section.getAlignment()));
246
72.4k
  W.write<uint32_t>(NumRelocations ? 
RelocationsStart27.3k
:
045.0k
);
247
72.4k
  W.write<uint32_t>(NumRelocations);
248
72.4k
  W.write<uint32_t>(Flags);
249
72.4k
  W.write<uint32_t>(IndirectSymBase.lookup(&Sec)); // reserved1
250
72.4k
  W.write<uint32_t>(Section.getStubSize()); // reserved2
251
72.4k
  if (is64Bit())
252
57.5k
    W.write<uint32_t>(0); // reserved3
253
72.4k
254
72.4k
  assert(W.OS.tell() - Start ==
255
72.4k
         (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section)));
256
72.4k
}
257
258
void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset,
259
                                              uint32_t NumSymbols,
260
                                              uint32_t StringTableOffset,
261
12.8k
                                              uint32_t StringTableSize) {
262
12.8k
  // struct symtab_command (24 bytes)
263
12.8k
264
12.8k
  uint64_t Start = W.OS.tell();
265
12.8k
  (void) Start;
266
12.8k
267
12.8k
  W.write<uint32_t>(MachO::LC_SYMTAB);
268
12.8k
  W.write<uint32_t>(sizeof(MachO::symtab_command));
269
12.8k
  W.write<uint32_t>(SymbolOffset);
270
12.8k
  W.write<uint32_t>(NumSymbols);
271
12.8k
  W.write<uint32_t>(StringTableOffset);
272
12.8k
  W.write<uint32_t>(StringTableSize);
273
12.8k
274
12.8k
  assert(W.OS.tell() - Start == sizeof(MachO::symtab_command));
275
12.8k
}
276
277
void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol,
278
                                                uint32_t NumLocalSymbols,
279
                                                uint32_t FirstExternalSymbol,
280
                                                uint32_t NumExternalSymbols,
281
                                                uint32_t FirstUndefinedSymbol,
282
                                                uint32_t NumUndefinedSymbols,
283
                                                uint32_t IndirectSymbolOffset,
284
12.8k
                                                uint32_t NumIndirectSymbols) {
285
12.8k
  // struct dysymtab_command (80 bytes)
286
12.8k
287
12.8k
  uint64_t Start = W.OS.tell();
288
12.8k
  (void) Start;
289
12.8k
290
12.8k
  W.write<uint32_t>(MachO::LC_DYSYMTAB);
291
12.8k
  W.write<uint32_t>(sizeof(MachO::dysymtab_command));
292
12.8k
  W.write<uint32_t>(FirstLocalSymbol);
293
12.8k
  W.write<uint32_t>(NumLocalSymbols);
294
12.8k
  W.write<uint32_t>(FirstExternalSymbol);
295
12.8k
  W.write<uint32_t>(NumExternalSymbols);
296
12.8k
  W.write<uint32_t>(FirstUndefinedSymbol);
297
12.8k
  W.write<uint32_t>(NumUndefinedSymbols);
298
12.8k
  W.write<uint32_t>(0); // tocoff
299
12.8k
  W.write<uint32_t>(0); // ntoc
300
12.8k
  W.write<uint32_t>(0); // modtaboff
301
12.8k
  W.write<uint32_t>(0); // nmodtab
302
12.8k
  W.write<uint32_t>(0); // extrefsymoff
303
12.8k
  W.write<uint32_t>(0); // nextrefsyms
304
12.8k
  W.write<uint32_t>(IndirectSymbolOffset);
305
12.8k
  W.write<uint32_t>(NumIndirectSymbols);
306
12.8k
  W.write<uint32_t>(0); // extreloff
307
12.8k
  W.write<uint32_t>(0); // nextrel
308
12.8k
  W.write<uint32_t>(0); // locreloff
309
12.8k
  W.write<uint32_t>(0); // nlocrel
310
12.8k
311
12.8k
  assert(W.OS.tell() - Start == sizeof(MachO::dysymtab_command));
312
12.8k
}
313
314
MachObjectWriter::MachSymbolData *
315
268
MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
316
268
  for (auto *SymbolData :
317
268
       {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
318
533
    for (MachSymbolData &Entry : *SymbolData)
319
854
      if (Entry.Symbol == &Sym)
320
265
        return &Entry;
321
268
322
268
  
return nullptr3
;
323
268
}
324
325
4.04M
const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const {
326
4.04M
  const MCSymbol *S = &Sym;
327
4.04M
  while (S->isVariable()) {
328
296
    const MCExpr *Value = S->getVariableValue();
329
296
    const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
330
296
    if (!Ref)
331
23
      return *S;
332
273
    S = &Ref->getSymbol();
333
273
  }
334
4.04M
  
return *S4.04M
;
335
4.04M
}
336
337
void MachObjectWriter::writeNlist(MachSymbolData &MSD,
338
857k
                                  const MCAsmLayout &Layout) {
339
857k
  const MCSymbol *Symbol = MSD.Symbol;
340
857k
  const MCSymbol &Data = *Symbol;
341
857k
  const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
342
857k
  uint8_t SectionIndex = MSD.SectionIndex;
343
857k
  uint8_t Type = 0;
344
857k
  uint64_t Address = 0;
345
857k
  bool IsAlias = Symbol != AliasedSymbol;
346
857k
347
857k
  const MCSymbol &OrigSymbol = *Symbol;
348
857k
  MachSymbolData *AliaseeInfo;
349
857k
  if (IsAlias) {
350
268
    AliaseeInfo = findSymbolData(*AliasedSymbol);
351
268
    if (AliaseeInfo)
352
265
      SectionIndex = AliaseeInfo->SectionIndex;
353
268
    Symbol = AliasedSymbol;
354
268
    // FIXME: Should this update Data as well?
355
268
  }
356
857k
357
857k
  // Set the N_TYPE bits. See <mach-o/nlist.h>.
358
857k
  //
359
857k
  // FIXME: Are the prebound or indirect fields possible here?
360
857k
  if (IsAlias && 
Symbol->isUndefined()268
)
361
5
    Type = MachO::N_INDR;
362
857k
  else if (Symbol->isUndefined())
363
161k
    Type = MachO::N_UNDF;
364
695k
  else if (Symbol->isAbsolute())
365
8
    Type = MachO::N_ABS;
366
695k
  else
367
695k
    Type = MachO::N_SECT;
368
857k
369
857k
  // FIXME: Set STAB bits.
370
857k
371
857k
  if (Data.isPrivateExtern())
372
36.9k
    Type |= MachO::N_PEXT;
373
857k
374
857k
  // Set external bit.
375
857k
  if (Data.isExternal() || 
(525k
!IsAlias525k
&&
Symbol->isUndefined()525k
))
376
482k
    Type |= MachO::N_EXT;
377
857k
378
857k
  // Compute the symbol address.
379
857k
  if (IsAlias && 
Symbol->isUndefined()268
)
380
5
    Address = AliaseeInfo->StringIndex;
381
857k
  else if (Symbol->isDefined())
382
695k
    Address = getSymbolAddress(OrigSymbol, Layout);
383
161k
  else if (Symbol->isCommon()) {
384
11.1k
    // Common symbols are encoded with the size in the address
385
11.1k
    // field, and their alignment in the flags.
386
11.1k
    Address = Symbol->getCommonSize();
387
11.1k
  }
388
857k
389
857k
  // struct nlist (12 bytes)
390
857k
391
857k
  W.write<uint32_t>(MSD.StringIndex);
392
857k
  W.OS << char(Type);
393
857k
  W.OS << char(SectionIndex);
394
857k
395
857k
  // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
396
857k
  // value.
397
857k
  bool EncodeAsAltEntry =
398
857k
    IsAlias && 
cast<MCSymbolMachO>(OrigSymbol).isAltEntry()268
;
399
857k
  W.write<uint16_t>(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry));
400
857k
  if (is64Bit())
401
824k
    W.write<uint64_t>(Address);
402
33.1k
  else
403
33.1k
    W.write<uint32_t>(Address);
404
857k
}
405
406
void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type,
407
                                                uint32_t DataOffset,
408
7.41k
                                                uint32_t DataSize) {
409
7.41k
  uint64_t Start = W.OS.tell();
410
7.41k
  (void) Start;
411
7.41k
412
7.41k
  W.write<uint32_t>(Type);
413
7.41k
  W.write<uint32_t>(sizeof(MachO::linkedit_data_command));
414
7.41k
  W.write<uint32_t>(DataOffset);
415
7.41k
  W.write<uint32_t>(DataSize);
416
7.41k
417
7.41k
  assert(W.OS.tell() - Start == sizeof(MachO::linkedit_data_command));
418
7.41k
}
419
420
static unsigned ComputeLinkerOptionsLoadCommandSize(
421
  const std::vector<std::string> &Options, bool is64Bit)
422
10
{
423
10
  unsigned Size = sizeof(MachO::linker_option_command);
424
10
  for (const std::string &Option : Options)
425
14
    Size += Option.size() + 1;
426
10
  return alignTo(Size, is64Bit ? 8 : 
40
);
427
10
}
428
429
void MachObjectWriter::writeLinkerOptionsLoadCommand(
430
  const std::vector<std::string> &Options)
431
5
{
432
5
  unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
433
5
  uint64_t Start = W.OS.tell();
434
5
  (void) Start;
435
5
436
5
  W.write<uint32_t>(MachO::LC_LINKER_OPTION);
437
5
  W.write<uint32_t>(Size);
438
5
  W.write<uint32_t>(Options.size());
439
5
  uint64_t BytesWritten = sizeof(MachO::linker_option_command);
440
7
  for (const std::string &Option : Options) {
441
7
    // Write each string, including the null byte.
442
7
    W.OS << Option << '\0';
443
7
    BytesWritten += Option.size() + 1;
444
7
  }
445
5
446
5
  // Pad to a multiple of the pointer size.
447
5
  W.OS.write_zeros(OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 
40
));
448
5
449
5
  assert(W.OS.tell() - Start == Size);
450
5
}
451
452
3.53M
static bool isFixupTargetValid(const MCValue &Target) {
453
3.53M
  // Target is (LHS - RHS + cst).
454
3.53M
  // We don't support the form where LHS is null: -RHS + cst
455
3.53M
  if (!Target.getSymA() && 
Target.getSymB()3
)
456
1
    return false;
457
3.53M
  return true;
458
3.53M
}
459
460
void MachObjectWriter::recordRelocation(MCAssembler &Asm,
461
                                        const MCAsmLayout &Layout,
462
                                        const MCFragment *Fragment,
463
                                        const MCFixup &Fixup, MCValue Target,
464
3.53M
                                        uint64_t &FixedValue) {
465
3.53M
  if (!isFixupTargetValid(Target)) {
466
1
    Asm.getContext().reportError(Fixup.getLoc(),
467
1
                                 "unsupported relocation expression");
468
1
    return;
469
1
  }
470
3.53M
471
3.53M
  TargetObjectWriter->recordRelocation(this, Asm, Layout, Fragment, Fixup,
472
3.53M
                                       Target, FixedValue);
473
3.53M
}
474
475
13.9k
void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) {
476
13.9k
  // This is the point where 'as' creates actual symbols for indirect symbols
477
13.9k
  // (in the following two passes). It would be easier for us to do this sooner
478
13.9k
  // when we see the attribute, but that makes getting the order in the symbol
479
13.9k
  // table much more complicated than it is worth.
480
13.9k
  //
481
13.9k
  // FIXME: Revisit this when the dust settles.
482
13.9k
483
13.9k
  // Report errors for use of .indirect_symbol not in a symbol pointer section
484
13.9k
  // or stub section.
485
13.9k
  for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
486
15.6k
         ie = Asm.indirect_symbol_end(); it != ie; 
++it1.74k
) {
487
1.74k
    const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
488
1.74k
489
1.74k
    if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
490
1.74k
        
Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS13
&&
491
1.74k
        
Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS7
&&
492
1.74k
        
Section.getType() != MachO::S_SYMBOL_STUBS5
) {
493
0
      MCSymbol &Symbol = *it->Symbol;
494
0
      report_fatal_error("indirect symbol '" + Symbol.getName() +
495
0
                         "' not in a symbol pointer or stub section");
496
0
    }
497
1.74k
  }
498
13.9k
499
13.9k
  // Bind non-lazy symbol pointers first.
500
13.9k
  unsigned IndirectIndex = 0;
501
13.9k
  for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
502
15.6k
         ie = Asm.indirect_symbol_end(); it != ie; 
++it, ++IndirectIndex1.74k
) {
503
1.74k
    const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
504
1.74k
505
1.74k
    if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
506
1.74k
        
Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS13
)
507
11
      continue;
508
1.73k
509
1.73k
    // Initialize the section indirect symbol base, if necessary.
510
1.73k
    IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
511
1.73k
512
1.73k
    Asm.registerSymbol(*it->Symbol);
513
1.73k
  }
514
13.9k
515
13.9k
  // Then lazy symbol pointers and symbol stubs.
516
13.9k
  IndirectIndex = 0;
517
13.9k
  for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
518
15.6k
         ie = Asm.indirect_symbol_end(); it != ie; 
++it, ++IndirectIndex1.74k
) {
519
1.74k
    const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
520
1.74k
521
1.74k
    if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
522
1.74k
        
Section.getType() != MachO::S_SYMBOL_STUBS1.73k
)
523
1.73k
      continue;
524
11
525
11
    // Initialize the section indirect symbol base, if necessary.
526
11
    IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
527
11
528
11
    // Set the symbol type to undefined lazy, but only on construction.
529
11
    //
530
11
    // FIXME: Do not hardcode.
531
11
    bool Created;
532
11
    Asm.registerSymbol(*it->Symbol, &Created);
533
11
    if (Created)
534
4
      cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(true);
535
11
  }
536
13.9k
}
537
538
/// computeSymbolTable - Compute the symbol table data
539
void MachObjectWriter::computeSymbolTable(
540
    MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
541
    std::vector<MachSymbolData> &ExternalSymbolData,
542
13.8k
    std::vector<MachSymbolData> &UndefinedSymbolData) {
543
13.8k
  // Build section lookup table.
544
13.8k
  DenseMap<const MCSection*, uint8_t> SectionIndexMap;
545
13.8k
  unsigned Index = 1;
546
13.8k
  for (MCAssembler::iterator it = Asm.begin(),
547
85.6k
         ie = Asm.end(); it != ie; 
++it, ++Index71.7k
)
548
71.7k
    SectionIndexMap[&*it] = Index;
549
13.8k
  assert(Index <= 256 && "Too many sections!");
550
13.8k
551
13.8k
  // Build the string table.
552
6.24M
  for (const MCSymbol &Symbol : Asm.symbols()) {
553
6.24M
    if (!Asm.isSymbolLinkerVisible(Symbol))
554
5.38M
      continue;
555
857k
556
857k
    StringTable.add(Symbol.getName());
557
857k
  }
558
13.8k
  StringTable.finalize();
559
13.8k
560
13.8k
  // Build the symbol arrays but only for non-local symbols.
561
13.8k
  //
562
13.8k
  // The particular order that we collect and then sort the symbols is chosen to
563
13.8k
  // match 'as'. Even though it doesn't matter for correctness, this is
564
13.8k
  // important for letting us diff .o files.
565
6.24M
  for (const MCSymbol &Symbol : Asm.symbols()) {
566
6.24M
    // Ignore non-linker visible symbols.
567
6.24M
    if (!Asm.isSymbolLinkerVisible(Symbol))
568
5.38M
      continue;
569
857k
570
857k
    if (!Symbol.isExternal() && 
!Symbol.isUndefined()525k
)
571
374k
      continue;
572
482k
573
482k
    MachSymbolData MSD;
574
482k
    MSD.Symbol = &Symbol;
575
482k
    MSD.StringIndex = StringTable.getOffset(Symbol.getName());
576
482k
577
482k
    if (Symbol.isUndefined()) {
578
161k
      MSD.SectionIndex = 0;
579
161k
      UndefinedSymbolData.push_back(MSD);
580
320k
    } else if (Symbol.isAbsolute()) {
581
3
      MSD.SectionIndex = 0;
582
3
      ExternalSymbolData.push_back(MSD);
583
320k
    } else {
584
320k
      MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
585
320k
      assert(MSD.SectionIndex && "Invalid section index!");
586
320k
      ExternalSymbolData.push_back(MSD);
587
320k
    }
588
482k
  }
589
13.8k
590
13.8k
  // Now add the data for local symbols.
591
6.24M
  for (const MCSymbol &Symbol : Asm.symbols()) {
592
6.24M
    // Ignore non-linker visible symbols.
593
6.24M
    if (!Asm.isSymbolLinkerVisible(Symbol))
594
5.38M
      continue;
595
857k
596
857k
    if (Symbol.isExternal() || 
Symbol.isUndefined()525k
)
597
482k
      continue;
598
374k
599
374k
    MachSymbolData MSD;
600
374k
    MSD.Symbol = &Symbol;
601
374k
    MSD.StringIndex = StringTable.getOffset(Symbol.getName());
602
374k
603
374k
    if (Symbol.isAbsolute()) {
604
5
      MSD.SectionIndex = 0;
605
5
      LocalSymbolData.push_back(MSD);
606
374k
    } else {
607
374k
      MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
608
374k
      assert(MSD.SectionIndex && "Invalid section index!");
609
374k
      LocalSymbolData.push_back(MSD);
610
374k
    }
611
374k
  }
612
13.8k
613
13.8k
  // External and undefined symbols are required to be in lexicographic order.
614
13.8k
  llvm::sort(ExternalSymbolData);
615
13.8k
  llvm::sort(UndefinedSymbolData);
616
13.8k
617
13.8k
  // Set the symbol indices.
618
13.8k
  Index = 0;
619
13.8k
  for (auto *SymbolData :
620
13.8k
       {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
621
41.5k
    for (MachSymbolData &Entry : *SymbolData)
622
857k
      Entry.Symbol->setIndex(Index++);
623
13.8k
624
71.7k
  for (const MCSection &Section : Asm) {
625
3.59M
    for (RelAndSymbol &Rel : Relocations[&Section]) {
626
3.59M
      if (!Rel.Sym)
627
809k
        continue;
628
2.78M
629
2.78M
      // Set the Index and the IsExtern bit.
630
2.78M
      unsigned Index = Rel.Sym->getIndex();
631
2.78M
      assert(isInt<24>(Index));
632
2.78M
      if (W.Endian == support::little)
633
2.78M
        Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
634
1
      else
635
1
        Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
636
2.78M
    }
637
71.7k
  }
638
13.8k
}
639
640
void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
641
13.9k
                                               const MCAsmLayout &Layout) {
642
13.9k
  uint64_t StartAddress = 0;
643
72.4k
  for (const MCSection *Sec : Layout.getSectionOrder()) {
644
72.4k
    StartAddress = alignTo(StartAddress, Sec->getAlignment());
645
72.4k
    SectionAddress[Sec] = StartAddress;
646
72.4k
    StartAddress += Layout.getSectionAddressSize(Sec);
647
72.4k
648
72.4k
    // Explicitly pad the section to match the alignment requirements of the
649
72.4k
    // following one. This is for 'gas' compatibility, it shouldn't
650
72.4k
    /// strictly be necessary.
651
72.4k
    StartAddress += getPaddingSize(Sec, Layout);
652
72.4k
  }
653
13.9k
}
654
655
void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
656
13.9k
                                                const MCAsmLayout &Layout) {
657
13.9k
  computeSectionAddresses(Asm, Layout);
658
13.9k
659
13.9k
  // Create symbol data for any indirect symbols.
660
13.9k
  bindIndirectSymbols(Asm);
661
13.9k
}
662
663
bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
664
    const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B,
665
3.98M
    bool InSet) const {
666
3.98M
  // FIXME: We don't handle things like
667
3.98M
  // foo = .
668
3.98M
  // creating atoms.
669
3.98M
  if (A.isVariable() || 
B.isVariable()3.98M
)
670
3
    return false;
671
3.98M
  return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, A, B,
672
3.98M
                                                                InSet);
673
3.98M
}
674
675
bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
676
    const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
677
7.06M
    bool InSet, bool IsPCRel) const {
678
7.06M
  if (InSet)
679
3.87M
    return true;
680
3.18M
681
3.18M
  // The effective address is
682
3.18M
  //     addr(atom(A)) + offset(A)
683
3.18M
  //   - addr(atom(B)) - offset(B)
684
3.18M
  // and the offsets are not relocatable, so the fixup is fully resolved when
685
3.18M
  //  addr(atom(A)) - addr(atom(B)) == 0.
686
3.18M
  const MCSymbol &SA = findAliasedSymbol(SymA);
687
3.18M
  const MCSection &SecA = SA.getSection();
688
3.18M
  const MCSection &SecB = *FB.getParent();
689
3.18M
690
3.18M
  if (IsPCRel) {
691
3.07M
    // The simple (Darwin, except on x86_64) way of dealing with this was to
692
3.07M
    // assume that any reference to a temporary symbol *must* be a temporary
693
3.07M
    // symbol in the same atom, unless the sections differ. Therefore, any PCrel
694
3.07M
    // relocation to a temporary symbol (in the same section) is fully
695
3.07M
    // resolved. This also works in conjunction with absolutized .set, which
696
3.07M
    // requires the compiler to use .set to absolutize the differences between
697
3.07M
    // symbols which the compiler knows to be assembly time constants, so we
698
3.07M
    // don't need to worry about considering symbol differences fully resolved.
699
3.07M
    //
700
3.07M
    // If the file isn't using sub-sections-via-symbols, we can make the
701
3.07M
    // same assumptions about any symbol that we normally make about
702
3.07M
    // assembler locals.
703
3.07M
704
3.07M
    bool hasReliableSymbolDifference = isX86_64();
705
3.07M
    if (!hasReliableSymbolDifference) {
706
2.39M
      if (!SA.isInSection() || &SecA != &SecB ||
707
2.39M
          
(2.39M
!SA.isTemporary()2.39M
&&
FB.getAtom() != SA.getFragment()->getAtom()750k
&&
708
2.39M
           
Asm.getSubsectionsViaSymbols()747k
))
709
747k
        return false;
710
1.64M
      return true;
711
1.64M
    }
712
683k
    // For Darwin x86_64, there is one special case when the reference IsPCRel.
713
683k
    // If the fragment with the reference does not have a base symbol but meets
714
683k
    // the simple way of dealing with this, in that it is a temporary symbol in
715
683k
    // the same atom then it is assumed to be fully resolved.  This is needed so
716
683k
    // a relocation entry is not created and so the static linker does not
717
683k
    // mess up the reference later.
718
683k
    else if(!FB.getAtom() &&
719
683k
            
SA.isTemporary()44
&&
SA.isInSection()30
&&
&SecA == &SecB30
){
720
2
      return true;
721
2
    }
722
795k
  }
723
795k
724
795k
  // If they are not in the same section, we can't compute the diff.
725
795k
  if (&SecA != &SecB)
726
113k
    return false;
727
682k
728
682k
  const MCFragment *FA = SA.getFragment();
729
682k
730
682k
  // Bail if the symbol has no fragment.
731
682k
  if (!FA)
732
0
    return false;
733
682k
734
682k
  // If the atoms are the same, they are guaranteed to have the same address.
735
682k
  if (FA->getAtom() == FB.getAtom())
736
665k
    return true;
737
16.4k
738
16.4k
  // Otherwise, we can't prove this is fully resolved.
739
16.4k
  return false;
740
16.4k
}
741
742
12.8k
static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type) {
743
12.8k
  switch (Type) {
744
12.8k
  
case MCVM_OSXVersionMin: return MachO::LC_VERSION_MIN_MACOSX3.07k
;
745
12.8k
  
case MCVM_IOSVersionMin: return MachO::LC_VERSION_MIN_IPHONEOS9.73k
;
746
12.8k
  
case MCVM_TvOSVersionMin: return MachO::LC_VERSION_MIN_TVOS2
;
747
12.8k
  
case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS3
;
748
0
  }
749
0
  llvm_unreachable("Invalid mc version min type");
750
0
}
751
752
uint64_t MachObjectWriter::writeObject(MCAssembler &Asm,
753
13.8k
                                       const MCAsmLayout &Layout) {
754
13.8k
  uint64_t StartOffset = W.OS.tell();
755
13.8k
756
13.8k
  // Compute symbol table information and bind symbol indices.
757
13.8k
  computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
758
13.8k
                     UndefinedSymbolData);
759
13.8k
760
13.8k
  unsigned NumSections = Asm.size();
761
13.8k
  const MCAssembler::VersionInfoType &VersionInfo =
762
13.8k
    Layout.getAssembler().getVersionInfo();
763
13.8k
764
13.8k
  // The section data starts after the header, the segment load command (and
765
13.8k
  // section headers) and the symbol table.
766
13.8k
  unsigned NumLoadCommands = 1;
767
13.8k
  uint64_t LoadCommandsSize = is64Bit() ?
768
10.3k
    sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
769
13.8k
    
sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section)3.51k
;
770
13.8k
771
13.8k
  // Add the deployment target version info load command size, if used.
772
13.8k
  if (VersionInfo.Major != 0) {
773
12.8k
    ++NumLoadCommands;
774
12.8k
    if (VersionInfo.EmitBuildVersion)
775
7
      LoadCommandsSize += sizeof(MachO::build_version_command);
776
12.8k
    else
777
12.8k
      LoadCommandsSize += sizeof(MachO::version_min_command);
778
12.8k
  }
779
13.8k
780
13.8k
  // Add the data-in-code load command size, if used.
781
13.8k
  unsigned NumDataRegions = Asm.getDataRegions().size();
782
13.8k
  if (NumDataRegions) {
783
878
    ++NumLoadCommands;
784
878
    LoadCommandsSize += sizeof(MachO::linkedit_data_command);
785
878
  }
786
13.8k
787
13.8k
  // Add the loh load command size, if used.
788
13.8k
  uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
789
13.8k
  uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 
810.3k
:
43.51k
);
790
13.8k
  if (LOHSize) {
791
6.54k
    ++NumLoadCommands;
792
6.54k
    LoadCommandsSize += sizeof(MachO::linkedit_data_command);
793
6.54k
  }
794
13.8k
795
13.8k
  // Add the symbol table load command sizes, if used.
796
13.8k
  unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
797
13.8k
    UndefinedSymbolData.size();
798
13.8k
  if (NumSymbols) {
799
12.8k
    NumLoadCommands += 2;
800
12.8k
    LoadCommandsSize += (sizeof(MachO::symtab_command) +
801
12.8k
                         sizeof(MachO::dysymtab_command));
802
12.8k
  }
803
13.8k
804
13.8k
  // Add the linker option load commands sizes.
805
13.8k
  for (const auto &Option : Asm.getLinkerOptions()) {
806
5
    ++NumLoadCommands;
807
5
    LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
808
5
  }
809
13.8k
810
13.8k
  // Compute the total size of the section data, as well as its file size and vm
811
13.8k
  // size.
812
13.8k
  uint64_t SectionDataStart = (is64Bit() ? 
sizeof(MachO::mach_header_64)10.3k
:
813
13.8k
                               
sizeof(MachO::mach_header)3.51k
) + LoadCommandsSize;
814
13.8k
  uint64_t SectionDataSize = 0;
815
13.8k
  uint64_t SectionDataFileSize = 0;
816
13.8k
  uint64_t VMSize = 0;
817
71.7k
  for (const MCSection &Sec : Asm) {
818
71.7k
    uint64_t Address = getSectionAddress(&Sec);
819
71.7k
    uint64_t Size = Layout.getSectionAddressSize(&Sec);
820
71.7k
    uint64_t FileSize = Layout.getSectionFileSize(&Sec);
821
71.7k
    FileSize += getPaddingSize(&Sec, Layout);
822
71.7k
823
71.7k
    VMSize = std::max(VMSize, Address + Size);
824
71.7k
825
71.7k
    if (Sec.isVirtualSection())
826
3.56k
      continue;
827
68.1k
828
68.1k
    SectionDataSize = std::max(SectionDataSize, Address + Size);
829
68.1k
    SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
830
68.1k
  }
831
13.8k
832
13.8k
  // The section data is padded to 4 bytes.
833
13.8k
  //
834
13.8k
  // FIXME: Is this machine dependent?
835
13.8k
  unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
836
13.8k
  SectionDataFileSize += SectionDataPadding;
837
13.8k
838
13.8k
  // Write the prolog, starting with the header and load command...
839
13.8k
  writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
840
13.8k
              Asm.getSubsectionsViaSymbols());
841
13.8k
  uint32_t Prot =
842
13.8k
      MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE;
843
13.8k
  writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
844
13.8k
                          SectionDataSize, Prot, Prot);
845
13.8k
846
13.8k
  // ... and then the section headers.
847
13.8k
  uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
848
71.7k
  for (const MCSection &Section : Asm) {
849
71.7k
    const auto &Sec = cast<MCSectionMachO>(Section);
850
71.7k
    std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
851
71.7k
    unsigned NumRelocs = Relocs.size();
852
71.7k
    uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
853
71.7k
    unsigned Flags = Sec.getTypeAndAttributes();
854
71.7k
    if (Sec.hasInstructions())
855
12.5k
      Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
856
71.7k
    writeSection(Layout, Sec, getSectionAddress(&Sec), SectionStart, Flags,
857
71.7k
                 RelocTableEnd, NumRelocs);
858
71.7k
    RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
859
71.7k
  }
860
13.8k
861
13.8k
  // Write out the deployment target information, if it's available.
862
13.8k
  if (VersionInfo.Major != 0) {
863
18.1k
    auto EncodeVersion = [](VersionTuple V) -> uint32_t {
864
18.1k
      assert(!V.empty() && "empty version");
865
18.1k
      unsigned Update = V.getSubminor() ? 
*V.getSubminor()12.8k
:
05.33k
;
866
18.1k
      unsigned Minor = V.getMinor() ? 
*V.getMinor()18.1k
:
01
;
867
18.1k
      assert(Update < 256 && "unencodable update target version");
868
18.1k
      assert(Minor < 256 && "unencodable minor target version");
869
18.1k
      assert(V.getMajor() < 65536 && "unencodable major target version");
870
18.1k
      return Update | (Minor << 8) | (V.getMajor() << 16);
871
18.1k
    };
872
12.8k
    uint32_t EncodedVersion = EncodeVersion(
873
12.8k
        VersionTuple(VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
874
12.8k
    uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
875
12.8k
                              ? 
EncodeVersion(VersionInfo.SDKVersion)5.33k
876
12.8k
                              : 
07.48k
;
877
12.8k
    if (VersionInfo.EmitBuildVersion) {
878
7
      // FIXME: Currently empty tools. Add clang version in the future.
879
7
      W.write<uint32_t>(MachO::LC_BUILD_VERSION);
880
7
      W.write<uint32_t>(sizeof(MachO::build_version_command));
881
7
      W.write<uint32_t>(VersionInfo.TypeOrPlatform.Platform);
882
7
      W.write<uint32_t>(EncodedVersion);
883
7
      W.write<uint32_t>(SDKVersion);
884
7
      W.write<uint32_t>(0);         // Empty tools list.
885
12.8k
    } else {
886
12.8k
      MachO::LoadCommandType LCType
887
12.8k
        = getLCFromMCVM(VersionInfo.TypeOrPlatform.Type);
888
12.8k
      W.write<uint32_t>(LCType);
889
12.8k
      W.write<uint32_t>(sizeof(MachO::version_min_command));
890
12.8k
      W.write<uint32_t>(EncodedVersion);
891
12.8k
      W.write<uint32_t>(SDKVersion);
892
12.8k
    }
893
12.8k
  }
894
13.8k
895
13.8k
  // Write the data-in-code load command, if used.
896
13.8k
  uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
897
13.8k
  if (NumDataRegions) {
898
878
    uint64_t DataRegionsOffset = RelocTableEnd;
899
878
    uint64_t DataRegionsSize = NumDataRegions * 8;
900
878
    writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
901
878
                             DataRegionsSize);
902
878
  }
903
13.8k
904
13.8k
  // Write the loh load command, if used.
905
13.8k
  uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
906
13.8k
  if (LOHSize)
907
6.54k
    writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
908
6.54k
                             DataInCodeTableEnd, LOHSize);
909
13.8k
910
13.8k
  // Write the symbol table load command, if used.
911
13.8k
  if (NumSymbols) {
912
12.8k
    unsigned FirstLocalSymbol = 0;
913
12.8k
    unsigned NumLocalSymbols = LocalSymbolData.size();
914
12.8k
    unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
915
12.8k
    unsigned NumExternalSymbols = ExternalSymbolData.size();
916
12.8k
    unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
917
12.8k
    unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
918
12.8k
    unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
919
12.8k
    unsigned NumSymTabSymbols =
920
12.8k
      NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
921
12.8k
    uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
922
12.8k
    uint64_t IndirectSymbolOffset = 0;
923
12.8k
924
12.8k
    // If used, the indirect symbols are written after the section data.
925
12.8k
    if (NumIndirectSymbols)
926
458
      IndirectSymbolOffset = LOHTableEnd;
927
12.8k
928
12.8k
    // The symbol table is written after the indirect symbol data.
929
12.8k
    uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
930
12.8k
931
12.8k
    // The string table is written after symbol table.
932
12.8k
    uint64_t StringTableOffset =
933
12.8k
      SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
934
9.79k
                                              sizeof(MachO::nlist_64) :
935
12.8k
                                              
sizeof(MachO::nlist)3.03k
);
936
12.8k
    writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
937
12.8k
                           StringTableOffset, StringTable.getSize());
938
12.8k
939
12.8k
    writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
940
12.8k
                             FirstExternalSymbol, NumExternalSymbols,
941
12.8k
                             FirstUndefinedSymbol, NumUndefinedSymbols,
942
12.8k
                             IndirectSymbolOffset, NumIndirectSymbols);
943
12.8k
  }
944
13.8k
945
13.8k
  // Write the linker options load commands.
946
13.8k
  for (const auto &Option : Asm.getLinkerOptions())
947
5
    writeLinkerOptionsLoadCommand(Option);
948
13.8k
949
13.8k
  // Write the actual section data.
950
71.7k
  for (const MCSection &Sec : Asm) {
951
71.7k
    Asm.writeSectionData(W.OS, &Sec, Layout);
952
71.7k
953
71.7k
    uint64_t Pad = getPaddingSize(&Sec, Layout);
954
71.7k
    W.OS.write_zeros(Pad);
955
71.7k
  }
956
13.8k
957
13.8k
  // Write the extra padding.
958
13.8k
  W.OS.write_zeros(SectionDataPadding);
959
13.8k
960
13.8k
  // Write the relocation entries.
961
71.7k
  for (const MCSection &Sec : Asm) {
962
71.7k
    // Write the section relocation entries, in reverse order to match 'as'
963
71.7k
    // (approximately, the exact algorithm is more complicated than this).
964
71.7k
    std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
965
3.59M
    for (const RelAndSymbol &Rel : make_range(Relocs.rbegin(), Relocs.rend())) {
966
3.59M
      W.write<uint32_t>(Rel.MRE.r_word0);
967
3.59M
      W.write<uint32_t>(Rel.MRE.r_word1);
968
3.59M
    }
969
71.7k
  }
970
13.8k
971
13.8k
  // Write out the data-in-code region payload, if there is one.
972
13.8k
  for (MCAssembler::const_data_region_iterator
973
13.8k
         it = Asm.data_region_begin(), ie = Asm.data_region_end();
974
15.0k
         it != ie; 
++it1.15k
) {
975
1.15k
    const DataRegionData *Data = &(*it);
976
1.15k
    uint64_t Start = getSymbolAddress(*Data->Start, Layout);
977
1.15k
    uint64_t End;
978
1.15k
    if (Data->End)
979
1.15k
      End = getSymbolAddress(*Data->End, Layout);
980
1
    else
981
1
      report_fatal_error("Data region not terminated");
982
1.15k
983
1.15k
    LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
984
1.15k
                      << "  start: " << Start << "(" << Data->Start->getName()
985
1.15k
                      << ")"
986
1.15k
                      << "  end: " << End << "(" << Data->End->getName() << ")"
987
1.15k
                      << "  size: " << End - Start << "\n");
988
1.15k
    W.write<uint32_t>(Start);
989
1.15k
    W.write<uint16_t>(End - Start);
990
1.15k
    W.write<uint16_t>(Data->Kind);
991
1.15k
  }
992
13.8k
993
13.8k
  // Write out the loh commands, if there is one.
994
13.8k
  
if (13.8k
LOHSize13.8k
) {
995
#ifndef NDEBUG
996
    unsigned Start = W.OS.tell();
997
#endif
998
    Asm.getLOHContainer().emit(*this, Layout);
999
6.54k
    // Pad to a multiple of the pointer size.
1000
6.54k
    W.OS.write_zeros(OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 
40
));
1001
6.54k
    assert(W.OS.tell() - Start == LOHSize);
1002
6.54k
  }
1003
13.8k
1004
13.8k
  // Write the symbol table data, if used.
1005
13.8k
  if (NumSymbols) {
1006
12.8k
    // Write the indirect symbol entries.
1007
12.8k
    for (MCAssembler::const_indirect_symbol_iterator
1008
12.8k
           it = Asm.indirect_symbol_begin(),
1009
14.5k
           ie = Asm.indirect_symbol_end(); it != ie; 
++it1.74k
) {
1010
1.74k
      // Indirect symbols in the non-lazy symbol pointer section have some
1011
1.74k
      // special handling.
1012
1.74k
      const MCSectionMachO &Section =
1013
1.74k
          static_cast<const MCSectionMachO &>(*it->Section);
1014
1.74k
      if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
1015
1.72k
        // If this symbol is defined and internal, mark it as such.
1016
1.72k
        if (it->Symbol->isDefined() && 
!it->Symbol->isExternal()16
) {
1017
3
          uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
1018
3
          if (it->Symbol->isAbsolute())
1019
1
            Flags |= MachO::INDIRECT_SYMBOL_ABS;
1020
3
          W.write<uint32_t>(Flags);
1021
3
          continue;
1022
3
        }
1023
1.73k
      }
1024
1.73k
1025
1.73k
      W.write<uint32_t>(it->Symbol->getIndex());
1026
1.73k
    }
1027
12.8k
1028
12.8k
    // FIXME: Check that offsets match computed ones.
1029
12.8k
1030
12.8k
    // Write the symbol table entries.
1031
12.8k
    for (auto *SymbolData :
1032
12.8k
         {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1033
38.4k
      for (MachSymbolData &Entry : *SymbolData)
1034
857k
        writeNlist(Entry, Layout);
1035
12.8k
1036
12.8k
    // Write the string table.
1037
12.8k
    StringTable.write(W.OS);
1038
12.8k
  }
1039
13.8k
1040
13.8k
  return W.OS.tell() - StartOffset;
1041
13.8k
}
1042
1043
std::unique_ptr<MCObjectWriter>
1044
llvm::createMachObjectWriter(std::unique_ptr<MCMachObjectTargetWriter> MOTW,
1045
16.6k
                             raw_pwrite_stream &OS, bool IsLittleEndian) {
1046
16.6k
  return llvm::make_unique<MachObjectWriter>(std::move(MOTW), OS,
1047
16.6k
                                             IsLittleEndian);
1048
16.6k
}