Bug Summary

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