Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/lld/lib/ReaderWriter/MachO/MachOLinkingContext.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- lib/ReaderWriter/MachO/MachOLinkingContext.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
#include "lld/ReaderWriter/MachOLinkingContext.h"
11
#include "ArchHandler.h"
12
#include "File.h"
13
#include "FlatNamespaceFile.h"
14
#include "MachONormalizedFile.h"
15
#include "MachOPasses.h"
16
#include "SectCreateFile.h"
17
#include "lld/Core/ArchiveLibraryFile.h"
18
#include "lld/Core/PassManager.h"
19
#include "lld/Core/Reader.h"
20
#include "lld/Core/Writer.h"
21
#include "lld/Driver/Driver.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/StringExtras.h"
24
#include "llvm/ADT/Triple.h"
25
#include "llvm/BinaryFormat/MachO.h"
26
#include "llvm/Demangle/Demangle.h"
27
#include "llvm/Support/Debug.h"
28
#include "llvm/Support/Errc.h"
29
#include "llvm/Support/Host.h"
30
#include "llvm/Support/Path.h"
31
#include <algorithm>
32
33
using lld::mach_o::ArchHandler;
34
using lld::mach_o::MachOFile;
35
using lld::mach_o::MachODylibFile;
36
using namespace llvm::MachO;
37
38
namespace lld {
39
40
456
bool MachOLinkingContext::parsePackedVersion(StringRef str, uint32_t &result) {
41
456
  result = 0;
42
456
43
456
  if (str.empty())
44
0
    return false;
45
456
46
456
  SmallVector<StringRef, 3> parts;
47
456
  llvm::SplitString(str, parts, ".");
48
456
49
456
  unsigned long long num;
50
456
  if (llvm::getAsUnsignedInteger(parts[0], 10, num))
51
0
    return true;
52
456
  
if (456
num > 65535456
)
53
0
    return true;
54
456
  result = num << 16;
55
456
56
456
  if (
parts.size() > 1456
) {
57
456
    if (llvm::getAsUnsignedInteger(parts[1], 10, num))
58
1
      return true;
59
455
    
if (455
num > 255455
)
60
0
      return true;
61
455
    result |= (num << 8);
62
455
  }
63
456
64
455
  
if (455
parts.size() > 2455
) {
65
3
    if (llvm::getAsUnsignedInteger(parts[2], 10, num))
66
0
      return true;
67
3
    
if (3
num > 2553
)
68
0
      return true;
69
3
    result |= num;
70
3
  }
71
455
72
455
  return false;
73
456
}
74
75
2
bool MachOLinkingContext::parsePackedVersion(StringRef str, uint64_t &result) {
76
2
  result = 0;
77
2
78
2
  if (str.empty())
79
0
    return false;
80
2
81
2
  SmallVector<StringRef, 5> parts;
82
2
  llvm::SplitString(str, parts, ".");
83
2
84
2
  unsigned long long num;
85
2
  if (llvm::getAsUnsignedInteger(parts[0], 10, num))
86
0
    return true;
87
2
  
if (2
num > 0xFFFFFF2
)
88
0
    return true;
89
2
  result = num << 40;
90
2
91
2
  unsigned Shift = 30;
92
5
  for (StringRef str : llvm::makeArrayRef(parts).slice(1)) {
93
5
    if (llvm::getAsUnsignedInteger(str, 10, num))
94
1
      return true;
95
4
    
if (4
num > 0x3FF4
)
96
0
      return true;
97
4
    result |= (num << Shift);
98
4
    Shift -= 10;
99
4
  }
100
2
101
1
  return false;
102
2
}
103
104
MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
105
  { "x86_64", arch_x86_64, true,  CPU_TYPE_X86_64,  CPU_SUBTYPE_X86_64_ALL },
106
  { "i386",   arch_x86,    true,  CPU_TYPE_I386,    CPU_SUBTYPE_X86_ALL },
107
  { "ppc",    arch_ppc,    false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
108
  { "armv6",  arch_armv6,  true,  CPU_TYPE_ARM,     CPU_SUBTYPE_ARM_V6 },
109
  { "armv7",  arch_armv7,  true,  CPU_TYPE_ARM,     CPU_SUBTYPE_ARM_V7 },
110
  { "armv7s", arch_armv7s, true,  CPU_TYPE_ARM,     CPU_SUBTYPE_ARM_V7S },
111
  { "arm64",  arch_arm64,  true,  CPU_TYPE_ARM64,   CPU_SUBTYPE_ARM64_ALL },
112
  { "",       arch_unknown,false, 0,                0 }
113
};
114
115
MachOLinkingContext::Arch
116
46
MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
117
127
  for (ArchInfo *info = _s_archInfos; 
!info->archName.empty()127
;
++info81
) {
118
127
    if (
(info->cputype == cputype) && 127
(info->cpusubtype == cpusubtype)54
)
119
46
      return info->arch;
120
127
  }
121
0
  return arch_unknown;
122
46
}
123
124
MachOLinkingContext::Arch
125
249
MachOLinkingContext::archFromName(StringRef archName) {
126
490
  for (ArchInfo *info = _s_archInfos; 
!info->archName.empty()490
;
++info241
) {
127
490
    if (info->archName.equals(archName))
128
249
      return info->arch;
129
490
  }
130
0
  return arch_unknown;
131
249
}
132
133
5
StringRef MachOLinkingContext::nameFromArch(Arch arch) {
134
6
  for (ArchInfo *info = _s_archInfos; 
!info->archName.empty()6
;
++info1
) {
135
6
    if (info->arch == arch)
136
5
      return info->archName;
137
6
  }
138
0
  return "<unknown>";
139
5
}
140
141
186
uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
142
186
  assert(arch != arch_unknown);
