Bug Summary

File:tools/llvm-ar/llvm-ar.cpp
Warning:line 697, column 7
Called C++ object pointer is null

Annotated Source Code

1//===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Builds up (relatively) standard unix archive files (.a) containing LLVM
11// bitcode or other files.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/StringSwitch.h"
16#include "llvm/ADT/Triple.h"
17#include "llvm/IR/LLVMContext.h"
18#include "llvm/IR/Module.h"
19#include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
20#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
21#include "llvm/Object/Archive.h"
22#include "llvm/Object/ArchiveWriter.h"
23#include "llvm/Object/MachO.h"
24#include "llvm/Object/ObjectFile.h"
25#include "llvm/Support/Chrono.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Errc.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/Format.h"
30#include "llvm/Support/LineIterator.h"
31#include "llvm/Support/ManagedStatic.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/PrettyStackTrace.h"
35#include "llvm/Support/Signals.h"
36#include "llvm/Support/TargetSelect.h"
37#include "llvm/Support/ToolOutputFile.h"
38#include "llvm/Support/raw_ostream.h"
39#include <algorithm>
40#include <cstdlib>
41#include <memory>
42
43#if !defined(_MSC_VER) && !defined(__MINGW32__)
44#include <unistd.h>
45#else
46#include <io.h>
47#endif
48
49using namespace llvm;
50
51// The name this program was invoked as.
52static StringRef ToolName;
53
54// Show the error message and exit.
55LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) static void fail(Twine Error) {
56 errs() << ToolName << ": " << Error << ".\n";
57 cl::PrintHelpMessage();
58 exit(1);
59}
60
61static void failIfError(std::error_code EC, Twine Context = "") {
62 if (!EC)
63 return;
64
65 std::string ContextStr = Context.str();
66 if (ContextStr == "")
67 fail(EC.message());
68 fail(Context + ": " + EC.message());
69}
70
71static void failIfError(Error E, Twine Context = "") {
72 if (!E)
73 return;
74
75 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
76 std::string ContextStr = Context.str();
77 if (ContextStr == "")
78 fail(EIB.message());
79 fail(Context + ": " + EIB.message());
80 });
81}
82
83// llvm-ar/llvm-ranlib remaining positional arguments.
84static cl::list<std::string>
85 RestOfArgs(cl::Positional, cl::ZeroOrMore,
86 cl::desc("[relpos] [count] <archive-file> [members]..."));
87
88static cl::opt<bool> MRI("M", cl::desc(""));
89static cl::opt<std::string> Plugin("plugin", cl::desc("plugin (ignored for compatibility"));
90
91namespace {
92enum Format { Default, GNU, BSD, DARWIN };
93}
94
95static cl::opt<Format>
96 FormatOpt("format", cl::desc("Archive format to create"),
97 cl::values(clEnumValN(Default, "default", "default")llvm::cl::OptionEnumValue { "default", int(Default), "default"
}
,
98 clEnumValN(GNU, "gnu", "gnu")llvm::cl::OptionEnumValue { "gnu", int(GNU), "gnu" },
99 clEnumValN(DARWIN, "darwin", "darwin")llvm::cl::OptionEnumValue { "darwin", int(DARWIN), "darwin" },
100 clEnumValN(BSD, "bsd", "bsd")llvm::cl::OptionEnumValue { "bsd", int(BSD), "bsd" }));
101
102static std::string Options;
103
104// Provide additional help output explaining the operations and modifiers of
105// llvm-ar. This object instructs the CommandLine library to print the text of
106// the constructor when the --help option is given.
107static cl::extrahelp MoreHelp(
108 "\nOPERATIONS:\n"
109 " d[NsS] - delete file(s) from the archive\n"
110 " m[abiSs] - move file(s) in the archive\n"
111 " p[kN] - print file(s) found in the archive\n"
112 " q[ufsS] - quick append file(s) to the archive\n"
113 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
114 " t - display contents of archive\n"
115 " x[No] - extract file(s) from the archive\n"
116 "\nMODIFIERS (operation specific):\n"
117 " [a] - put file(s) after [relpos]\n"
118 " [b] - put file(s) before [relpos] (same as [i])\n"
119 " [i] - put file(s) before [relpos] (same as [b])\n"
120 " [o] - preserve original dates\n"
121 " [s] - create an archive index (cf. ranlib)\n"
122 " [S] - do not build a symbol table\n"
123 " [T] - create a thin archive\n"
124 " [u] - update only files newer than archive contents\n"
125 "\nMODIFIERS (generic):\n"
126 " [c] - do not warn if the library had to be created\n"
127 " [v] - be verbose about actions taken\n"
128);
129
130// This enumeration delineates the kinds of operations on an archive
131// that are permitted.
132enum ArchiveOperation {
133 Print, ///< Print the contents of the archive
134 Delete, ///< Delete the specified members
135 Move, ///< Move members to end or as given by {a,b,i} modifiers
136 QuickAppend, ///< Quickly append to end of archive
137 ReplaceOrInsert, ///< Replace or Insert members
138 DisplayTable, ///< Display the table of contents
139 Extract, ///< Extract files back to file system
140 CreateSymTab ///< Create a symbol table in an existing archive
141};
142
143// Modifiers to follow operation to vary behavior
144static bool AddAfter = false; ///< 'a' modifier
145static bool AddBefore = false; ///< 'b' modifier
146static bool Create = false; ///< 'c' modifier
147static bool OriginalDates = false; ///< 'o' modifier
148static bool OnlyUpdate = false; ///< 'u' modifier
149static bool Verbose = false; ///< 'v' modifier
150static bool Symtab = true; ///< 's' modifier
151static bool Deterministic = true; ///< 'D' and 'U' modifiers
152static bool Thin = false; ///< 'T' modifier
153
154// Relative Positional Argument (for insert/move). This variable holds
155// the name of the archive member to which the 'a', 'b' or 'i' modifier
156// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
157// one variable.
158static std::string RelPos;
159
160// This variable holds the name of the archive file as given on the
161// command line.
162static std::string ArchiveName;
163
164// This variable holds the list of member files to proecess, as given
165// on the command line.
166static std::vector<StringRef> Members;
167
168// Extract the member filename from the command line for the [relpos] argument
169// associated with a, b, and i modifiers
170static void getRelPos() {
171 if(RestOfArgs.size() == 0)
172 fail("Expected [relpos] for a, b, or i modifier");
173 RelPos = RestOfArgs[0];
174 RestOfArgs.erase(RestOfArgs.begin());
175}
176
177static void getOptions() {
178 if(RestOfArgs.size() == 0)
179 fail("Expected options");
180 Options = RestOfArgs[0];
181 RestOfArgs.erase(RestOfArgs.begin());
182}
183
184// Get the archive file name from the command line
185static void getArchive() {
186 if(RestOfArgs.size() == 0)
187 fail("An archive name must be specified");
188 ArchiveName = RestOfArgs[0];
189 RestOfArgs.erase(RestOfArgs.begin());
190}
191
192// Copy over remaining items in RestOfArgs to our Members vector
193static void getMembers() {
194 for (auto &Arg : RestOfArgs)
195 Members.push_back(Arg);
196}
197
198static void runMRIScript();
199
200// Parse the command line options as presented and return the operation
201// specified. Process all modifiers and check to make sure that constraints on
202// modifier/operation pairs have not been violated.
203static ArchiveOperation parseCommandLine() {
204 if (MRI) {
205 if (!RestOfArgs.empty())
206 fail("Cannot mix -M and other options");
207 runMRIScript();
208 }
209
210 getOptions();
211
212 // Keep track of number of operations. We can only specify one
213 // per execution.
214 unsigned NumOperations = 0;
215
216 // Keep track of the number of positional modifiers (a,b,i). Only
217 // one can be specified.
218 unsigned NumPositional = 0;
219
220 // Keep track of which operation was requested
221 ArchiveOperation Operation;
222
223 bool MaybeJustCreateSymTab = false;
224
225 for(unsigned i=0; i<Options.size(); ++i) {
226 switch(Options[i]) {
227 case 'd': ++NumOperations; Operation = Delete; break;
228 case 'm': ++NumOperations; Operation = Move ; break;
229 case 'p': ++NumOperations; Operation = Print; break;
230 case 'q': ++NumOperations; Operation = QuickAppend; break;
231 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
232 case 't': ++NumOperations; Operation = DisplayTable; break;
233 case 'x': ++NumOperations; Operation = Extract; break;
234 case 'c': Create = true; break;
235 case 'l': /* accepted but unused */ break;
236 case 'o': OriginalDates = true; break;
237 case 's':
238 Symtab = true;
239 MaybeJustCreateSymTab = true;
240 break;
241 case 'S':
242 Symtab = false;
243 break;
244 case 'u': OnlyUpdate = true; break;
245 case 'v': Verbose = true; break;
246 case 'a':
247 getRelPos();
248 AddAfter = true;
249 NumPositional++;
250 break;
251 case 'b':
252 getRelPos();
253 AddBefore = true;
254 NumPositional++;
255 break;
256 case 'i':
257 getRelPos();
258 AddBefore = true;
259 NumPositional++;
260 break;
261 case 'D':
262 Deterministic = true;
263 break;
264 case 'U':
265 Deterministic = false;
266 break;
267 case 'T':
268 Thin = true;
269 break;
270 default:
271 fail(std::string("unknown option ") + Options[i]);
272 }
273 }
274
275 // At this point, the next thing on the command line must be
276 // the archive name.
277 getArchive();
278
279 // Everything on the command line at this point is a member.
280 getMembers();
281
282 if (NumOperations == 0 && MaybeJustCreateSymTab) {
283 NumOperations = 1;
284 Operation = CreateSymTab;
285 if (!Members.empty())
286 fail("The s operation takes only an archive as argument");
287 }
288
289 // Perform various checks on the operation/modifier specification
290 // to make sure we are dealing with a legal request.
291 if (NumOperations == 0)
292 fail("You must specify at least one of the operations");
293 if (NumOperations > 1)
294 fail("Only one operation may be specified");
295 if (NumPositional > 1)
296 fail("You may only specify one of a, b, and i modifiers");
297 if (AddAfter || AddBefore) {
298 if (Operation != Move && Operation != ReplaceOrInsert)
299 fail("The 'a', 'b' and 'i' modifiers can only be specified with "
300 "the 'm' or 'r' operations");
301 }
302 if (OriginalDates && Operation != Extract)
303 fail("The 'o' modifier is only applicable to the 'x' operation");
304 if (OnlyUpdate && Operation != ReplaceOrInsert)
305 fail("The 'u' modifier is only applicable to the 'r' operation");
306
307 // Return the parsed operation to the caller
308 return Operation;
309}
310
311// Implements the 'p' operation. This function traverses the archive
312// looking for members that match the path list.
313static void doPrint(StringRef Name, const object::Archive::Child &C) {
314 if (Verbose)
315 outs() << "Printing " << Name << "\n";
316
317 Expected<StringRef> DataOrErr = C.getBuffer();
318 failIfError(DataOrErr.takeError());
319 StringRef Data = *DataOrErr;
320 outs().write(Data.data(), Data.size());
321}
322
323// Utility function for printing out the file mode when the 't' operation is in
324// verbose mode.
325static void printMode(unsigned mode) {
326 outs() << ((mode & 004) ? "r" : "-");
327 outs() << ((mode & 002) ? "w" : "-");
328 outs() << ((mode & 001) ? "x" : "-");
329}
330
331// Implement the 't' operation. This function prints out just
332// the file names of each of the members. However, if verbose mode is requested
333// ('v' modifier) then the file type, permission mode, user, group, size, and
334// modification time are also printed.
335static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
336 if (Verbose) {
337 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
338 failIfError(ModeOrErr.takeError());
339 sys::fs::perms Mode = ModeOrErr.get();
340 printMode((Mode >> 6) & 007);
341 printMode((Mode >> 3) & 007);
342 printMode(Mode & 007);
343 Expected<unsigned> UIDOrErr = C.getUID();
344 failIfError(UIDOrErr.takeError());
345 outs() << ' ' << UIDOrErr.get();
346 Expected<unsigned> GIDOrErr = C.getGID();
347 failIfError(GIDOrErr.takeError());
348 outs() << '/' << GIDOrErr.get();
349 Expected<uint64_t> Size = C.getSize();
350 failIfError(Size.takeError());
351 outs() << ' ' << format("%6llu", Size.get());
352 auto ModTimeOrErr = C.getLastModified();
353 failIfError(ModTimeOrErr.takeError());
354 outs() << ' ' << ModTimeOrErr.get();
355 outs() << ' ';
356 }
357
358 if (C.getParent()->isThin()) {
359 outs() << sys::path::parent_path(ArchiveName);
360 outs() << '/';
361 }
362 outs() << Name << "\n";
363}
364
365// Implement the 'x' operation. This function extracts files back to the file
366// system.
367static void doExtract(StringRef Name, const object::Archive::Child &C) {
368 // Retain the original mode.
369 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
370 failIfError(ModeOrErr.takeError());
371 sys::fs::perms Mode = ModeOrErr.get();
372
373 int FD;
374 failIfError(sys::fs::openFileForWrite(sys::path::filename(Name), FD,
375 sys::fs::F_None, Mode),
376 Name);
377
378 {
379 raw_fd_ostream file(FD, false);
380
381 // Get the data and its length
382 Expected<StringRef> BufOrErr = C.getBuffer();
383 failIfError(BufOrErr.takeError());
384 StringRef Data = BufOrErr.get();
385
386 // Write the data.
387 file.write(Data.data(), Data.size());
388 }
389
390 // If we're supposed to retain the original modification times, etc. do so
391 // now.
392 if (OriginalDates) {
393 auto ModTimeOrErr = C.getLastModified();
394 failIfError(ModTimeOrErr.takeError());
395 failIfError(
396 sys::fs::setLastModificationAndAccessTime(FD, ModTimeOrErr.get()));
397 }
398
399 if (close(FD))
400 fail("Could not close the file");
401}
402
403static bool shouldCreateArchive(ArchiveOperation Op) {
404 switch (Op) {
405 case Print:
406 case Delete:
407 case Move:
408 case DisplayTable:
409 case Extract:
410 case CreateSymTab:
411 return false;
412
413 case QuickAppend:
414 case ReplaceOrInsert:
415 return true;
416 }
417
418 llvm_unreachable("Missing entry in covered switch.")::llvm::llvm_unreachable_internal("Missing entry in covered switch."
, "/build/llvm-toolchain-snapshot-6.0~svn315928/tools/llvm-ar/llvm-ar.cpp"
, 418)
;
419}
420
421static void performReadOperation(ArchiveOperation Operation,
422 object::Archive *OldArchive) {
423 if (Operation == Extract && OldArchive->isThin())
424 fail("extracting from a thin archive is not supported");
425
426 bool Filter = !Members.empty();
427 {
428 Error Err = Error::success();
429 for (auto &C : OldArchive->children(Err)) {
430 Expected<StringRef> NameOrErr = C.getName();
431 failIfError(NameOrErr.takeError());
432 StringRef Name = NameOrErr.get();
433
434 if (Filter) {
435 auto I = find(Members, Name);
436 if (I == Members.end())
437 continue;
438 Members.erase(I);
439 }
440
441 switch (Operation) {
442 default:
443 llvm_unreachable("Not a read operation")::llvm::llvm_unreachable_internal("Not a read operation", "/build/llvm-toolchain-snapshot-6.0~svn315928/tools/llvm-ar/llvm-ar.cpp"
, 443)
;
444 case Print:
445 doPrint(Name, C);
446 break;
447 case DisplayTable:
448 doDisplayTable(Name, C);
449 break;
450 case Extract:
451 doExtract(Name, C);
452 break;
453 }
454 }
455 failIfError(std::move(Err));
456 }
457
458 if (Members.empty())
459 return;
460 for (StringRef Name : Members)
461 errs() << Name << " was not found\n";
462 exit(1);
463}
464
465static void addMember(std::vector<NewArchiveMember> &Members,
466 StringRef FileName, int Pos = -1) {
467 Expected<NewArchiveMember> NMOrErr =
468 NewArchiveMember::getFile(FileName, Deterministic);
469 failIfError(NMOrErr.takeError(), FileName);
470
471 // Use the basename of the object path for the member name.
472 NMOrErr->MemberName = sys::path::filename(NMOrErr->MemberName);
473
474 if (Pos == -1)
475 Members.push_back(std::move(*NMOrErr));
476 else
477 Members[Pos] = std::move(*NMOrErr);
478}
479
480static void addMember(std::vector<NewArchiveMember> &Members,
481 const object::Archive::Child &M, int Pos = -1) {
482 if (Thin && !M.getParent()->isThin())
483 fail("Cannot convert a regular archive to a thin one");
484 Expected<NewArchiveMember> NMOrErr =
485 NewArchiveMember::getOldMember(M, Deterministic);
486 failIfError(NMOrErr.takeError());
487 if (Pos == -1)
488 Members.push_back(std::move(*NMOrErr));
489 else
490 Members[Pos] = std::move(*NMOrErr);
491}
492
493enum InsertAction {
494 IA_AddOldMember,
495 IA_AddNewMember,
496 IA_Delete,
497 IA_MoveOldMember,
498 IA_MoveNewMember
499};
500
501static InsertAction computeInsertAction(ArchiveOperation Operation,
502 const object::Archive::Child &Member,
503 StringRef Name,
504 std::vector<StringRef>::iterator &Pos) {
505 if (Operation == QuickAppend || Members.empty())
506 return IA_AddOldMember;
507
508 auto MI = find_if(Members, [Name](StringRef Path) {
509 return Name == sys::path::filename(Path);
510 });
511
512 if (MI == Members.end())
513 return IA_AddOldMember;
514
515 Pos = MI;
516
517 if (Operation == Delete)
518 return IA_Delete;
519
520 if (Operation == Move)
521 return IA_MoveOldMember;
522
523 if (Operation == ReplaceOrInsert) {
524 StringRef PosName = sys::path::filename(RelPos);
525 if (!OnlyUpdate) {
526 if (PosName.empty())
527 return IA_AddNewMember;
528 return IA_MoveNewMember;
529 }
530
531 // We could try to optimize this to a fstat, but it is not a common
532 // operation.
533 sys::fs::file_status Status;
534 failIfError(sys::fs::status(*MI, Status), *MI);
535 auto ModTimeOrErr = Member.getLastModified();
536 failIfError(ModTimeOrErr.takeError());
537 if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
538 if (PosName.empty())
539 return IA_AddOldMember;
540 return IA_MoveOldMember;
541 }
542
543 if (PosName.empty())
544 return IA_AddNewMember;
545 return IA_MoveNewMember;
546 }
547 llvm_unreachable("No such operation")::llvm::llvm_unreachable_internal("No such operation", "/build/llvm-toolchain-snapshot-6.0~svn315928/tools/llvm-ar/llvm-ar.cpp"
, 547)
;
548}
549
550// We have to walk this twice and computing it is not trivial, so creating an
551// explicit std::vector is actually fairly efficient.
552static std::vector<NewArchiveMember>
553computeNewArchiveMembers(ArchiveOperation Operation,
554 object::Archive *OldArchive) {
555 std::vector<NewArchiveMember> Ret;
556 std::vector<NewArchiveMember> Moved;
557 int InsertPos = -1;
558 StringRef PosName = sys::path::filename(RelPos);
559 if (OldArchive) {
560 Error Err = Error::success();
561 for (auto &Child : OldArchive->children(Err)) {
562 int Pos = Ret.size();
563 Expected<StringRef> NameOrErr = Child.getName();
564 failIfError(NameOrErr.takeError());
565 StringRef Name = NameOrErr.get();
566 if (Name == PosName) {
567 assert(AddAfter || AddBefore)((AddAfter || AddBefore) ? static_cast<void> (0) : __assert_fail
("AddAfter || AddBefore", "/build/llvm-toolchain-snapshot-6.0~svn315928/tools/llvm-ar/llvm-ar.cpp"
, 567, __PRETTY_FUNCTION__))
;
568 if (AddBefore)
569 InsertPos = Pos;
570 else
571 InsertPos = Pos + 1;
572 }
573
574 std::vector<StringRef>::iterator MemberI = Members.end();
575 InsertAction Action =
576 computeInsertAction(Operation, Child, Name, MemberI);
577 switch (Action) {
578 case IA_AddOldMember:
579 addMember(Ret, Child);
580 break;
581 case IA_AddNewMember:
582 addMember(Ret, *MemberI);
583 break;
584 case IA_Delete:
585 break;
586 case IA_MoveOldMember:
587 addMember(Moved, Child);
588 break;
589 case IA_MoveNewMember:
590 addMember(Moved, *MemberI);
591 break;
592 }
593 if (MemberI != Members.end())
594 Members.erase(MemberI);
595 }
596 failIfError(std::move(Err));
597 }
598
599 if (Operation == Delete)
600 return Ret;
601
602 if (!RelPos.empty() && InsertPos == -1)
603 fail("Insertion point not found");
604
605 if (RelPos.empty())
606 InsertPos = Ret.size();
607
608 assert(unsigned(InsertPos) <= Ret.size())((unsigned(InsertPos) <= Ret.size()) ? static_cast<void
> (0) : __assert_fail ("unsigned(InsertPos) <= Ret.size()"
, "/build/llvm-toolchain-snapshot-6.0~svn315928/tools/llvm-ar/llvm-ar.cpp"
, 608, __PRETTY_FUNCTION__))
;
609 int Pos = InsertPos;
610 for (auto &M : Moved) {
611 Ret.insert(Ret.begin() + Pos, std::move(M));
612 ++Pos;
613 }
614
615 for (unsigned I = 0; I != Members.size(); ++I)
616 Ret.insert(Ret.begin() + InsertPos, NewArchiveMember());
617 Pos = InsertPos;
618 for (auto &Member : Members) {
619 addMember(Ret, Member, Pos);
620 ++Pos;
621 }
622
623 return Ret;
624}
625
626static object::Archive::Kind getDefaultForHost() {
627 return Triple(sys::getProcessTriple()).isOSDarwin()
628 ? object::Archive::K_DARWIN
629 : object::Archive::K_GNU;
630}
631
632static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
633 Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
634 object::ObjectFile::createObjectFile(Member.Buf->getMemBufferRef());
635
636 if (OptionalObject)
637 return isa<object::MachOObjectFile>(**OptionalObject)
638 ? object::Archive::K_DARWIN
639 : object::Archive::K_GNU;
640
641 // squelch the error in case we had a non-object file
642 consumeError(OptionalObject.takeError());
643 return getDefaultForHost();
644}
645
646static void
647performWriteOperation(ArchiveOperation Operation,
648 object::Archive *OldArchive,
649 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
650 std::vector<NewArchiveMember> *NewMembersP) {
651 std::vector<NewArchiveMember> NewMembers;
652 if (!NewMembersP)
653 NewMembers = computeNewArchiveMembers(Operation, OldArchive);
654
655 object::Archive::Kind Kind;
656 switch (FormatOpt) {
657 case Default:
658 if (Thin)
659 Kind = object::Archive::K_GNU;
660 else if (OldArchive)
661 Kind = OldArchive->kind();
662 else if (NewMembersP)
663 Kind = NewMembersP->size() ? getKindFromMember(NewMembersP->front())
664 : getDefaultForHost();
665 else
666 Kind = NewMembers.size() ? getKindFromMember(NewMembers.front())
667 : getDefaultForHost();
668 break;
669 case GNU:
670 Kind = object::Archive::K_GNU;
671 break;
672 case BSD:
673 if (Thin)
674 fail("Only the gnu format has a thin mode");
675 Kind = object::Archive::K_BSD;
676 break;
677 case DARWIN:
678 if (Thin)
679 fail("Only the gnu format has a thin mode");
680 Kind = object::Archive::K_DARWIN;
681 break;
682 }
683
684 Error E =
685 writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
686 Kind, Deterministic, Thin, std::move(OldArchiveBuf));
687 failIfError(std::move(E), ArchiveName);
688}
689
690static void createSymbolTable(object::Archive *OldArchive) {
691 // When an archive is created or modified, if the s option is given, the
692 // resulting archive will have a current symbol table. If the S option
693 // is given, it will have no symbol table.
694 // In summary, we only need to update the symbol table if we have none.
695 // This is actually very common because of broken build systems that think
696 // they have to run ranlib.
697 if (OldArchive->hasSymbolTable())
12
Called C++ object pointer is null
698 return;
699
700 performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
701}
702
703static void performOperation(ArchiveOperation Operation,
704 object::Archive *OldArchive,
705 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
706 std::vector<NewArchiveMember> *NewMembers) {
707 switch (Operation) {
9
Control jumps to 'case CreateSymTab:' at line 721
708 case Print:
709 case DisplayTable:
710 case Extract:
711 performReadOperation(Operation, OldArchive);
712 return;
713
714 case Delete:
715 case Move:
716 case QuickAppend:
717 case ReplaceOrInsert:
718 performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
719 NewMembers);
720 return;
721 case CreateSymTab:
722 createSymbolTable(OldArchive);
10
Passing null pointer value via 1st parameter 'OldArchive'
11
Calling 'createSymbolTable'
723 return;
724 }
725 llvm_unreachable("Unknown operation.")::llvm::llvm_unreachable_internal("Unknown operation.", "/build/llvm-toolchain-snapshot-6.0~svn315928/tools/llvm-ar/llvm-ar.cpp"
, 725)
;
726}
727
728static int performOperation(ArchiveOperation Operation,
729 std::vector<NewArchiveMember> *NewMembers) {
730 // Create or open the archive object.
731 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
732 MemoryBuffer::getFile(ArchiveName, -1, false);
733 std::error_code EC = Buf.getError();
734 if (EC && EC != errc::no_such_file_or_directory)
4
Taking false branch
735 fail("error opening '" + ArchiveName + "': " + EC.message() + "!");
736
737 if (!EC) {
5
Taking false branch
738 Error Err = Error::success();
739 object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
740 EC = errorToErrorCode(std::move(Err));
741 failIfError(EC,
742 "error loading '" + ArchiveName + "': " + EC.message() + "!");
743 performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
744 return 0;
745 }
746
747 assert(EC == errc::no_such_file_or_directory)((EC == errc::no_such_file_or_directory) ? static_cast<void
> (0) : __assert_fail ("EC == errc::no_such_file_or_directory"
, "/build/llvm-toolchain-snapshot-6.0~svn315928/tools/llvm-ar/llvm-ar.cpp"
, 747, __PRETTY_FUNCTION__))
;
748
749 if (!shouldCreateArchive(Operation)) {
6
Taking true branch
750 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
751 } else {
752 if (!Create) {
753 // Produce a warning if we should and we're creating the archive
754 errs() << ToolName << ": creating " << ArchiveName << "\n";
755 }
756 }
757
758 performOperation(Operation, nullptr, nullptr, NewMembers);
7
Passing null pointer value via 2nd parameter 'OldArchive'
8
Calling 'performOperation'
759 return 0;
760}
761
762static void runMRIScript() {
763 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
764
765 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
766 failIfError(Buf.getError());
767 const MemoryBuffer &Ref = *Buf.get();
768 bool Saved = false;
769 std::vector<NewArchiveMember> NewMembers;
770 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
771 std::vector<std::unique_ptr<object::Archive>> Archives;
772
773 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
774 StringRef Line = *I;
775 StringRef CommandStr, Rest;
776 std::tie(CommandStr, Rest) = Line.split(' ');
777 Rest = Rest.trim();
778 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
779 Rest = Rest.drop_front().drop_back();
780 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
781 .Case("addlib", MRICommand::AddLib)
782 .Case("addmod", MRICommand::AddMod)
783 .Case("create", MRICommand::Create)
784 .Case("save", MRICommand::Save)
785 .Case("end", MRICommand::End)
786 .Default(MRICommand::Invalid);
787
788 switch (Command) {
789 case MRICommand::AddLib: {
790 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
791 failIfError(BufOrErr.getError(), "Could not open library");
792 ArchiveBuffers.push_back(std::move(*BufOrErr));
793 auto LibOrErr =
794 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
795 failIfError(errorToErrorCode(LibOrErr.takeError()),
796 "Could not parse library");
797 Archives.push_back(std::move(*LibOrErr));
798 object::Archive &Lib = *Archives.back();
799 {
800 Error Err = Error::success();
801 for (auto &Member : Lib.children(Err))
802 addMember(NewMembers, Member);
803 failIfError(std::move(Err));
804 }
805 break;
806 }
807 case MRICommand::AddMod:
808 addMember(NewMembers, Rest);
809 break;
810 case MRICommand::Create:
811 Create = true;
812 if (!ArchiveName.empty())
813 fail("Editing multiple archives not supported");
814 if (Saved)
815 fail("File already saved");
816 ArchiveName = Rest;
817 break;
818 case MRICommand::Save:
819 Saved = true;
820 break;
821 case MRICommand::End:
822 break;
823 case MRICommand::Invalid:
824 fail("Unknown command: " + CommandStr);
825 }
826 }
827
828 // Nothing to do if not saved.
829 if (Saved)
830 performOperation(ReplaceOrInsert, &NewMembers);
831 exit(0);
832}
833
834static int ar_main() {
835 // Do our own parsing of the command line because the CommandLine utility
836 // can't handle the grouped positional parameters without a dash.
837 ArchiveOperation Operation = parseCommandLine();
838 return performOperation(Operation, nullptr);
839}
840
841static int ranlib_main() {
842 if (RestOfArgs.size() != 1)
1
Assuming the condition is false
2
Taking false branch
843 fail(ToolName + " takes just one archive as an argument");
844 ArchiveName = RestOfArgs[0];
845 return performOperation(CreateSymTab, nullptr);
3
Calling 'performOperation'
846}
847
848int main(int argc, char **argv) {
849 ToolName = argv[0];
850 // Print a stack trace if we signal out.
851 sys::PrintStackTraceOnErrorSignal(argv[0]);
852 PrettyStackTraceProgram X(argc, argv);
853 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
854
855 llvm::InitializeAllTargetInfos();
856 llvm::InitializeAllTargetMCs();
857 llvm::InitializeAllAsmParsers();
858
859 StringRef Stem = sys::path::stem(ToolName);
860 if (Stem.find("dlltool") != StringRef::npos)
861 return dlltoolDriverMain(makeArrayRef(argv, argc));
862
863 if (Stem.find("ranlib") == StringRef::npos &&
864 Stem.find("lib") != StringRef::npos)
865 return libDriverMain(makeArrayRef(argv, argc));
866
867 // Have the command line options parsed and handle things
868 // like --help and --version.
869 cl::ParseCommandLineOptions(argc, argv,
870 "LLVM Archiver (llvm-ar)\n\n"
871 " This program archives bitcode files into single libraries\n"
872 );
873
874 if (Stem.find("ranlib") != StringRef::npos)
875 return ranlib_main();
876 if (Stem.find("ar") != StringRef::npos)
877 return ar_main();
878 fail("Not ranlib, ar, lib or dlltool!");
879}