Coverage Report

Created: 2017-09-19 22:28

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp ---------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
10
///
11
/// \file For mach-o object files, this implementation converts from
12
/// mach-o on-disk binary format to in-memory normalized mach-o.
13
///
14
///                 +---------------+
15
///                 | binary mach-o |
16
///                 +---------------+
17
///                        |
18
///                        |
19
///                        v
20
///                  +------------+
21
///                  | normalized |
22
///                  +------------+
23
24
#include "ArchHandler.h"
25
#include "MachONormalizedFile.h"
26
#include "MachONormalizedFileBinaryUtils.h"
27
#include "lld/Core/Error.h"
28
#include "lld/Core/LLVM.h"
29
#include "lld/Core/SharedLibraryFile.h"
30
#include "llvm/ADT/STLExtras.h"
31
#include "llvm/ADT/SmallString.h"
32
#include "llvm/ADT/StringRef.h"
33
#include "llvm/ADT/StringSwitch.h"
34
#include "llvm/ADT/Twine.h"
35
#include "llvm/BinaryFormat/MachO.h"
36
#include "llvm/BinaryFormat/Magic.h"
37
#include "llvm/Object/MachO.h"
38
#include "llvm/Support/Casting.h"
39
#include "llvm/Support/Errc.h"
40
#include "llvm/Support/ErrorHandling.h"
41
#include "llvm/Support/FileOutputBuffer.h"
42
#include "llvm/Support/Host.h"
43
#include "llvm/Support/MemoryBuffer.h"
44
#include "llvm/Support/raw_ostream.h"
45
#include <functional>
46
#include <system_error>
47
48
using namespace llvm::MachO;
49
using llvm::object::ExportEntry;
50
using llvm::file_magic;
51
using llvm::object::MachOObjectFile;
52
53
namespace lld {
54
namespace mach_o {
55
namespace normalized {
56
57
// Utility to call a lambda expression on each load command.
58
static llvm::Error forEachLoadCommand(
59
    StringRef lcRange, unsigned lcCount, bool isBig, bool is64,
60
90
    std::function<bool(uint32_t cmd, uint32_t size, const char *lc)> func) {
61
90
  const char* p = lcRange.begin();
62
372
  for (unsigned i=0; 
i < lcCount372
;
++i282
) {
63
298
    const load_command *lc = reinterpret_cast<const load_command*>(p);
64
298
    load_command lcCopy;
65
298
    const load_command *slc = lc;
66
298
    if (
isBig != llvm::sys::IsBigEndianHost298
) {
67
12
      memcpy(&lcCopy, lc, sizeof(load_command));
68
12
      swapStruct(lcCopy);
69
12
      slc = &lcCopy;
70
12
    }
71
298
    if ( (p + slc->cmdsize) > lcRange.end() )
72
0
      return llvm::make_error<GenericError>("Load command exceeds range");
73
298
74
298
    
if (298
func(slc->cmd, slc->cmdsize, p)298
)
75
16
      return llvm::Error::success();
76
282
77
282
    p += slc->cmdsize;
78
282
  }
79
90
80
74
  return llvm::Error::success();
81
90
}
82
83
static std::error_code appendRelocations(Relocations &relocs, StringRef buffer,
84
                                         bool bigEndian,
85
86
                                         uint32_t reloff, uint32_t nreloc) {
86
86
  if ((reloff + nreloc*8) > buffer.size())
87
0
    return make_error_code(llvm::errc::executable_format_error);
88
86
  const any_relocation_info* relocsArray =
89
86
            reinterpret_cast<const any_relocation_info*>(buffer.begin()+reloff);
90
86
91
377
  for(uint32_t i=0; 
i < nreloc377
;
++i291
) {
92
291
    relocs.push_back(unpackRelocation(relocsArray[i], bigEndian));
93
291
  }
94
86
  return std::error_code();
95
86
}
96
97
static std::error_code
98
appendIndirectSymbols(IndirectSymbols &isyms, StringRef buffer, bool isBig,
99
                      uint32_t istOffset, uint32_t istCount,
100
0
                      uint32_t startIndex, uint32_t count) {
101
0
  if ((istOffset + istCount*4) > buffer.size())
102
0
    return make_error_code(llvm::errc::executable_format_error);
103
0
  
if (0
startIndex+count > istCount0
)
104
0
    return make_error_code(llvm::errc::executable_format_error);
105
0
  const uint8_t *indirectSymbolArray = (const uint8_t *)buffer.data();
106
0
107
0
  for(uint32_t i=0; 
i < count0
;
++i0
) {
108
0
    isyms.push_back(read32(
109
0
        indirectSymbolArray + (startIndex + i) * sizeof(uint32_t), isBig));
110
0
  }
111
0
  return std::error_code();
112
0
}
113
114
115
418
template <typename T> static T readBigEndian(T t) {
116
418
  if (llvm::sys::IsLittleEndianHost)
117
418
    llvm::sys::swapByteOrder(t);
118
418
  return t;
119
418
}
120
121
122
46
static bool isMachOHeader(const mach_header *mh, bool &is64, bool &isBig) {
123
46
  switch (read32(&mh->magic, false)) {
124
15
  case llvm::MachO::MH_MAGIC:
125
15
    is64 = false;
126
15
    isBig = false;
127
15
    return true;
128
28
  case llvm::MachO::MH_MAGIC_64:
129
28
    is64 = true;
130
28
    isBig = false;
131
28
    return true;
132
3
  case llvm::MachO::MH_CIGAM:
133
3
    is64 = false;
134
3
    isBig = true;
135
3
    return true;
136
0
  case llvm::MachO::MH_CIGAM_64:
137
0
    is64 = true;
138
0
    isBig = true;
139
0
    return true;
140
0
  default:
141
0
    return false;
142
0
  }
143
0
}
144
145
146
1
bool isThinObjectFile(StringRef path, MachOLinkingContext::Arch &arch) {
147
1
  // Try opening and mapping file at path.
148
1
  ErrorOr<std::unique_ptr<MemoryBuffer>> b = MemoryBuffer::getFileOrSTDIN(path);
149
1
  if (b.getError())
150
0
    return false;
151
1
152
1
  // If file length < 32 it is too small to be mach-o object file.
153
1
  StringRef fileBuffer = b->get()->getBuffer();
154
1
  if (fileBuffer.size() < 32)
155
0
    return false;
156
1
157
1
  // If file buffer does not start with MH_MAGIC (and variants), not obj file.
158
1
  const mach_header *mh = reinterpret_cast<const mach_header *>(
159
1
                                                            fileBuffer.begin());
160
1
  bool is64, isBig;
161
1
  if (!isMachOHeader(mh, is64, isBig))
162
0
    return false;
163
1
164
1
  // If not MH_OBJECT, not object file.
165
1
  
if (1
read32(&mh->filetype, isBig) != MH_OBJECT1
)
166
0
    return false;
167
1
168
1
  // Lookup up arch from cpu/subtype pair.
169
1
  arch = MachOLinkingContext::archFromCpuType(
170
1
      read32(&mh->cputype, isBig),
171
1
      read32(&mh->cpusubtype, isBig));
172
1
  return true;
173
1
}
174
175
bool sliceFromFatFile(MemoryBufferRef mb, MachOLinkingContext::Arch arch,
176
361
                      uint32_t &offset, uint32_t &size) {
177
361
  const char *start = mb.getBufferStart();
178
361
  const llvm::MachO::fat_header *fh =
179
361
      reinterpret_cast<const llvm::MachO::fat_header *>(start);
180
361
  if (readBigEndian(fh->magic) != llvm::MachO::FAT_MAGIC)
181
351
    return false;
182
10
  uint32_t nfat_arch = readBigEndian(fh->nfat_arch);
183
10
  const fat_arch *fstart =
184
10
      reinterpret_cast<const fat_arch *>(start + sizeof(fat_header));
185
10
  const fat_arch *fend =
186
10
      reinterpret_cast<const fat_arch *>(start + sizeof(fat_header) +
187
10
                                         sizeof(fat_arch) * nfat_arch);
188
10
  const uint32_t reqCpuType = MachOLinkingContext::cpuTypeFromArch(arch);
189
10
  const uint32_t reqCpuSubtype = MachOLinkingContext::cpuSubtypeFromArch(arch);
190
17
  for (const fat_arch *fa = fstart; 
fa < fend17
;
++fa7
) {
191
17
    if ((readBigEndian(fa->cputype) == reqCpuType) &&
192
17
        
(readBigEndian(fa->cpusubtype) == reqCpuSubtype)10
) {
193
10
      offset = readBigEndian(fa->offset);
194
10
      size = readBigEndian(fa->size);
195
10
      if ((offset + size) > mb.getBufferSize())
196
0
        return false;
197
10
      return true;
198
10
    }
199
17
  }
200
0
  return false;
201
361
}
202
203
/// Reads a mach-o file and produces an in-memory normalized view.
204
llvm::Expected<std::unique_ptr<NormalizedFile>>
205
readBinary(std::unique_ptr<MemoryBuffer> &mb,
206
45
           const MachOLinkingContext::Arch arch) {
207
45
  // Make empty NormalizedFile.
208
45
  std::unique_ptr<NormalizedFile> f(new NormalizedFile());
209
45
210
45
  const char *start = mb->getBufferStart();
211
45
  size_t objSize = mb->getBufferSize();
212
45
  const mach_header *mh = reinterpret_cast<const mach_header *>(start);
213
45
214
45
  uint32_t sliceOffset;
215
45
  uint32_t sliceSize;
216
45
  if (
sliceFromFatFile(mb->getMemBufferRef(), arch, sliceOffset, sliceSize)45
) {
217
2
    start = &start[sliceOffset];
218
2
    objSize = sliceSize;
219
2
    mh = reinterpret_cast<const mach_header *>(start);
220
2
  }
221
45
222
45
  // Determine endianness and pointer size for mach-o file.
223
45
  bool is64, isBig;
224
45
  if (!isMachOHeader(mh, is64, isBig))
225
0
    return llvm::make_error<GenericError>("File is not a mach-o");
226
45
227
45
  // Endian swap header, if needed.
228
45
  mach_header headerCopy;
229
45
  const mach_header *smh = mh;
230
45
  if (
isBig != llvm::sys::IsBigEndianHost45
) {
231
3
    memcpy(&headerCopy, mh, sizeof(mach_header));
232
3
    swapStruct(headerCopy);
233
3
    smh = &headerCopy;
234
3
  }
235
45
236
45
  // Validate head and load commands fit in buffer.
237
45
  const uint32_t lcCount = smh->ncmds;
238
45
  const char *lcStart =
239
45
      start + (is64 ? 
sizeof(mach_header_64)28
:
sizeof(mach_header)17
);
240
45
  StringRef lcRange(lcStart, smh->sizeofcmds);
241
45
  if (lcRange.end() > (start + objSize))
242
0
    return llvm::make_error<GenericError>("Load commands exceed file size");
243
45
244
45
  // Get architecture from mach_header.
245
45
  f->arch = MachOLinkingContext::archFromCpuType(smh->cputype, smh->cpusubtype);
246
45
  if (
f->arch != arch45
) {
247
0
    return llvm::make_error<GenericError>(
248
0
                                  Twine("file is wrong architecture. Expected "
249
0
                                  "(" + MachOLinkingContext::nameFromArch(arch)
250
0
                                  + ") found ("
251
0
                                  + MachOLinkingContext::nameFromArch(f->arch)
252
0
                                  + ")" ));
253
0
  }
254
45
  // Copy file type and flags
255
45
  f->fileType = HeaderFileType(smh->filetype);
256
45
  f->flags = smh->flags;
257
45
258
45
259
45
  // Pre-scan load commands looking for indirect symbol table.
260
45
  uint32_t indirectSymbolTableOffset = 0;
261
45
  uint32_t indirectSymbolTableCount = 0;
262
45
  auto ec = forEachLoadCommand(lcRange, lcCount, isBig, is64,
263
45
                               [&](uint32_t cmd, uint32_t size,
264
138
                                   const char *lc) -> bool {
265
138
    if (
cmd == LC_DYSYMTAB138
) {
266
16
      const dysymtab_command *d = reinterpret_cast<const dysymtab_command*>(lc);
267
16
      indirectSymbolTableOffset = read32(&d->indirectsymoff, isBig);
268
16
      indirectSymbolTableCount = read32(&d->nindirectsyms, isBig);
269
16
      return true;
270
16
    }
271
122
    return false;
272
122
  });
273
45
  if (ec)
274
0
    return std::move(ec);
275
45
276
45
  // Walk load commands looking for segments/sections and the symbol table.
277
45
  const data_in_code_entry *dataInCode = nullptr;
278
45
  const dyld_info_command *dyldInfo = nullptr;
279
45
  uint32_t dataInCodeSize = 0;
280
45
  ec = forEachLoadCommand(lcRange, lcCount, isBig, is64,
281
160
                    [&] (uint32_t cmd, uint32_t size, const char* lc) -> bool {
282
160
    switch(cmd) {
283
33
    case LC_SEGMENT_64:
284
33
      if (
is6433
) {
285
33
        const segment_command_64 *seg =
286
33
                              reinterpret_cast<const segment_command_64*>(lc);
287
33
        const unsigned sectionCount = read32(&seg->nsects, isBig);
288
33
        const section_64 *sects = reinterpret_cast<const section_64*>
289
33
                                  (lc + sizeof(segment_command_64));
290
33
        const unsigned lcSize = sizeof(segment_command_64)
291
33
                                              + sectionCount*sizeof(section_64);
292
33
        // Verify sections don't extend beyond end of segment load command.
293
33
        if (lcSize > size)
294
0
          return true;
295
96
        
for (unsigned i=0; 33
i < sectionCount96
;
++i63
) {
296
63
          const section_64 *sect = &sects[i];
297
63
          Section section;
298
63
          section.segmentName = getString16(sect->segname);
299
63
          section.sectionName = getString16(sect->sectname);
300
63
          section.type = (SectionType)(read32(&sect->flags, isBig) &
301
63
                                       SECTION_TYPE);
302
63
          section.attributes  = read32(&sect->flags, isBig) & SECTION_ATTRIBUTES;
303
63
          section.alignment   = 1 << read32(&sect->align, isBig);
304
63
          section.address     = read64(&sect->addr, isBig);
305
63
          const uint8_t *content =
306
63
            (const uint8_t *)start + read32(&sect->offset, isBig);
307
63
          size_t contentSize = read64(&sect->size, isBig);
308
63
          // Note: this assign() is copying the content bytes.  Ideally,
309
63
          // we can use a custom allocator for vector to avoid the copy.
310
63
          section.content = llvm::makeArrayRef(content, contentSize);
311
63
          appendRelocations(section.relocations, mb->getBuffer(), isBig,
312
63
                            read32(&sect->reloff, isBig),
313
63
                            read32(&sect->nreloc, isBig));
314
63
          if (
section.type == S_NON_LAZY_SYMBOL_POINTERS63
) {
315
0
            appendIndirectSymbols(section.indirectSymbols, mb->getBuffer(),
316
0
                                  isBig,
317
0
                                  indirectSymbolTableOffset,
318
0
                                  indirectSymbolTableCount,
319
0
                                  read32(&sect->reserved1, isBig),
320
0
                                  contentSize/4);
321
0
          }
322
63
          f->sections.push_back(section);
323
63
        }
324
33
      }
325
33
      break;
326
17
    case LC_SEGMENT:
327
17
      if (
!is6417
) {
328
17
        const segment_command *seg =
329
17
                              reinterpret_cast<const segment_command*>(lc);
330
17
        const unsigned sectionCount = read32(&seg->nsects, isBig);
331
17
        const section *sects = reinterpret_cast<const section*>
332
17
                                  (lc + sizeof(segment_command));
333
17
        const unsigned lcSize = sizeof(segment_command)
334
17
                                              + sectionCount*sizeof(section);
335
17
        // Verify sections don't extend beyond end of segment load command.
336
17
        if (lcSize > size)
337
0
          return true;
338
40
        
for (unsigned i=0; 17
i < sectionCount40
;
++i23
) {
339
23
          const section *sect = &sects[i];
340
23
          Section section;
341
23
          section.segmentName = getString16(sect->segname);
342
23
          section.sectionName = getString16(sect->sectname);
343
23
          section.type = (SectionType)(read32(&sect->flags, isBig) &
344
23
                                       SECTION_TYPE);
345
23
          section.attributes =
346
23
              read32((const uint8_t *)&sect->flags, isBig) & SECTION_ATTRIBUTES;
347
23
          section.alignment   = 1 << read32(&sect->align, isBig);
348
23
          section.address     = read32(&sect->addr, isBig);
349
23
          const uint8_t *content =
350
23
            (const uint8_t *)start + read32(&sect->offset, isBig);
351
23
          size_t contentSize = read32(&sect->size, isBig);
352
23
          // Note: this assign() is copying the content bytes.  Ideally,
353
23
          // we can use a custom allocator for vector to avoid the copy.
354
23
          section.content = llvm::makeArrayRef(content, contentSize);
355
23
          appendRelocations(section.relocations, mb->getBuffer(), isBig,
356
23
                            read32(&sect->reloff, isBig),
357
23
                            read32(&sect->nreloc, isBig));
358
23
          if (
section.type == S_NON_LAZY_SYMBOL_POINTERS23
) {
359
0
            appendIndirectSymbols(
360
0
                section.indirectSymbols, mb->getBuffer(), isBig,
361
0
                indirectSymbolTableOffset, indirectSymbolTableCount,
362
0
                read32(&sect->reserved1, isBig), contentSize / 4);
363
0
          }
364
23
          f->sections.push_back(section);
365
23
        }
366
17
      }
367
17
      break;
368
39
    case LC_SYMTAB: {
369
39
      const symtab_command *st = reinterpret_cast<const symtab_command*>(lc);
370
39
      const char *strings = start + read32(&st->stroff, isBig);
371
39
      const uint32_t strSize = read32(&st->strsize, isBig);
372
39
      // Validate string pool and symbol table all in buffer.
373
39
      if (read32((const uint8_t *)&st->stroff, isBig) +
374
39
              read32((const uint8_t *)&st->strsize, isBig) >
375
39
          objSize)
376
0
        return true;
377
39
      
if (39
is6439
) {
378
26
        const uint32_t symOffset = read32(&st->symoff, isBig);
379
26
        const uint32_t symCount = read32(&st->nsyms, isBig);
380
26
        if ( symOffset+(symCount*sizeof(nlist_64)) > objSize)
381
0
          return true;
382
26
        const nlist_64 *symbols =
383
26
            reinterpret_cast<const nlist_64 *>(start + symOffset);
384
26
        // Convert each nlist_64 to a lld::mach_o::normalized::Symbol.
385
99
        for(uint32_t i=0; 
i < symCount99
;
++i73
) {
386
73
          nlist_64 tempSym;
387
73
          memcpy(&tempSym, &symbols[i], sizeof(nlist_64));
388
73
          const nlist_64 *sin = &tempSym;
389
73
          if (isBig != llvm::sys::IsBigEndianHost)
390
0
            swapStruct(tempSym);
391
73
          Symbol sout;
392
73
          if (sin->n_strx > strSize)
393
0
            return true;
394
73
          sout.name  = &strings[sin->n_strx];
395
73
          sout.type = static_cast<NListType>(sin->n_type & (N_STAB|N_TYPE));
396
73
          sout.scope = (sin->n_type & (N_PEXT|N_EXT));
397
73
          sout.sect  = sin->n_sect;
398
73
          sout.desc  = sin->n_desc;
399
73
          sout.value = sin->n_value;
400
73
          if (sin->n_type & N_STAB)
401
0
            f->stabsSymbols.push_back(sout);
402
73
          else 
if (73
sout.type == N_UNDF73
)
403
20
            f->undefinedSymbols.push_back(sout);
404
53
          else 
if (53
sin->n_type & N_EXT53
)
405
30
            f->globalSymbols.push_back(sout);
406
53
          else
407
23
            f->localSymbols.push_back(sout);
408
73
        }
409
39
      } else {
410
13
        const uint32_t symOffset = read32(&st->symoff, isBig);
411
13
        const uint32_t symCount = read32(&st->nsyms, isBig);
412
13
        if ( symOffset+(symCount*sizeof(nlist)) > objSize)
413
0
          return true;
414
13
        const nlist *symbols =
415
13
            reinterpret_cast<const nlist *>(start + symOffset);
416
13
        // Convert each nlist to a lld::mach_o::normalized::Symbol.
417
52
        for(uint32_t i=0; 
i < symCount52
;
++i39
) {
418
39
          const nlist *sin = &symbols[i];
419
39
          nlist tempSym;
420
39
          if (
isBig != llvm::sys::IsBigEndianHost39
) {
421
5
            tempSym = *sin; swapStruct(tempSym); sin = &tempSym;
422
5
          }
423
39
          Symbol sout;
424
39
          if (sin->n_strx > strSize)
425
0
            return true;
426
39
          sout.name  = &strings[sin->n_strx];
427
39
          sout.type  = (NListType)(sin->n_type & N_TYPE);
428
39
          sout.scope = (sin->n_type & (N_PEXT|N_EXT));
429
39
          sout.sect  = sin->n_sect;
430
39
          sout.desc  = sin->n_desc;
431
39
          sout.value = sin->n_value;
432
39
          if (sout.type == N_UNDF)
433
9
            f->undefinedSymbols.push_back(sout);
434
30
          else 
if (30
sout.scope == (SymbolScope)N_EXT30
)
435
12
            f->globalSymbols.push_back(sout);
436
18
          else 
if (18
sin->n_type & N_STAB18
)
437
0
            f->stabsSymbols.push_back(sout);
438
18
          else
439
18
            f->localSymbols.push_back(sout);
440
39
        }
441
13
      }
442
39
      }
443
39
      break;
444
4
    case LC_ID_DYLIB: {
445
4
      const dylib_command *dl = reinterpret_cast<const dylib_command*>(lc);
446
4
      f->installName = lc + read32(&dl->dylib.name, isBig);
447
4
      f->currentVersion = read32(&dl->dylib.current_version, isBig);
448
4
      f->compatVersion = read32(&dl->dylib.compatibility_version, isBig);
449
4
      }
450
4
      break;
451
23
    case LC_DATA_IN_CODE: {
452
23
      const linkedit_data_command *ldc =
453
23
                            reinterpret_cast<const linkedit_data_command*>(lc);
454
23
      dataInCode = reinterpret_cast<const data_in_code_entry *>(
455
23
          start + read32(&ldc->dataoff, isBig));
456
23
      dataInCodeSize = read32(&ldc->datasize, isBig);
457
23
      }
458
23
      break;
459
4
    case LC_LOAD_DYLIB:
460
4
    case LC_LOAD_WEAK_DYLIB:
461
4
    case LC_REEXPORT_DYLIB:
462
4
    case LC_LOAD_UPWARD_DYLIB: {
463
4
      const dylib_command *dl = reinterpret_cast<const dylib_command*>(lc);
464
4
      DependentDylib entry;
465
4
      entry.path = lc + read32(&dl->dylib.name, isBig);
466
4
      entry.kind = LoadCommandType(cmd);
467
4
      entry.compatVersion = read32(&dl->dylib.compatibility_version, isBig);
468
4
      entry.currentVersion = read32(&dl->dylib.current_version, isBig);
469
4
      f->dependentDylibs.push_back(entry);
470
4
     }
471
4
      break;
472
0
    case LC_RPATH: {
473
0
      const rpath_command *rpc = reinterpret_cast<const rpath_command *>(lc);
474
0
      f->rpaths.push_back(lc + read32(&rpc->path, isBig));
475
0
     }
476
0
      break;
477
4
    case LC_DYLD_INFO:
478
4
    case LC_DYLD_INFO_ONLY:
479
4
      dyldInfo = reinterpret_cast<const dyld_info_command*>(lc);
480
4
      break;
481
10
    case LC_VERSION_MIN_MACOSX:
482
10
    case LC_VERSION_MIN_IPHONEOS:
483
10
    case LC_VERSION_MIN_WATCHOS:
484
10
    case LC_VERSION_MIN_TVOS:
485
10
      // If we are emitting an object file, then we may take the load command
486
10
      // kind from these commands and pass it on to the output
487
10
      // file.
488
10
      f->minOSVersionKind = (LoadCommandType)cmd;
489
10
      break;
490
160
    }
491
160
    return false;
492
160
  });
493
45
  if (ec)
494
0
    return std::move(ec);
495
45
496
45
  
if (45
dataInCode45
) {
497
23
    // Convert on-disk data_in_code_entry array to DataInCode vector.
498
33
    for (unsigned i=0; 
i < dataInCodeSize/sizeof(data_in_code_entry)33
;
++i10
) {
499
10
      DataInCode entry;
500
10
      entry.offset = read32(&dataInCode[i].offset, isBig);
501
10
      entry.length = read16(&dataInCode[i].length, isBig);
502
10
      entry.kind =
503
10
          (DataRegionType)read16((const uint8_t *)&dataInCode[i].kind, isBig);
504
10
      f->dataInCode.push_back(entry);
505
10
    }
506
23
  }
507
45
508
45
  if (
dyldInfo45
) {
509
4
    // If any exports, extract and add to normalized exportInfo vector.
510
4
    if (
dyldInfo->export_size4
) {
511
4
      const uint8_t *trieStart = reinterpret_cast<const uint8_t *>(
512
4
          start + read32(&dyldInfo->export_off, isBig));
513
4
      ArrayRef<uint8_t> trie(trieStart, read32(&dyldInfo->export_size, isBig));
514
4
      Error Err = Error::success();
515
4
      for (const ExportEntry &trieExport : MachOObjectFile::exports(Err, trie)) {
516
4
        Export normExport;
517
4
        normExport.name = trieExport.name().copy(f->ownedAllocations);
518
4
        normExport.offset = trieExport.address();
519
4
        normExport.kind = ExportSymbolKind(trieExport.flags() & EXPORT_SYMBOL_FLAGS_KIND_MASK);
520
4
        normExport.flags = trieExport.flags() & ~EXPORT_SYMBOL_FLAGS_KIND_MASK;
521
4
        normExport.otherOffset = trieExport.other();
522
4
        if (!trieExport.otherName().empty())
523
0
          normExport.otherName = trieExport.otherName().copy(f->ownedAllocations);
524
4
        f->exportInfo.push_back(normExport);
525
4
      }
526
4
      if (Err)
527
0
        return std::move(Err);
528
45
    }
529
4
  }
530
45
531
45
  return std::move(f);
532
45
}
533
534
class MachOObjectReader : public Reader {
535
public:
536
223
  MachOObjectReader(MachOLinkingContext &ctx) : _ctx(ctx) {}
537
538
322
  bool canParse(file_magic magic, MemoryBufferRef mb) const override {
539
27
    return (magic == file_magic::macho_object && mb.getBufferSize() > 32);
540
322
  }
541
542
  ErrorOr<std::unique_ptr<File>>
543
  loadFile(std::unique_ptr<MemoryBuffer> mb,
544
27
           const Registry &registry) const override {
545
27
    std::unique_ptr<File> ret =
546
27
      llvm::make_unique<MachOFile>(std::move(mb), &_ctx);
547
27
    return std::move(ret);
548
27
  }
549
550
private:
551
  MachOLinkingContext &_ctx;
552
};
553
554
class MachODylibReader : public Reader {
555
public:
556
223
  MachODylibReader(MachOLinkingContext &ctx) : _ctx(ctx) {}
557
558
295
  bool canParse(file_magic magic, MemoryBufferRef mb) const override {
559
295
    switch (magic) {
560
4
    case file_magic::macho_dynamically_linked_shared_lib:
561
4
    case file_magic::macho_dynamically_linked_shared_lib_stub:
562
4
      return mb.getBufferSize() > 32;
563
291
    default:
564
291
      return false;
565
0
    }
566
0
  }
567
568
  ErrorOr<std::unique_ptr<File>>
569
  loadFile(std::unique_ptr<MemoryBuffer> mb,
570
4
           const Registry &registry) const override {
571
4
    std::unique_ptr<File> ret =
572
4
        llvm::make_unique<MachODylibFile>(std::move(mb), &_ctx);
573
4
    return std::move(ret);
574
4
  }
575
576
private:
577
  MachOLinkingContext &_ctx;
578
};
579
580
} // namespace normalized
581
} // namespace mach_o
582
583
223
void Registry::addSupportMachOObjects(MachOLinkingContext &ctx) {
584
223
  MachOLinkingContext::Arch arch = ctx.arch();
585
223
  add(std::unique_ptr<Reader>(new mach_o::normalized::MachOObjectReader(ctx)));
586
223
  add(std::unique_ptr<Reader>(new mach_o::normalized::MachODylibReader(ctx)));
587
223
  addKindTable(Reference::KindNamespace::mach_o, ctx.archHandler().kindArch(),
588
223
               ctx.archHandler().kindStrings());
589
223
  add(std::unique_ptr<YamlIOTaggedDocumentHandler>(
590
223
                           new mach_o::MachOYamlIOTaggedDocumentHandler(arch)));
591
223
}
592
593
594
} // namespace lld