143
381
  for (ArchInfo *info = _s_archInfos; 
!info->archName.empty()381
;
++info195
) {
144
381
    if (info->arch == arch)
145
186
      return info->cputype;
146
381
  }
147
0
  
llvm_unreachable0
("Unknown arch type");
148
0
}
149
150
187
uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
151
187
  assert(arch != arch_unknown);
152
382
  for (ArchInfo *info = _s_archInfos; 
!info->archName.empty()382
;
++info195
) {
153
382
    if (info->arch == arch)
154
187
      return info->cpusubtype;
155
382
  }
156
0
  
llvm_unreachable0
("Unknown arch type");
157
0
}
158
159
1
bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
160
1
  return mach_o::normalized::isThinObjectFile(path, arch);
161
1
}
162
163
bool MachOLinkingContext::sliceFromFatFile(MemoryBufferRef mb, uint32_t &offset,
164
316
                                           uint32_t &size) {
165
316
  return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
166
316
}
167
168
242
MachOLinkingContext::MachOLinkingContext() {}
169
170
242
MachOLinkingContext::~MachOLinkingContext() {
171
242
  // Atoms are allocated on BumpPtrAllocator's on File's.
172
242
  // As we transfer atoms from one file to another, we need to clear all of the
173
242
  // atoms before we remove any of the BumpPtrAllocator's.
174
242
  auto &nodes = getNodes();
175
1.65k
  for (unsigned i = 0, e = nodes.size(); 
i != e1.65k
;
++i1.41k
) {
176
1.41k
    FileNode *node = dyn_cast<FileNode>(nodes[i].get());
177
1.41k
    if (!node)
178
182
      continue;
179
1.23k
    File *file = node->getFile();
180
1.23k
    file->clearAtoms();
181
1.23k
  }
182
242
}
183
184
void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
185
                                    uint32_t minOSVersion,
