Coverage Report

Created: 2018-06-25 02:00

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