1//===-- llvm-libtool-darwin.cpp - a tool for creating libraries -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// A utility for creating static and dynamic libraries for Darwin.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DependencyInfo.h"
14#include "llvm/ADT/MapVector.h"
15#include "llvm/BinaryFormat/Magic.h"
16#include "llvm/IR/LLVMContext.h"
17#include "llvm/Object/ArchiveWriter.h"
18#include "llvm/Object/IRObjectFile.h"
19#include "llvm/Object/MachO.h"
20#include "llvm/Object/MachOUniversal.h"
21#include "llvm/Object/MachOUniversalWriter.h"
22#include "llvm/Object/ObjectFile.h"
23#include "llvm/Option/ArgList.h"
24#include "llvm/Option/Option.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/LLVMDriver.h"
27#include "llvm/Support/LineIterator.h"
28#include "llvm/Support/TargetSelect.h"
29#include "llvm/Support/VirtualFileSystem.h"
30#include "llvm/Support/WithColor.h"
31#include "llvm/Support/YAMLTraits.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/TextAPI/Architecture.h"
34#include <cstdlib>
35#include <map>
36#include <type_traits>
37
38using namespace llvm;
39using namespace llvm::object;
40using namespace llvm::opt;
41
42// Command-line option boilerplate.
43namespace {
44enum ID {
45 OPT_INVALID = 0, // This is not an option ID.
46#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
47#include "Opts.inc"
48#undef OPTION
49};
50
51#define PREFIX(NAME, VALUE) \
52 static constexpr StringLiteral NAME##_init[] = VALUE; \
53 static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \
54 std::size(NAME##_init) - 1);
55#include "Opts.inc"
56#undef PREFIX
57
58static constexpr opt::OptTable::Info InfoTable[] = {
59#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
60#include "Opts.inc"
61#undef OPTION
62};
63
64class LibtoolDarwinOptTable : public opt::GenericOptTable {
65public:
66 LibtoolDarwinOptTable() : GenericOptTable(InfoTable) {}
67};
68} // end anonymous namespace
69
70class NewArchiveMemberList;
71typedef std::map<uint64_t, NewArchiveMemberList> MembersPerArchitectureMap;
72
73static std::string OutputFile;
74static std::vector<std::string> InputFiles;
75static std::optional<std::string> ArchType;
76
77enum class Operation { None, Static };
78static Operation LibraryOperation = Operation::None;
79
80static bool DeterministicOption;
81static bool NonDeterministicOption;
82static std::string FileList;
83static std::vector<std::string> Libraries;
84static std::vector<std::string> LibrarySearchDirs;
85static std::string DependencyInfoPath;
86static bool VersionOption;
87static bool NoWarningForNoSymbols;
88static bool WarningsAsErrors;
89static std::string IgnoredSyslibRoot;
90
91static const std::array<std::string, 3> StandardSearchDirs{
92 "/lib",
93 "/usr/lib",
94 "/usr/local/lib",
95};
96
97std::unique_ptr<DependencyInfo> GlobalDependencyInfo;
98
99struct Config {
100 bool Deterministic = true; // Updated by 'D' and 'U' modifiers.
101 uint32_t ArchCPUType;
102 uint32_t ArchCPUSubtype;
103};
104
105static Expected<std::string> searchForFile(const Twine &FileName) {
106 auto FindLib =
107 [FileName](
108 ArrayRef<std::string> SearchDirs) -> std::optional<std::string> {
109 for (StringRef Dir : SearchDirs) {
110 SmallString<128> Path;
111 sys::path::append(path&: Path, a: Dir, b: FileName);
112
113 if (sys::fs::exists(Path))
114 return std::string(Path);
115
116 GlobalDependencyInfo->addMissingInput(Path);
117 }
118 return std::nullopt;
119 };
120
121 std::optional<std::string> Found = FindLib(LibrarySearchDirs);
122 if (!Found)
123 Found = FindLib(StandardSearchDirs);
124 if (Found)
125 return *Found;
126
127 return createStringError(EC: std::errc::invalid_argument,
128 Fmt: "cannot locate file '%s'", Vals: FileName.str().c_str());
129}
130
131static Error processCommandLineLibraries() {
132 for (StringRef BaseName : Libraries) {
133 Expected<std::string> FullPath = searchForFile(
134 FileName: BaseName.ends_with(Suffix: ".o") ? BaseName.str() : "lib" + BaseName + ".a");
135 if (!FullPath)
136 return FullPath.takeError();
137 InputFiles.push_back(x: FullPath.get());
138 }
139
140 return Error::success();
141}
142
143static Error processFileList() {
144 StringRef FileName, DirName;
145 std::tie(args&: FileName, args&: DirName) = StringRef(FileList).rsplit(Separator: ",");
146
147 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
148 MemoryBuffer::getFileOrSTDIN(Filename: FileName, /*IsText=*/false,
149 /*RequiresNullTerminator=*/false);
150 if (std::error_code EC = FileOrErr.getError())
151 return createFileError(F: FileName, E: errorCodeToError(EC));
152 const MemoryBuffer &Ref = *FileOrErr.get();
153
154 line_iterator I(Ref, /*SkipBlanks=*/false);
155 if (I.is_at_eof())
156 return createStringError(EC: std::errc::invalid_argument,
157 Fmt: "file list file: '%s' is empty",
158 Vals: FileName.str().c_str());
159 for (; !I.is_at_eof(); ++I) {
160 StringRef Line = *I;
161 if (Line.empty())
162 return createStringError(EC: std::errc::invalid_argument,
163 Fmt: "file list file: '%s': filename cannot be empty",
164 Vals: FileName.str().c_str());
165
166 SmallString<128> Path;
167 if (!DirName.empty())
168 sys::path::append(path&: Path, a: DirName, b: Line);
169 else
170 sys::path::append(path&: Path, a: Line);
171 InputFiles.push_back(x: static_cast<std::string>(Path));
172 }
173 return Error::success();
174}
175
176static Error validateArchitectureName(StringRef ArchitectureName) {
177 if (!MachOObjectFile::isValidArch(ArchFlag: ArchitectureName)) {
178 std::string Buf;
179 raw_string_ostream OS(Buf);
180 for (StringRef Arch : MachOObjectFile::getValidArchs())
181 OS << Arch << " ";
182
183 return createStringError(
184 EC: std::errc::invalid_argument,
185 Fmt: "invalid architecture '%s': valid architecture names are %s",
186 Vals: ArchitectureName.str().c_str(), Vals: OS.str().c_str());
187 }
188 return Error::success();
189}
190
191static uint64_t getCPUID(uint32_t CPUType, uint32_t CPUSubtype) {
192 switch (CPUType) {
193 case MachO::CPU_TYPE_ARM:
194 case MachO::CPU_TYPE_ARM64:
195 case MachO::CPU_TYPE_ARM64_32:
196 case MachO::CPU_TYPE_X86_64:
197 // We consider CPUSubtype only for the above 4 CPUTypes to match cctools'
198 // libtool behavior.
199 return static_cast<uint64_t>(CPUType) << 32 | CPUSubtype;
200 default:
201 return CPUType;
202 }
203}
204
205// MembersData is an organized collection of members.
206struct MembersData {
207 // MembersPerArchitectureMap is a mapping from CPU architecture to a list of
208 // members.
209 MembersPerArchitectureMap MembersPerArchitecture;
210 std::vector<std::unique_ptr<MemoryBuffer>> FileBuffers;
211};
212
213// NewArchiveMemberList instances serve as collections of archive members and
214// information about those members.
215class NewArchiveMemberList {
216 std::vector<NewArchiveMember> Members;
217 // This vector contains the file that each NewArchiveMember from Members came
218 // from. Therefore, it has the same size as Members.
219 std::vector<StringRef> Files;
220
221public:
222 // Add a NewArchiveMember and the file it came from to the list.
223 void push_back(NewArchiveMember &&Member, StringRef File) {
224 Members.push_back(x: std::move(Member));
225 Files.push_back(x: File);
226 }
227
228 ArrayRef<NewArchiveMember> getMembers() const { return Members; }
229
230 ArrayRef<StringRef> getFiles() const { return Files; }
231
232 static_assert(
233 std::is_same<decltype(MembersData::MembersPerArchitecture)::mapped_type,
234 NewArchiveMemberList>(),
235 "This test makes sure NewArchiveMemberList is used by MembersData since "
236 "the following asserts test invariants required for MembersData.");
237 static_assert(
238 !std::is_copy_constructible_v<
239 decltype(NewArchiveMemberList::Members)::value_type>,
240 "MembersData::MembersPerArchitecture has a dependency on "
241 "MembersData::FileBuffers so it should not be able to "
242 "be copied on its own without FileBuffers. Unfortunately, "
243 "is_copy_constructible does not detect whether the container (ie vector) "
244 "of a non-copyable type is itself non-copyable so we have to test the "
245 "actual type of the stored data (ie, value_type).");
246 static_assert(
247 !std::is_copy_assignable_v<
248 decltype(NewArchiveMemberList::Members)::value_type>,
249 "MembersData::MembersPerArchitecture has a dependency on "
250 "MembersData::FileBuffers so it should not be able to "
251 "be copied on its own without FileBuffers. Unfortunately, "
252 "is_copy_constructible does not detect whether the container (ie vector) "
253 "of a non-copyable type is itself non-copyable so we have to test the "
254 "actual type of the stored data (ie, value_type).");
255};
256
257// MembersBuilder collects and organizes all members from the files provided by
258// the user.
259class MembersBuilder {
260public:
261 MembersBuilder(LLVMContext &LLVMCtx, const Config &C)
262 : LLVMCtx(LLVMCtx), C(C) {}
263
264 Expected<MembersData> build() {
265 for (StringRef FileName : InputFiles)
266 if (Error E = AddMember(*this, FileName)())
267 return std::move(E);
268
269 std::string Arch = ArchType.value_or(u: "");
270 if (!Arch.empty()) {
271 uint64_t ArchCPUID = getCPUID(CPUType: C.ArchCPUType, CPUSubtype: C.ArchCPUSubtype);
272 if (Data.MembersPerArchitecture.find(x: ArchCPUID) ==
273 Data.MembersPerArchitecture.end())
274 return createStringError(EC: std::errc::invalid_argument,
275 Fmt: "no library created (no object files in input "
276 "files matching -arch_only %s)",
277 Vals: Arch.c_str());
278 }
279 return std::move(Data);
280 }
281
282private:
283 class AddMember {
284 MembersBuilder &Builder;
285 StringRef FileName;
286
287 public:
288 AddMember(MembersBuilder &Builder, StringRef FileName)
289 : Builder(Builder), FileName(FileName) {}
290
291 Error operator()() {
292 Expected<NewArchiveMember> NewMemberOrErr =
293 NewArchiveMember::getFile(FileName, Deterministic: Builder.C.Deterministic);
294 if (!NewMemberOrErr)
295 return createFileError(F: FileName, E: NewMemberOrErr.takeError());
296 auto &NewMember = *NewMemberOrErr;
297
298 // For regular archives, use the basename of the object path for the
299 // member name.
300 NewMember.MemberName = sys::path::filename(path: NewMember.MemberName);
301 file_magic Magic = identify_magic(magic: NewMember.Buf->getBuffer());
302
303 // Flatten archives.
304 if (Magic == file_magic::archive)
305 return addArchiveMembers(NewMember: std::move(NewMember));
306
307 // Flatten universal files.
308 if (Magic == file_magic::macho_universal_binary)
309 return addUniversalMembers(NewMember: std::move(NewMember));
310
311 // Bitcode files.
312 if (Magic == file_magic::bitcode)
313 return verifyAndAddIRObject(Member: std::move(NewMember));
314
315 return verifyAndAddMachOObject(Member: std::move(NewMember));
316 }
317
318 private:
319 // Check that a file's architecture [FileCPUType, FileCPUSubtype]
320 // matches the architecture specified under -arch_only flag.
321 bool acceptFileArch(uint32_t FileCPUType, uint32_t FileCPUSubtype) {
322 if (Builder.C.ArchCPUType != FileCPUType)
323 return false;
324
325 switch (Builder.C.ArchCPUType) {
326 case MachO::CPU_TYPE_ARM:
327 case MachO::CPU_TYPE_ARM64_32:
328 case MachO::CPU_TYPE_X86_64:
329 return Builder.C.ArchCPUSubtype == FileCPUSubtype;
330
331 case MachO::CPU_TYPE_ARM64:
332 if (Builder.C.ArchCPUSubtype == MachO::CPU_SUBTYPE_ARM64_ALL)
333 return FileCPUSubtype == MachO::CPU_SUBTYPE_ARM64_ALL ||
334 FileCPUSubtype == MachO::CPU_SUBTYPE_ARM64_V8;
335 else
336 return Builder.C.ArchCPUSubtype == FileCPUSubtype;
337
338 default:
339 return true;
340 }
341 }
342
343 Error verifyAndAddMachOObject(NewArchiveMember Member) {
344 auto MBRef = Member.Buf->getMemBufferRef();
345 Expected<std::unique_ptr<object::ObjectFile>> ObjOrErr =
346 object::ObjectFile::createObjectFile(Object: MBRef);
347
348 // Throw error if not a valid object file.
349 if (!ObjOrErr)
350 return createFileError(F: Member.MemberName, E: ObjOrErr.takeError());
351
352 // Throw error if not in Mach-O format.
353 if (!isa<object::MachOObjectFile>(Val: **ObjOrErr))
354 return createStringError(EC: std::errc::invalid_argument,
355 Fmt: "'%s': format not supported",
356 Vals: Member.MemberName.data());
357
358 auto *O = cast<MachOObjectFile>(Val: ObjOrErr->get());
359 uint32_t FileCPUType, FileCPUSubtype;
360 std::tie(args&: FileCPUType, args&: FileCPUSubtype) = MachO::getCPUTypeFromArchitecture(
361 Arch: MachO::getArchitectureFromName(Name: O->getArchTriple().getArchName()));
362
363 // If -arch_only is specified then skip this file if it doesn't match
364 // the architecture specified.
365 if (ArchType && !acceptFileArch(FileCPUType, FileCPUSubtype)) {
366 return Error::success();
367 }
368
369 if (!NoWarningForNoSymbols && O->symbols().empty()) {
370 Error E = createFileError(
371 F: Member.MemberName,
372 E: createStringError(EC: std::errc::invalid_argument,
373 Fmt: "has no symbols for architecture %s",
374 Vals: O->getArchTriple().getArchName().str().c_str()));
375
376 if (WarningsAsErrors)
377 return E;
378 WithColor::defaultWarningHandler(Warning: std::move(E));
379 }
380
381 uint64_t FileCPUID = getCPUID(CPUType: FileCPUType, CPUSubtype: FileCPUSubtype);
382 Builder.Data.MembersPerArchitecture[FileCPUID].push_back(
383 Member: std::move(Member), File: FileName);
384 return Error::success();
385 }
386
387 Error verifyAndAddIRObject(NewArchiveMember Member) {
388 auto MBRef = Member.Buf->getMemBufferRef();
389 Expected<std::unique_ptr<object::IRObjectFile>> IROrErr =
390 object::IRObjectFile::create(Object: MBRef, Context&: Builder.LLVMCtx);
391
392 // Throw error if not a valid IR object file.
393 if (!IROrErr)
394 return createFileError(F: Member.MemberName, E: IROrErr.takeError());
395
396 Triple TT = Triple(IROrErr->get()->getTargetTriple());
397
398 Expected<uint32_t> FileCPUTypeOrErr = MachO::getCPUType(T: TT);
399 if (!FileCPUTypeOrErr)
400 return FileCPUTypeOrErr.takeError();
401
402 Expected<uint32_t> FileCPUSubTypeOrErr = MachO::getCPUSubType(T: TT);
403 if (!FileCPUSubTypeOrErr)
404 return FileCPUSubTypeOrErr.takeError();
405
406 // If -arch_only is specified then skip this file if it doesn't match
407 // the architecture specified.
408 if (ArchType &&
409 !acceptFileArch(FileCPUType: *FileCPUTypeOrErr, FileCPUSubtype: *FileCPUSubTypeOrErr)) {
410 return Error::success();
411 }
412
413 uint64_t FileCPUID = getCPUID(CPUType: *FileCPUTypeOrErr, CPUSubtype: *FileCPUSubTypeOrErr);
414 Builder.Data.MembersPerArchitecture[FileCPUID].push_back(
415 Member: std::move(Member), File: FileName);
416 return Error::success();
417 }
418
419 Error addChildMember(const object::Archive::Child &M) {
420 Expected<NewArchiveMember> NewMemberOrErr =
421 NewArchiveMember::getOldMember(OldMember: M, Deterministic: Builder.C.Deterministic);
422 if (!NewMemberOrErr)
423 return NewMemberOrErr.takeError();
424 auto &NewMember = *NewMemberOrErr;
425
426 file_magic Magic = identify_magic(magic: NewMember.Buf->getBuffer());
427
428 if (Magic == file_magic::bitcode)
429 return verifyAndAddIRObject(Member: std::move(NewMember));
430
431 return verifyAndAddMachOObject(Member: std::move(NewMember));
432 }
433
434 Error processArchive(object::Archive &Lib) {
435 Error Err = Error::success();
436 for (const object::Archive::Child &Child : Lib.children(Err))
437 if (Error E = addChildMember(M: Child))
438 return createFileError(F: FileName, E: std::move(E));
439 if (Err)
440 return createFileError(F: FileName, E: std::move(Err));
441
442 return Error::success();
443 }
444
445 Error addArchiveMembers(NewArchiveMember NewMember) {
446 Expected<std::unique_ptr<Archive>> LibOrErr =
447 object::Archive::create(Source: NewMember.Buf->getMemBufferRef());
448 if (!LibOrErr)
449 return createFileError(F: FileName, E: LibOrErr.takeError());
450
451 if (Error E = processArchive(Lib&: **LibOrErr))
452 return E;
453
454 // Update vector FileBuffers with the MemoryBuffers to transfer
455 // ownership.
456 Builder.Data.FileBuffers.push_back(x: std::move(NewMember.Buf));
457 return Error::success();
458 }
459
460 Error addUniversalMembers(NewArchiveMember NewMember) {
461 Expected<std::unique_ptr<MachOUniversalBinary>> BinaryOrErr =
462 MachOUniversalBinary::create(Source: NewMember.Buf->getMemBufferRef());
463 if (!BinaryOrErr)
464 return createFileError(F: FileName, E: BinaryOrErr.takeError());
465
466 auto *UO = BinaryOrErr->get();
467 for (const MachOUniversalBinary::ObjectForArch &O : UO->objects()) {
468
469 Expected<std::unique_ptr<MachOObjectFile>> MachOObjOrErr =
470 O.getAsObjectFile();
471 if (MachOObjOrErr) {
472 NewArchiveMember NewMember =
473 NewArchiveMember(MachOObjOrErr->get()->getMemoryBufferRef());
474 NewMember.MemberName = sys::path::filename(path: NewMember.MemberName);
475
476 if (Error E = verifyAndAddMachOObject(Member: std::move(NewMember)))
477 return E;
478 continue;
479 }
480
481 Expected<std::unique_ptr<IRObjectFile>> IRObjectOrError =
482 O.getAsIRObject(Ctx&: Builder.LLVMCtx);
483 if (IRObjectOrError) {
484 // A universal file member can be a MachOObjectFile, an IRObject or an
485 // Archive. In case we can successfully cast the member as an
486 // IRObject, it is safe to throw away the error generated due to
487 // casting the object as a MachOObjectFile.
488 consumeError(Err: MachOObjOrErr.takeError());
489
490 NewArchiveMember NewMember =
491 NewArchiveMember(IRObjectOrError->get()->getMemoryBufferRef());
492 NewMember.MemberName = sys::path::filename(path: NewMember.MemberName);
493
494 if (Error E = verifyAndAddIRObject(Member: std::move(NewMember)))
495 return E;
496 continue;
497 }
498
499 Expected<std::unique_ptr<Archive>> ArchiveOrError = O.getAsArchive();
500 if (ArchiveOrError) {
501 // A universal file member can be a MachOObjectFile, an IRObject or an
502 // Archive. In case we can successfully cast the member as an Archive,
503 // it is safe to throw away the error generated due to casting the
504 // object as a MachOObjectFile.
505 consumeError(Err: MachOObjOrErr.takeError());
506 consumeError(Err: IRObjectOrError.takeError());
507
508 if (Error E = processArchive(Lib&: **ArchiveOrError))
509 return E;
510 continue;
511 }
512
513 Error CombinedError = joinErrors(
514 E1: ArchiveOrError.takeError(),
515 E2: joinErrors(E1: IRObjectOrError.takeError(), E2: MachOObjOrErr.takeError()));
516 return createFileError(F: FileName, E: std::move(CombinedError));
517 }
518
519 // Update vector FileBuffers with the MemoryBuffers to transfer
520 // ownership.
521 Builder.Data.FileBuffers.push_back(x: std::move(NewMember.Buf));
522 return Error::success();
523 }
524 };
525
526 MembersData Data;
527 LLVMContext &LLVMCtx;
528 const Config &C;
529};
530
531static Expected<SmallVector<Slice, 2>>
532buildSlices(LLVMContext &LLVMCtx,
533 ArrayRef<OwningBinary<Archive>> OutputBinaries) {
534 SmallVector<Slice, 2> Slices;
535
536 for (const auto &OB : OutputBinaries) {
537 const Archive &A = *OB.getBinary();
538 Expected<Slice> ArchiveSlice = Slice::create(A, LLVMCtx: &LLVMCtx);
539 if (!ArchiveSlice)
540 return ArchiveSlice.takeError();
541 Slices.push_back(Elt: *ArchiveSlice);
542 }
543 return Slices;
544}
545
546static Error
547checkForDuplicates(const MembersPerArchitectureMap &MembersPerArch) {
548 for (const auto &M : MembersPerArch) {
549 ArrayRef<NewArchiveMember> Members = M.second.getMembers();
550 ArrayRef<StringRef> Files = M.second.getFiles();
551 MapVector<StringRef, SmallVector<StringRef, 1>> MembersToFiles;
552 for (auto Iterators = std::make_pair(x: Members.begin(), y: Files.begin());
553 Iterators.first != Members.end();
554 ++Iterators.first, ++Iterators.second) {
555 assert(Iterators.second != Files.end() &&
556 "Files should be the same size as Members.");
557 MembersToFiles[Iterators.first->MemberName].push_back(Elt: *Iterators.second);
558 }
559
560 std::string ErrorData;
561 raw_string_ostream ErrorStream(ErrorData);
562 for (const auto &[Key, Value] : MembersToFiles) {
563 if (Value.size() > 1) {
564 ErrorStream << "file '" << Key << "' was specified multiple times.\n";
565
566 for (StringRef OriginalFile : Value)
567 ErrorStream << "in: " << OriginalFile.str() << '\n';
568
569 ErrorStream << '\n';
570 }
571 }
572
573 ErrorStream.flush();
574 if (ErrorData.size() > 0)
575 return createStringError(EC: std::errc::invalid_argument, Fmt: ErrorData.c_str());
576 }
577 return Error::success();
578}
579
580static Error createStaticLibrary(LLVMContext &LLVMCtx, const Config &C) {
581 MembersBuilder Builder(LLVMCtx, C);
582 auto DataOrError = Builder.build();
583 if (auto Error = DataOrError.takeError())
584 return Error;
585
586 const auto &NewMembers = DataOrError->MembersPerArchitecture;
587
588 if (Error E = checkForDuplicates(MembersPerArch: NewMembers)) {
589 if (WarningsAsErrors)
590 return E;
591 WithColor::defaultWarningHandler(Warning: std::move(E));
592 }
593
594 if (NewMembers.size() == 1)
595 return writeArchive(ArcName: OutputFile, NewMembers: NewMembers.begin()->second.getMembers(),
596 WriteSymtab: SymtabWritingMode::NormalSymtab,
597 /*Kind=*/object::Archive::K_DARWIN, Deterministic: C.Deterministic,
598 /*Thin=*/false);
599
600 SmallVector<OwningBinary<Archive>, 2> OutputBinaries;
601 for (const std::pair<const uint64_t, NewArchiveMemberList> &M : NewMembers) {
602 Expected<std::unique_ptr<MemoryBuffer>> OutputBufferOrErr =
603 writeArchiveToBuffer(
604 NewMembers: M.second.getMembers(), WriteSymtab: SymtabWritingMode::NormalSymtab,
605 /*Kind=*/object::Archive::K_DARWIN, Deterministic: C.Deterministic,
606 /*Thin=*/false);
607 if (!OutputBufferOrErr)
608 return OutputBufferOrErr.takeError();
609 std::unique_ptr<MemoryBuffer> &OutputBuffer = OutputBufferOrErr.get();
610
611 Expected<std::unique_ptr<Archive>> ArchiveOrError =
612 Archive::create(Source: OutputBuffer->getMemBufferRef());
613 if (!ArchiveOrError)
614 return ArchiveOrError.takeError();
615 std::unique_ptr<Archive> &A = ArchiveOrError.get();
616
617 OutputBinaries.push_back(
618 Elt: OwningBinary<Archive>(std::move(A), std::move(OutputBuffer)));
619 }
620
621 Expected<SmallVector<Slice, 2>> Slices = buildSlices(LLVMCtx, OutputBinaries);
622 if (!Slices)
623 return Slices.takeError();
624
625 llvm::stable_sort(Range&: *Slices);
626 return writeUniversalBinary(Slices: *Slices, OutputFileName: OutputFile);
627}
628
629static void parseRawArgs(int Argc, char **Argv) {
630 LibtoolDarwinOptTable Tbl;
631 llvm::BumpPtrAllocator A;
632 llvm::StringSaver Saver{A};
633 opt::InputArgList Args =
634 Tbl.parseArgs(Argc, Argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) {
635 llvm::errs() << Msg << '\n';
636 std::exit(status: 1);
637 });
638
639 if (Args.hasArg(Ids: OPT_help)) {
640 Tbl.printHelp(OS&: llvm::outs(), Usage: "llvm-libtool-darwin [options] <input files>",
641 Title: "llvm-libtool-darwin");
642 std::exit(status: 0);
643 }
644
645 InputFiles = Args.getAllArgValues(Id: OPT_INPUT);
646 Libraries = Args.getAllArgValues(Id: OPT_libraries);
647 LibrarySearchDirs = Args.getAllArgValues(Id: OPT_librarySearchDirs);
648
649 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_outputFile))
650 OutputFile = A->getValue();
651
652 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_archType))
653 ArchType = std::make_optional(t: A->getValue());
654
655 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_fileList))
656 FileList = A->getValue();
657
658 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_dependencyInfoPath))
659 DependencyInfoPath = A->getValue();
660
661 if (const opt::Arg *A = Args.getLastArg(Ids: OPT_ignoredSyslibRoot))
662 IgnoredSyslibRoot = A->getValue();
663
664 LibraryOperation =
665 Args.hasArg(Ids: OPT_static) ? Operation::Static : Operation::None;
666 DeterministicOption = Args.hasArg(Ids: OPT_deterministicOption);
667 NonDeterministicOption = Args.hasArg(Ids: OPT_nonDeterministicOption);
668 VersionOption = Args.hasArg(Ids: OPT_version);
669 NoWarningForNoSymbols = Args.hasArg(Ids: OPT_noWarningForNoSymbols);
670 WarningsAsErrors = Args.hasArg(Ids: OPT_warningsAsErrors);
671}
672
673static Expected<Config> parseCommandLine(int Argc, char **Argv) {
674 Config C;
675 parseRawArgs(Argc, Argv);
676
677 if (LibraryOperation == Operation::None) {
678 if (!VersionOption) {
679 return createStringError(EC: std::errc::invalid_argument,
680 Fmt: "-static option: must be specified");
681 }
682 return C;
683 }
684
685 GlobalDependencyInfo =
686 DependencyInfoPath.empty()
687 ? std::make_unique<DummyDependencyInfo>()
688 : std::make_unique<DependencyInfo>(args&: DependencyInfoPath);
689
690 if (OutputFile.empty()) {
691 return createStringError(EC: std::errc::invalid_argument,
692 Fmt: "-o option: must be specified");
693 }
694
695 if (DeterministicOption && NonDeterministicOption)
696 return createStringError(EC: std::errc::invalid_argument,
697 Fmt: "cannot specify both -D and -U flags");
698 else if (NonDeterministicOption)
699 C.Deterministic = false;
700
701 if (!Libraries.empty())
702 if (Error E = processCommandLineLibraries())
703 return std::move(E);
704
705 if (!FileList.empty())
706 if (Error E = processFileList())
707 return std::move(E);
708
709 if (InputFiles.empty())
710 return createStringError(EC: std::errc::invalid_argument,
711 Fmt: "no input files specified");
712
713 if (ArchType) {
714 if (Error E = validateArchitectureName(ArchitectureName: ArchType.value()))
715 return std::move(E);
716
717 std::tie(args&: C.ArchCPUType, args&: C.ArchCPUSubtype) =
718 MachO::getCPUTypeFromArchitecture(
719 Arch: MachO::getArchitectureFromName(Name: ArchType.value()));
720 }
721
722 GlobalDependencyInfo->write(Version: "llvm-libtool-darwin " LLVM_VERSION_STRING,
723 Inputs: InputFiles, Output: OutputFile);
724
725 return C;
726}
727
728int llvm_libtool_darwin_main(int Argc, char **Argv, const llvm::ToolContext &) {
729 Expected<Config> ConfigOrErr = parseCommandLine(Argc, Argv);
730 if (!ConfigOrErr) {
731 WithColor::defaultErrorHandler(Err: ConfigOrErr.takeError());
732 return EXIT_FAILURE;
733 }
734
735 if (VersionOption)
736 cl::PrintVersionMessage();
737
738 llvm::InitializeAllTargetInfos();
739 llvm::InitializeAllTargetMCs();
740 llvm::InitializeAllAsmParsers();
741
742 LLVMContext LLVMCtx;
743 Config C = *ConfigOrErr;
744 switch (LibraryOperation) {
745 case Operation::None:
746 break;
747 case Operation::Static:
748 if (Error E = createStaticLibrary(LLVMCtx, C)) {
749 WithColor::defaultErrorHandler(Err: std::move(E));
750 return EXIT_FAILURE;
751 }
752 break;
753 }
754 return EXIT_SUCCESS;
755}
756