186
241
                                    bool exportDynamicSymbols) {
187
241
  _outputMachOType = type;
188
241
  _arch = arch;
189
241
  _os = os;
190
241
  _osMinVersion = minOSVersion;
191
241
192
241
  // If min OS not specified on command line, use reasonable defaults.
193
241
  // Note that we only do sensible defaults when emitting something other than
194
241
  // object and preload.
195
241
  if (_outputMachOType != llvm::MachO::MH_OBJECT &&
196
241
      
_outputMachOType != llvm::MachO::MH_PRELOAD152
) {
197
151
    if (
minOSVersion == 0151
) {
198
95
      switch (_arch) {
199
76
      case arch_x86_64:
200
76
      case arch_x86:
201
76
        parsePackedVersion("10.8", _osMinVersion);
202
76
        _os = MachOLinkingContext::OS::macOSX;
203
76
        break;
204
14
      case arch_armv6:
205
14
      case arch_armv7:
206
14
      case arch_armv7s:
207
14
      case arch_arm64:
208
14
        parsePackedVersion("7.0", _osMinVersion);
209
14
        _os = MachOLinkingContext::OS::iOS;
210
14
        break;
211
5
      default:
212
5
        break;
213
241
      }
214
241
    }
215
151
  }
216
241
217
241
  switch (_outputMachOType) {
218
92
  case llvm::MachO::MH_EXECUTE:
219
92
    // If targeting newer OS, use _main
220
92
    if (
minOS("10.8", "6.0")92
) {
221
79
      _entrySymbolName = "_main";
222
92
    } else {
223
13
      // If targeting older OS, use start (in crt1.o)
224
13
      _entrySymbolName = "start";
225
13
    }
226
92
227
92
    // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
228
92
    // support) and 4KB on 32-bit.
229
92
    if (
is64Bit(_arch)92
) {
230
66
      _pageZeroSize = 0x100000000;
231
92
    } else {
232
26
      _pageZeroSize = 0x1000;
233
26
    }
234
92
235
92
    // Initial base address is __PAGEZERO size.
236
92
    _baseAddress = _pageZeroSize;
237
92
238
92
    // Make PIE by default when targetting newer OSs.
239
92
    switch (os) {
240
32
      case OS::macOSX:
241
32
        if (minOSVersion >= 0x000A0700) // MacOSX 10.7
242
29
          _pie = true;
243
32
        break;
244
2
      case OS::iOS:
245
2
        if (minOSVersion >= 0x00040300) // iOS 4.3
246
2
          _pie = true;
247
2
       break;
248
3
       case OS::iOS_simulator:
249
3
        _pie = true;
250
3
       break;
251
55
       case OS::unknown:
252
55
       break;
253
92
    }
254
92
    setGlobalsAreDeadStripRoots(exportDynamicSymbols);
255
92
    break;
256
50
  case llvm::MachO::MH_DYLIB:
257
50
    setGlobalsAreDeadStripRoots(exportDynamicSymbols);
258
50
    break;
259
9
  case llvm::MachO::MH_BUNDLE:
260
9
    break;
261
89
  case llvm::MachO::MH_OBJECT:
262
89
    _printRemainingUndefines = false;
263
89
    _allowRemainingUndefines = true;
264
90
  default:
265
90
    break;
266
241
  }
267
241
268
241
  // Set default segment page sizes based on arch.
269
241
  
if (241
arch == arch_arm64241
)
270
18
    _pageSize = 4*4096;
271
241
}
272
273
5
uint32_t MachOLinkingContext::getCPUType() const {
274
5
  return cpuTypeFromArch(_arch);
275
5
}
276
277
6
uint32_t MachOLinkingContext::getCPUSubType() const {
278
6
  return cpuSubtypeFromArch(_arch);
279
6
}
280
281
927
bool MachOLinkingContext::is64Bit(Arch arch) {
282
2.08k
  for (ArchInfo *info = _s_archInfos; 
!info->archName.empty()2.08k
;
++info1.15k
) {
283
2.07k
    if (
info->arch == arch2.07k
) {
284
922
      return (info->cputype & CPU_ARCH_ABI64);
285
922
    }
286
2.07k
  }
287
927
  // unknown archs are not 64-bit.
288
5
  return false;
289
927
}
290
291
338
bool MachOLinkingContext::isHostEndian(Arch arch) {
292
338
  assert(arch != arch_unknown);
293
685
  for (ArchInfo *info = _s_archInfos; 
!info->archName.empty()685
;
++info347
) {
294
685
    if (
info->arch == arch685
) {
295
338
      return (info->littleEndian == llvm::sys::IsLittleEndianHost);
296
338
    }
297
685
  }
298
0
  
llvm_unreachable0
("Unknown arch type");
299
0
}
300
301
1.14k
bool MachOLinkingContext::isBigEndian(Arch arch) {
302
1.14k
  assert(arch != arch_unknown);
303
2.55k
  for (ArchInfo *info = _s_archInfos; 
!info->archName.empty()2.55k
;
++info1.41k
) {
304
2.55k
    if (
info->arch == arch2.55k
) {
305
1.14k
      return ! info->littleEndian;
306
1.14k
    }
307
2.55k
  }
308
0
  
llvm_unreachable0
("Unknown arch type");
309
0
}
310
311
159
bool MachOLinkingContext::is64Bit() const {
312
159
  return is64Bit(_arch);
313
159
}
314
315
410
bool MachOLinkingContext::outputTypeHasEntry() const {
316
410
  switch (_outputMachOType) {
317
157
  case MH_EXECUTE:
318
157
  case MH_DYLINKER:
319
157
  case MH_PRELOAD:
320
157
    return true;
321
253
  default:
322
253
    return false;
323
0
  }
324
0
}
325
326
364
bool MachOLinkingContext::needsStubsPass() const {
327
364
  switch (_outputMachOType) {
328
111
  case MH_EXECUTE:
329
111
    return !_outputMachOTypeStatic;
330
98
  case MH_DYLIB:
331
98
  case MH_BUNDLE:
332
98
    return true;
333
155
  default:
334
155
    return false;
335
0
  }
336
0
}
337
338
168
bool MachOLinkingContext::needsGOTPass() const {
339
168
  // GOT pass not used in -r mode.
340
168
  if (_outputMachOType == MH_OBJECT)
341
72
    return false;
342
96
  // Only some arches use GOT pass.
343
96
  switch (_arch) {
344
86
    case arch_x86_64:
345
86
    case arch_arm64:
346
86
      return true;
347
10
    default:
348
10
      return false;
349
0
  }
350
0
}
351
352
168
bool MachOLinkingContext::needsCompactUnwindPass() const {
353
168
  switch (_outputMachOType) {
354
96
  case MH_EXECUTE:
355
96
  case MH_DYLIB:
356
96
  case MH_BUNDLE:
357
96
    return archHandler().needsCompactUnwind();
358
72
  default:
359
72
    return false;
360
0
  }
361
0
}
362
363
168
bool MachOLinkingContext::needsObjCPass() const {
364
168
  // ObjC pass is only needed if any of the inputs were ObjC.
365
168
  return _objcConstraint != objc_unknown;
366
168
}
367
368
168
bool MachOLinkingContext::needsShimPass() const {
369
168
  // Shim pass only used in final executables.
370
168
  if (_outputMachOType == MH_OBJECT)
371
72
    return false;
372
96
  // Only 32-bit arm arches use Shim pass.
373
96
  switch (_arch) {
374
6
  case arch_armv6:
375
6
  case arch_armv7:
376
6
  case arch_armv7s:
377
6
    return true;
378
90
  default:
379
90
    return false;
380
0
  }
381
0
}
382
383
168
bool MachOLinkingContext::needsTLVPass() const {
384
168
  switch (_outputMachOType) {
385
96
  case MH_BUNDLE:
386
96
  case MH_EXECUTE:
387
96
  case MH_DYLIB:
388
96
    return true;
389
72
  default:
390
72
    return false;
391
0
  }
392
0
}
393
394
113
StringRef MachOLinkingContext::binderSymbolName() const {
395
113
  return archHandler().stubInfo().binderSymbolName;
396
113
}
397
398
201
bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
399
201
  uint32_t parsedVersion;
400
201
  switch (_os) {
401
163
  case OS::macOSX:
402
163
    if (parsePackedVersion(mac, parsedVersion))
403
0
      return false;
404
163
    return _osMinVersion >= parsedVersion;
405
33
  case OS::iOS:
406
33
  case OS::iOS_simulator:
407
33
    if (parsePackedVersion(iOS, parsedVersion))
408
0
      return false;
409
33
    return _osMinVersion >= parsedVersion;
410
5
  case OS::unknown:
411
5
    // If we don't know the target, then assume that we don't meet the min OS.
412
5
    // This matches the ld64 behaviour
413
5
    return false;
414
0
  }
415
0
  
llvm_unreachable0
("invalid OS enum");
416
0
}
417
418
0
bool MachOLinkingContext::addEntryPointLoadCommand() const {
419
0
  if (
(_outputMachOType == MH_EXECUTE) && 0
!_outputMachOTypeStatic0
) {
420
0
    return minOS("10.8", "6.0");
421
0
  }
422
0
  return false;
423
0
}
424
425
0
bool MachOLinkingContext::addUnixThreadLoadCommand() const {
426
0
  switch (_outputMachOType) {
427
0
  case MH_EXECUTE:
428
0
    if (_outputMachOTypeStatic)
429
0
      return true;
430
0
    else
431
0
      return !minOS("10.8", "6.0");
432
0
    break;
433
0
  case MH_DYLINKER:
434
0
  case MH_PRELOAD:
435
0
    return true;
436
0
  default:
437
0
    return false;
438
0
  }
439
0
}
440
441
1.01k
bool MachOLinkingContext::pathExists(StringRef path) const {
442
1.01k
  if (!_testingFileUsage)
443
900
    return llvm::sys::fs::exists(path.str());
444
110
445
110
  // Otherwise, we're in test mode: only files explicitly provided on the
446
110
  // command-line exist.
447
110
  std::string key = path.str();
448
110
  std::replace(key.begin(), key.end(), '\\', '/');
449
110
  return _existingPaths.find(key) != _existingPaths.end();
450
110
}
451
452
50
bool MachOLinkingContext::fileExists(StringRef path) const {
453
50
  bool found = pathExists(path);
454
50
  // Log search misses.
455
50
  if (!found)
456
28
    addInputFileNotFound(path);
457
50
458
50
  // When testing, file is never opened, so logging is done here.
459
50
  if (
_testingFileUsage && 50
found43
)
460
18
    addInputFileDependency(path);
461
50
462
50
  return found;
463
50
}
464
465
5
void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
466
5
  _syslibRoots = paths;
467
5
}
468
469
1
void MachOLinkingContext::addRpath(StringRef rpath) {
470
1
  _rpaths.push_back(rpath);
471
1
}
472
473
void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
474
474
                                               bool isSystemPath) {
475
474
  bool addedModifiedPath = false;
476
474
477
474
  // -syslibroot only applies to absolute paths.
478
474
  if (
libPath.startswith("/")474
) {
479
14
    for (auto syslibRoot : _syslibRoots) {
480
14
      SmallString<256> path(syslibRoot);
481
14
      llvm::sys::path::append(path, libPath);
482
14
      if (
pathExists(path)14
) {
483
6
        _searchDirs.push_back(path.str().copy(_allocator));
484
6
        addedModifiedPath = true;
485
6
      }
486
14
    }
487
471
  }
488
474
489
474
  if (addedModifiedPath)
490
5
    return;
491
469
492
469
  // Finally, if only one -syslibroot is given, system paths which aren't in it
493
469
  // get suppressed.
494
469
  
if (469
_syslibRoots.size() != 1 || 469
!isSystemPath7
) {
495
464
    if (
pathExists(libPath)464
) {
496
456
      _searchDirs.push_back(libPath);
497
456
    }
498
464
  }
499
474
}
500
501
void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
502
471
                                                bool isSystemPath) {
503
471
  bool pathAdded = false;
504
471
505
471
  // -syslibroot only used with to absolute framework search paths.
506
471
  if (
fwPath.startswith("/")471
) {
507
14
    for (auto syslibRoot : _syslibRoots) {
508
14
      SmallString<256> path(syslibRoot);
509
14
      llvm::sys::path::append(path, fwPath);
510
14
      if (
pathExists(path)14
) {
511
2
        _frameworkDirs.push_back(path.str().copy(_allocator));
512
2
        pathAdded = true;
513
2
      }
514
14
    }
515
470
  }
516
471
  // If fwPath found in any -syslibroot, then done.
517
471
  if (pathAdded)
518
2
    return;
519
469
520
469
  // If only one -syslibroot, system paths not in that SDK are suppressed.
521
469
  
if (469
isSystemPath && 469
(_syslibRoots.size() == 1)465
)
522
7
    return;
523
462
524
462
  // Only use raw fwPath if that directory exists.
525
462
  
if (462
pathExists(fwPath)462
)
526
449
    _frameworkDirs.push_back(fwPath);
527
471
}
528
529
llvm::Optional<StringRef>
530
MachOLinkingContext::searchDirForLibrary(StringRef path,
531
24
                                         StringRef libName) const {
532
24
  SmallString<256> fullPath;
533
24
  if (
libName.endswith(".o")24
) {
534
3
    // A request ending in .o is special: just search for the file directly.
535
3
    fullPath.assign(path);
536
3
    llvm::sys::path::append(fullPath, libName);
537
3
    if (fileExists(fullPath))
538
2
      return fullPath.str().copy(_allocator);
539
1
    return llvm::None;
540
1
  }
541
21
542
21
  // Search for dynamic library
543
21
  fullPath.assign(path);
544
21
  llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
545
21
  if (fileExists(fullPath))
546
9
    return fullPath.str().copy(_allocator);
547
12
548
12
  // If not, try for a static library
549
12
  fullPath.assign(path);
550
12
  llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
551
12
  if (fileExists(fullPath))
552
4
    return fullPath.str().copy(_allocator);
553
8
554
8
  return llvm::None;
555
8
}
556
557
llvm::Optional<StringRef>
558
16
MachOLinkingContext::searchLibrary(StringRef libName) const {
559
16
  SmallString<256> path;
560
24
  for (StringRef dir : searchDirs()) {
561
24
    llvm::Optional<StringRef> searchDir = searchDirForLibrary(dir, libName);
562
24
    if (searchDir)
563
15
      return searchDir;
564
1
  }
565
1
566
1
  return llvm::None;
567
1
}
568
569
llvm::Optional<StringRef>
570
7
MachOLinkingContext::findPathForFramework(StringRef fwName) const{
571
7
  SmallString<256> fullPath;
572
14
  for (StringRef dir : frameworkDirs()) {
573
14
    fullPath.assign(dir);
574
14
    llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
575
14
    if (fileExists(fullPath))
576
7
      return fullPath.str().copy(_allocator);
577
0
  }
578
0
579
0
  return llvm::None;
580
0
}
581
582
224
bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
583
224
  // TODO: if -arch not specified, look at arch of first .o file.
584
224
585
224
  if (
_currentVersion && 224
_outputMachOType != MH_DYLIB4
) {
586
0
    diagnostics << "error: -current_version can only be used with dylibs\n";
587
0
    return false;
588
0
  }
589
224
590
224
  
if (224
_compatibilityVersion && 224
_outputMachOType != MH_DYLIB4
) {
591
0
    diagnostics
592
0
        << "error: -compatibility_version can only be used with dylibs\n";
593
0
    return false;
594
0
  }
595
224
596
224
  
if (224
_deadStrippableDylib && 224
_outputMachOType != MH_DYLIB2
) {
597
1
    diagnostics
598
1
        << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
599
1
    return false;
600
1
  }
601
223
602
223
  
if (223
!_bundleLoader.empty() && 223
outputMachOType() != MH_BUNDLE2
) {
603
1
    diagnostics
604
1
        << "error: -bundle_loader can only be used with Mach-O bundles\n";
605
1
    return false;
606
1
  }
607
222
608
222
  // If -exported_symbols_list used, all exported symbols must be defined.
609
222
  
if (222
_exportMode == ExportMode::whiteList222
) {
610
8
    for (const auto &symbol : _exportedSymbols)
611
12
      addInitialUndefinedSymbol(symbol.getKey());
612
8
  }
613
222
614
222
  // If -dead_strip, set up initial live symbols.
615
222
  if (
deadStrip()222
) {
616
14
    // Entry point is live.
617
14
    if (outputTypeHasEntry())
618
5
      addDeadStripRoot(entrySymbolName());
619
14
    // Lazy binding helper is live.
620
14
    if (needsStubsPass())
621
12
      addDeadStripRoot(binderSymbolName());
622
14
    // If using -exported_symbols_list, make all exported symbols live.
623
14
    if (
_exportMode == ExportMode::whiteList14
) {
624
1
      setGlobalsAreDeadStripRoots(false);
625
1
      for (const auto &symbol : _exportedSymbols)
626
2
        addDeadStripRoot(symbol.getKey());
627
1
    }
628
14
  }
629
224
630
224
  addOutputFileDependency(outputPath());
631
224
632
224
  return true;
633
224
}
634
635
168
void MachOLinkingContext::addPasses(PassManager &pm) {
636
168
  // objc pass should be before layout pass.  Otherwise test cases may contain
637
168
  // no atoms which confuses the layout pass.
638
168
  if (needsObjCPass())
639
2
    mach_o::addObjCPass(pm, *this);
640
168
  mach_o::addLayoutPass(pm, *this);
641
168
  if (needsStubsPass())
642
96
    mach_o::addStubsPass(pm, *this);
643
168
  if (needsCompactUnwindPass())
644
86
    mach_o::addCompactUnwindPass(pm, *this);
645
168
  if (needsGOTPass())
646
86
    mach_o::addGOTPass(pm, *this);
647
168
  if (needsTLVPass())
648
96
    mach_o::addTLVPass(pm, *this);
649
168
  if (needsShimPass())
650
6
    mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
651
168
}
652
653
349
Writer &MachOLinkingContext::writer() const {
654
349
  if (!_writer)
655
182
    _writer = createWriterMachO(*this);
656
349
  return *_writer;
657
349
}
658
659
ErrorOr<std::unique_ptr<MemoryBuffer>>
660
373
MachOLinkingContext::getMemoryBuffer(StringRef path) {
661
373
  addInputFileDependency(path);
662
373
663
373
  ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
664
373
    MemoryBuffer::getFileOrSTDIN(path);
665
373
  if (std::error_code ec = mbOrErr.getError())
666
57
    return ec;
667
316
  std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
668
316
669
316
  // If buffer contains a fat file, find required arch in fat buffer
670
316
  // and switch buffer to point to just that required slice.
671
316
  uint32_t offset;
672
316
  uint32_t size;
673
316
  if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
674
8
    return MemoryBuffer::getFileSlice(path, size, offset);
675
308
  return std::move(mb);
676
308
}
677
678
0
MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
679
0
  ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
680
0
  if (mbOrErr.getError())
681
0
    return nullptr;
682
0
683
0
  ErrorOr<std::unique_ptr<File>> fileOrErr =
684
0
      registry().loadFile(std::move(mbOrErr.get()));
685
0
  if (!fileOrErr)
686
0
    return nullptr;
687
0
  std::unique_ptr<File> &file = fileOrErr.get();
688
0
  file->parse();
689
0
  MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
690
0
  // Node object now owned by _indirectDylibs vector.
691
0
  _indirectDylibs.push_back(std::move(file));
692
0
  return result;
693
0
}
694
695
1
MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
696
1
  // See if already loaded.
697
1
  auto pos = _pathToDylibMap.find(path);
698
1
  if (pos != _pathToDylibMap.end())
699
1
    return pos->second;
700
0
701
0
  // Search -L paths if of the form "libXXX.dylib"
702
0
  std::pair<StringRef, StringRef> split = path.rsplit('/');
703
0
  StringRef leafName = split.second;
704
0
  if (
leafName.startswith("lib") && 0
leafName.endswith(".dylib")0
) {
705
0
    // FIXME: Need to enhance searchLibrary() to only look for .dylib
706
0
    auto libPath = searchLibrary(leafName);
707
0
    if (libPath)
708
0
      return loadIndirectDylib(libPath.getValue());
709
0
  }
710
0
711
0
  // Try full path with sysroot.
712
0
  
for (StringRef sysPath : _syslibRoots) 0
{
713
0
    SmallString<256> fullPath;
714
0
    fullPath.assign(sysPath);
715
0
    llvm::sys::path::append(fullPath, path);
716
0
    if (pathExists(fullPath))
717
0
      return loadIndirectDylib(fullPath);
718
0
  }
719
0
720
0
  // Try full path.
721
0
  
if (0
pathExists(path)0
) {
722
0
    return loadIndirectDylib(path);
723
0
  }
724
0
725
0
  return nullptr;
726
0
}
727
728
110
uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
729
110
  auto pos = _pathToDylibMap.find(installName);
730
110
  if (pos != _pathToDylibMap.end())
731
110
    return pos->second->currentVersion();
732
110
  else
733
0
    return 0x10000; // 1.0
734
0
}
735
736
110
uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
737
110
  auto pos = _pathToDylibMap.find(installName);
738
110
  if (pos != _pathToDylibMap.end())
739
110
    return pos->second->compatVersion();
740
110
  else
741
0
    return 0x10000; // 1.0
742
0
}
743
744
void MachOLinkingContext::createImplicitFiles(
745
182
                            std::vector<std::unique_ptr<File> > &result) {
746
182
  // Add indirect dylibs by asking each linked dylib to add its indirects.
747
182
  // Iterate until no more dylibs get loaded.
748
182
  size_t dylibCount = 0;
749
286
  while (
dylibCount != _allDylibs.size()286
) {
750
104
    dylibCount = _allDylibs.size();
751
116
    for (MachODylibFile *dylib : _allDylibs) {
752
1
      dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
753
1
                                  return findIndirectDylib(path); });
754
116
    }
755
104
  }
756
182
757
182
  // Let writer add output type specific extras.
758
182
  writer().createImplicitFiles(result);
759
182
760
182
  // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
761
182
  // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
762
182
  if (
undefinedMode() != UndefinedMode::error182
) {
763
2
    result.emplace_back(new mach_o::FlatNamespaceFile(*this));
764
2
    _flatNamespaceFile = result.back().get();
765
2
  }
766
182
}
767
768
void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
769
116
                                        bool upward) const {
770
116
  std::lock_guard<std::mutex> lock(_dylibsMutex);
771
116
772
116
  if (std::find(_allDylibs.begin(),
773
116
                _allDylibs.end(), dylib) == _allDylibs.end())
774
116
    _allDylibs.push_back(dylib);
775
116
  _pathToDylibMap[dylib->installName()] = dylib;
776
116
  // If path is different than install name, register path too.
777
116
  if (!dylib->path().equals(dylib->installName()))
778
116
    _pathToDylibMap[dylib->path()] = dylib;
779
116
  if (upward)
780
1
    _upwardDylibs.insert(dylib);
781
116
}
782
783
110
bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
784
2
  for (MachODylibFile *dylib : _upwardDylibs) {
785
2
    if (dylib->installName().equals(installName))
786
1
      return true;
787
109
  }
788
109
  return false;
789
109
}
790
791
1.19k
ArchHandler &MachOLinkingContext::archHandler() const {
792
1.19k
  if (!_archHandler)
793
223
    _archHandler = ArchHandler::create(_arch);
794
1.19k
  return *_archHandler;
795
1.19k
}
796
797
void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
798
3
                                              uint16_t align) {
799
3
  SectionAlign entry = { seg, sect, align };
800
3
  _sectAligns.push_back(entry);
801
3
}
802
803
void MachOLinkingContext::addSectCreateSection(
804
                                        StringRef seg, StringRef sect,
805
1
                                        std::unique_ptr<MemoryBuffer> content) {
806
1
807
1
  if (
!_sectCreateFile1
) {
808
1
    auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
809
1
    _sectCreateFile = sectCreateFile.get();
810
1
    getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
811
1
  }
812
1
813
1
  assert(_sectCreateFile && "sectcreate file does not exist.");
814
1
  _sectCreateFile->addSection(seg, sect, std::move(content));
815
1
}
816
817
bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
818
374
                                         uint16_t &align) const {
819
6
  for (const SectionAlign &entry : _sectAligns) {
820
6
    if (
seg.equals(entry.segmentName) && 6
sect.equals(entry.sectionName)4
) {
821
3
      align = entry.align;
822
3
      return true;
823
3
    }
824
371
  }
825
371
  return false;
826
371
}
827
828
13
void MachOLinkingContext::addExportSymbol(StringRef sym) {
829
13
  // Support old crufty export lists with bogus entries.
830
13
  if (
sym.endswith(".eh") || 13
sym.startswith(".objc_category_name_")13
) {
831
0
    llvm::errs() << "warning: ignoring " << sym << " in export list\n";
832
0
    return;
833
0
  }
834
13
  // Only i386 MacOSX uses old ABI, so don't change those.
835
13
  
if (13
(_os != OS::macOSX) || 13
(_arch != arch_x86)10
) {
836
13
    // ObjC has two differnent ABIs.  Be nice and allow one export list work for
837
13
    // both ABIs by renaming symbols.
838
13
    if (
sym.startswith(".objc_class_name_")13
) {
839
1
      std::string abi2className("_OBJC_CLASS_$_");
840
1
      abi2className += sym.substr(17);
841
1
      _exportedSymbols.insert(copy(abi2className));
842
1
      std::string abi2metaclassName("_OBJC_METACLASS_$_");
843
1
      abi2metaclassName += sym.substr(17);
844
1
      _exportedSymbols.insert(copy(abi2metaclassName));
845
1
      return;
846
1
    }
847
12
  }
848
12
849
12
  // FIXME: Support wildcards.
850
12
  _exportedSymbols.insert(sym);
851
12
}
852
853
47
bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
854
47
  switch (_exportMode) {
855
0
  case ExportMode::globals:
856
0
    llvm_unreachable("exportSymbolNamed() should not be called in this mode");
857
0
    break;
858
39
  case ExportMode::whiteList:
859
39
    return _exportedSymbols.count(sym);
860
8
  case ExportMode::blackList:
861
8
    return !_exportedSymbols.count(sym);
862
0
  }
863
0
  
llvm_unreachable0
("_exportMode unknown enum value");
864
0
}
865
866
8
std::string MachOLinkingContext::demangle(StringRef symbolName) const {
867
8
  // Only try to demangle symbols if -demangle on command line
868
8
  if (!demangleSymbols())
869
5
    return symbolName;
870
3
871
3
  // Only try to demangle symbols that look like C++ symbols
872
3
  
if (3
!symbolName.startswith("__Z")3
)
873
1
    return symbolName;
874
2
875
2
  SmallString<256> symBuff;
876
2
  StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
877
2
  // Mach-O has extra leading underscore that needs to be removed.
878
2
  const char *cstr = nullTermSym.data() + 1;
879
2
  int status;
880
2
  char *demangled = llvm::itaniumDemangle(cstr, nullptr, nullptr, &status);
881
2
  if (
demangled2
) {
882
1
    std::string result(demangled);
883
1
    // __cxa_demangle() always uses a malloc'ed buffer to return the result.
884
1
    free(demangled);
885
1
    return result;
886
1
  }
887
1
888
1
  return symbolName;
889
1
}
890
891
static void addDependencyInfoHelper(llvm::raw_fd_ostream *DepInfo,
892
647
                                    char Opcode, StringRef Path) {
893
647
  if (!DepInfo)
894
640
    return;
895
7
896
7
  *DepInfo << Opcode;
897
7
  *DepInfo << Path;
898
7
  *DepInfo << '\0';
899
7
}
900
901
1
std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
902
1
  std::error_code ec;
903
1
  _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
904
1
                         llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
905
1
  if (
ec1
) {
906
0
    _dependencyInfo.reset();
907
0
    return ec;
908
0
  }
909
1
910
1
  addDependencyInfoHelper(_dependencyInfo.get(), 0x00, "lld" /*FIXME*/);
911
1
  return std::error_code();
912
1
}
913
914
396
void MachOLinkingContext::addInputFileDependency(StringRef path) const {
915
396
  addDependencyInfoHelper(_dependencyInfo.get(), 0x10, path);
916
396
}
917
918
28
void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
919
28
  addDependencyInfoHelper(_dependencyInfo.get(), 0x11, path);
920
28
}
921
922
222
void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
923
222
  addDependencyInfoHelper(_dependencyInfo.get(), 0x40, path);
924
222
}
925
926
void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
927
5
                                              StringRef filename) {
928
5
  // To support sorting static functions which may have the same name in
929
5
  // multiple .o files, _orderFiles maps the symbol name to a vector
930
5
  // of OrderFileNode each of which can specify a file prefix.
931
5
  OrderFileNode info;
932
5
  if (!filename.empty())
933
1
    info.fileFilter = copy(filename);
934
5
  info.order = _orderFileEntries++;
935
5
  _orderFiles[symbol].push_back(info);
936
5
}
937
938
bool
939
MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
940
                                      const DefinedAtom *atom,
941
11
                                      unsigned &ordinal) {
942
11
  const File *objFile = &atom->file();
943
11
  assert(objFile);
944
11
  StringRef objName = objFile->path();
945
11
  std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
946
11
  if (!dirAndLeaf.second.empty())
947
11
    objName = dirAndLeaf.second;
948
11
  for (const OrderFileNode &info : nodes) {
949
11
    if (
info.fileFilter.empty()11
) {
950
5
      // Have unprefixed symbol name in order file that matches this atom.
951
5
      ordinal = info.order;
952
5
      return true;
953
5
    }
954
6
    
if (6
info.fileFilter.equals(objName)6
) {
955
6
      // Have prefixed symbol name in order file that matches atom's path.
956
6
      ordinal = info.order;
957
6
      return true;
958
6
    }
959
0
  }
960
0
  return false;
961
0
}
962
963
bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
964
                                            const DefinedAtom *right,
965
298
                                            bool &leftBeforeRight) const {
966
298
  // No custom sorting if no order file entries.
967
298
  if (!_orderFileEntries)
968
286
    return false;
969
12
970
12
  // Order files can only order named atoms.
971
12
  StringRef leftName = left->name();
972
12
  StringRef rightName = right->name();
973
12
  if (
leftName.empty() || 12
rightName.empty()11
)
974
1
    return false;
975
11
976
11
  // If neither is in order file list, no custom sorter.
977
11
  auto leftPos = _orderFiles.find(leftName);
978
11
  auto rightPos = _orderFiles.find(rightName);
979
11
  bool leftIsOrdered = (leftPos != _orderFiles.end());
980
11
  bool rightIsOrdered = (rightPos != _orderFiles.end());
981
11
  if (
!leftIsOrdered && 11
!rightIsOrdered4
)
982
2
    return false;
983
9
984
9
  // There could be multiple symbols with same name but different file prefixes.
985
9
  unsigned leftOrder;
986
9
  unsigned rightOrder;
987
9
  bool foundLeft =
988
7
      leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
989
9
  bool foundRight = rightIsOrdered &&
990
4
                    findOrderOrdinal(rightPos->getValue(), right, rightOrder);
991
9
  if (
!foundLeft && 9
!foundRight2
)
992
0
    return false;
993
9
994
9
  // If only one is in order file list, ordered one goes first.
995
9
  
if (9
foundLeft != foundRight9
)
996
7
    leftBeforeRight = foundLeft;
997
9
  else
998
2
    leftBeforeRight = (leftOrder < rightOrder);
999
298
1000
298
  return true;
1001
298
}
1002
1003
1.75k
static bool isLibrary(const std::unique_ptr<Node> &elem) {
1004
1.75k
  if (FileNode *
node1.75k
= dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
1005
1.75k
    File *file = node->getFile();
1006
1.51k
    return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
1007
1.75k
  }
1008
0
  return false;
1009
0
}
1010
1011
// The darwin linker processes input files in two phases.  The first phase
1012
// links in all object (.o) files in command line order. The second phase
1013
// links in libraries in command line order.
1014
// In this function we reorder the input files so that all the object files
1015
// comes before any library file. We also make a group for the library files
1016
// so that the Resolver will reiterate over the libraries as long as we find
1017
// new undefines from libraries.
1018
182
void MachOLinkingContext::finalizeInputFiles() {
1019
182
  std::vector<std::unique_ptr<Node>> &elements = getNodes();
1020
182
  std::stable_sort(elements.begin(), elements.end(),
1021
182
                   [](const std::unique_ptr<Node> &a,
1022
622
                      const std::unique_ptr<Node> &b) {
1023
499
                     return !isLibrary(a) && isLibrary(b);
1024
622
                   });
1025
182
  size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1026
182
  elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1027
182
}
1028
1029
627
llvm::Error MachOLinkingContext::handleLoadedFile(File &file) {
1030
627
  auto *machoFile = dyn_cast<MachOFile>(&file);
1031
627
  if (!machoFile)
1032
454
    return llvm::Error::success();
1033
173
1034
173
  // Check that the arch of the context matches that of the file.
1035
173
  // Also set the arch of the context if it didn't have one.
1036
173
  
if (173
_arch == arch_unknown173
) {
1037
0
    _arch = machoFile->arch();
1038
173
  } else 
if (173
machoFile->arch() != arch_unknown && 173
machoFile->arch() != _arch173
) {
1039
0
    // Archs are different.
1040
0
    return llvm::make_error<GenericError>(file.path() +
1041
0
                  Twine(" cannot be linked due to incompatible architecture"));
1042
0
  }
1043
173
1044
173
  // Check that the OS of the context matches that of the file.
1045
173
  // Also set the OS of the context if it didn't have one.
1046
173
  
if (173
_os == OS::unknown173
) {
1047
71
    _os = machoFile->OS();
1048
173
  } else 
if (102
machoFile->OS() != OS::unknown && 102
machoFile->OS() != _os2
) {
1049
1
    // OSes are different.
1050
1
    return llvm::make_error<GenericError>(file.path() +
1051
1
              Twine(" cannot be linked due to incompatible operating systems"));
1052
1
  }
1053
172
1054
172
  // Check that if the objc info exists, that it is compatible with the target
1055
172
  // OS.
1056
172
  switch (machoFile->objcConstraint()) {
1057
166
    case objc_unknown:
1058
166
      // The file is not compiled with objc, so skip the checks.
1059
166
      break;
1060
0
    case objc_gc_only:
1061
0
    case objc_supports_gc:
1062
0
      llvm_unreachable("GC support should already have thrown an error");
1063
3
    case objc_retainReleaseForSimulator:
1064
3
      // The file is built with simulator objc, so make sure that the context
1065
3
      // is also building with simulator support.
1066
3
      if (_os != OS::iOS_simulator)
1067
1
        return llvm::make_error<GenericError>(file.path() +
1068
1
          Twine(" cannot be linked.  It contains ObjC built for the simulator"
1069
1
                " while we are linking a non-simulator target"));
1070
3
      assert((_objcConstraint == objc_unknown ||
1071
2
              _objcConstraint == objc_retainReleaseForSimulator) &&
1072
2
             "Must be linking with retain/release for the simulator");
1073
2
      _objcConstraint = objc_retainReleaseForSimulator;
1074
2
      break;
1075
3
    case objc_retainRelease:
1076
3
      // The file is built without simulator objc, so make sure that the
1077
3
      // context is also building without simulator support.
1078
3
      if (_os == OS::iOS_simulator)
1079
1
        return llvm::make_error<GenericError>(file.path() +
1080
1
          Twine(" cannot be linked.  It contains ObjC built for a non-simulator"
1081
1
                " target while we are linking a simulator target"));
1082
0
      assert((_objcConstraint == objc_unknown ||
1083
2
              _objcConstraint == objc_retainRelease) &&
1084
2
             "Must be linking with retain/release for a non-simulator target");
1085
2
      _objcConstraint = objc_retainRelease;
1086
2
      break;
1087
170
  }
1088
170
1089
170
  // Check that the swift version of the context matches that of the file.
1090
170
  // Also set the swift version of the context if it didn't have one.
1091
170
  
if (170
!_swiftVersion170
) {
1092
169
    _swiftVersion = machoFile->swiftVersion();
1093
170
  } else 
if (1
machoFile->swiftVersion() &&
1094
1
             
machoFile->swiftVersion() != _swiftVersion1
) {
1095
1
    // Swift versions are different.
1096
1
    return llvm::make_error<GenericError>("different swift versions");
1097
1
  }
1098
169
1099
169
  return llvm::Error::success();
1100
169
}
1101
1102
} // end namespace lld