Bug Summary

File:tools/llvm-ar/llvm-ar.cpp
Warning:line 699, 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~svn303373/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~svn303373/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 if (Pos == -1)
477 Members.push_back(std::move(*NMOrErr));
478 else
479 Members[Pos] = std::move(*NMOrErr);
480}
481
482static void addMember(std::vector<NewArchiveMember> &Members,
483 const object::Archive::Child &M, int Pos = -1) {
484 if (Thin && !M.getParent()->isThin())
485 fail("Cannot convert a regular archive to a thin one");
486 Expected<NewArchiveMember> NMOrErr =
487 NewArchiveMember::getOldMember(M, Deterministic);
488 failIfError(NMOrErr.takeError());
489 if (Pos == -1)
490 Members.push_back(std::move(*NMOrErr));
491 else
492 Members[Pos] = std::move(*NMOrErr);
493}
494
495enum InsertAction {
496 IA_AddOldMember,
497 IA_AddNewMeber,
498 IA_Delete,
499 IA_MoveOldMember,
500 IA_MoveNewMember
501};
502
503static InsertAction computeInsertAction(ArchiveOperation Operation,
504 const object::Archive::Child &Member,
505 StringRef Name,
506 std::vector<StringRef>::iterator &Pos) {
507 if (Operation == QuickAppend || Members.empty())
508 return IA_AddOldMember;
509
510 auto MI = find_if(Members, [Name](StringRef Path) {
511 return Name == sys::path::filename(Path);
512 });
513
514 if (MI == Members.end())
515 return IA_AddOldMember;
516
517 Pos = MI;
518
519 if (Operation == Delete)
520 return IA_Delete;
521
522 if (Operation == Move)
523 return IA_MoveOldMember;
524
525 if (Operation == ReplaceOrInsert) {
526 StringRef PosName = sys::path::filename(RelPos);
527 if (!OnlyUpdate) {
528 if (PosName.empty())
529 return IA_AddNewMeber;
530 return IA_MoveNewMember;
531 }
532
533 // We could try to optimize this to a fstat, but it is not a common
534 // operation.
535 sys::fs::file_status Status;
536 failIfError(sys::fs::status(*MI, Status), *MI);
537 auto ModTimeOrErr = Member.getLastModified();
538 failIfError(ModTimeOrErr.takeError());
539 if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
540 if (PosName.empty())
541 return IA_AddOldMember;
542 return IA_MoveOldMember;
543 }
544
545 if (PosName.empty())
546 return IA_AddNewMeber;
547 return IA_MoveNewMember;
548 }
549 llvm_unreachable("No such operation")::llvm::llvm_unreachable_internal("No such operation", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/llvm-ar/llvm-ar.cpp"
, 549)
;
550}
551
552// We have to walk this twice and computing it is not trivial, so creating an
553// explicit std::vector is actually fairly efficient.
554static std::vector<NewArchiveMember>
555computeNewArchiveMembers(ArchiveOperation Operation,
556 object::Archive *OldArchive) {
557 std::vector<NewArchiveMember> Ret;
558 std::vector<NewArchiveMember> Moved;
559 int InsertPos = -1;
560 StringRef PosName = sys::path::filename(RelPos);
561 if (OldArchive) {
562 Error Err = Error::success();
563 for (auto &Child : OldArchive->children(Err)) {
564 int Pos = Ret.size();
565 Expected<StringRef> NameOrErr = Child.getName();
566 failIfError(NameOrErr.takeError());
567 StringRef Name = NameOrErr.get();
568 if (Name == PosName) {
569 assert(AddAfter || AddBefore)((AddAfter || AddBefore) ? static_cast<void> (0) : __assert_fail
("AddAfter || AddBefore", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/llvm-ar/llvm-ar.cpp"
, 569, __PRETTY_FUNCTION__))
;
570 if (AddBefore)
571 InsertPos = Pos;
572 else
573 InsertPos = Pos + 1;
574 }
575
576 std::vector<StringRef>::iterator MemberI = Members.end();
577 InsertAction Action =
578 computeInsertAction(Operation, Child, Name, MemberI);
579 switch (Action) {
580 case IA_AddOldMember:
581 addMember(Ret, Child);
582 break;
583 case IA_AddNewMeber:
584 addMember(Ret, *MemberI);
585 break;
586 case IA_Delete:
587 break;
588 case IA_MoveOldMember:
589 addMember(Moved, Child);
590 break;
591 case IA_MoveNewMember:
592 addMember(Moved, *MemberI);
593 break;
594 }
595 if (MemberI != Members.end())
596 Members.erase(MemberI);
597 }
598 failIfError(std::move(Err));
599 }
600
601 if (Operation == Delete)
602 return Ret;
603
604 if (!RelPos.empty() && InsertPos == -1)
605 fail("Insertion point not found");
606
607 if (RelPos.empty())
608 InsertPos = Ret.size();
609
610 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~svn303373/tools/llvm-ar/llvm-ar.cpp"
, 610, __PRETTY_FUNCTION__))
;
611 int Pos = InsertPos;
612 for (auto &M : Moved) {
613 Ret.insert(Ret.begin() + Pos, std::move(M));
614 ++Pos;
615 }
616
617 for (unsigned I = 0; I != Members.size(); ++I)
618 Ret.insert(Ret.begin() + InsertPos, NewArchiveMember());
619 Pos = InsertPos;
620 for (auto &Member : Members) {
621 addMember(Ret, Member, Pos);
622 ++Pos;
623 }
624
625 return Ret;
626}
627
628static object::Archive::Kind getDefaultForHost() {
629 return Triple(sys::getProcessTriple()).isOSDarwin()
630 ? object::Archive::K_DARWIN
631 : object::Archive::K_GNU;
632}
633
634static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
635 Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
636 object::ObjectFile::createObjectFile(Member.Buf->getMemBufferRef());
637
638 if (OptionalObject)
639 return isa<object::MachOObjectFile>(**OptionalObject)
640 ? object::Archive::K_DARWIN
641 : object::Archive::K_GNU;
642
643 // squelch the error in case we had a non-object file
644 consumeError(OptionalObject.takeError());
645 return getDefaultForHost();
646}
647
648static void
649performWriteOperation(ArchiveOperation Operation,
650 object::Archive *OldArchive,
651 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
652 std::vector<NewArchiveMember> *NewMembersP) {
653 std::vector<NewArchiveMember> NewMembers;
654 if (!NewMembersP)
655 NewMembers = computeNewArchiveMembers(Operation, OldArchive);
656
657 object::Archive::Kind Kind;
658 switch (FormatOpt) {
659 case Default:
660 if (Thin)
661 Kind = object::Archive::K_GNU;
662 else if (OldArchive)
663 Kind = OldArchive->kind();
664 else if (NewMembersP)
665 Kind = NewMembersP->size() ? getKindFromMember(NewMembersP->front())
666 : getDefaultForHost();
667 else
668 Kind = NewMembers.size() ? getKindFromMember(NewMembers.front())
669 : getDefaultForHost();
670 break;
671 case GNU:
672 Kind = object::Archive::K_GNU;
673 break;
674 case BSD:
675 if (Thin)
676 fail("Only the gnu format has a thin mode");
677 Kind = object::Archive::K_BSD;
678 break;
679 case DARWIN:
680 if (Thin)
681 fail("Only the gnu format has a thin mode");
682 Kind = object::Archive::K_DARWIN;
683 break;
684 }
685
686 std::pair<StringRef, std::error_code> Result =
687 writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
688 Kind, Deterministic, Thin, std::move(OldArchiveBuf));
689 failIfError(Result.second, Result.first);
690}
691
692static void createSymbolTable(object::Archive *OldArchive) {
693 // When an archive is created or modified, if the s option is given, the
694 // resulting archive will have a current symbol table. If the S option
695 // is given, it will have no symbol table.
696 // In summary, we only need to update the symbol table if we have none.
697 // This is actually very common because of broken build systems that think
698 // they have to run ranlib.
699 if (OldArchive->hasSymbolTable())
12
Called C++ object pointer is null
700 return;
701
702 performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
703}
704
705static void performOperation(ArchiveOperation Operation,
706 object::Archive *OldArchive,
707 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
708 std::vector<NewArchiveMember> *NewMembers) {
709 switch (Operation) {
9
Control jumps to 'case CreateSymTab:' at line 723
710 case Print:
711 case DisplayTable:
712 case Extract:
713 performReadOperation(Operation, OldArchive);
714 return;
715
716 case Delete:
717 case Move:
718 case QuickAppend:
719 case ReplaceOrInsert:
720 performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
721 NewMembers);
722 return;
723 case CreateSymTab:
724 createSymbolTable(OldArchive);
10
Passing null pointer value via 1st parameter 'OldArchive'
11
Calling 'createSymbolTable'
725 return;
726 }
727 llvm_unreachable("Unknown operation.")::llvm::llvm_unreachable_internal("Unknown operation.", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/llvm-ar/llvm-ar.cpp"
, 727)
;
728}
729
730static int performOperation(ArchiveOperation Operation,
731 std::vector<NewArchiveMember> *NewMembers) {
732 // Create or open the archive object.
733 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
734 MemoryBuffer::getFile(ArchiveName, -1, false);
735 std::error_code EC = Buf.getError();
736 if (EC && EC != errc::no_such_file_or_directory)
4
Taking false branch
737 fail("error opening '" + ArchiveName + "': " + EC.message() + "!");
738
739 if (!EC) {
5
Taking false branch
740 Error Err = Error::success();
741 object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
742 EC = errorToErrorCode(std::move(Err));
743 failIfError(EC,
744 "error loading '" + ArchiveName + "': " + EC.message() + "!");
745 performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
746 return 0;
747 }
748
749 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~svn303373/tools/llvm-ar/llvm-ar.cpp"
, 749, __PRETTY_FUNCTION__))
;
750
751 if (!shouldCreateArchive(Operation)) {
6
Taking true branch
752 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
753 } else {
754 if (!Create) {
755 // Produce a warning if we should and we're creating the archive
756 errs() << ToolName << ": creating " << ArchiveName << "\n";
757 }
758 }
759
760 performOperation(Operation, nullptr, nullptr, NewMembers);
7
Passing null pointer value via 2nd parameter 'OldArchive'
8
Calling 'performOperation'
761 return 0;
762}
763
764static void runMRIScript() {
765 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
766
767 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
768 failIfError(Buf.getError());
769 const MemoryBuffer &Ref = *Buf.get();
770 bool Saved = false;
771 std::vector<NewArchiveMember> NewMembers;
772 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
773 std::vector<std::unique_ptr<object::Archive>> Archives;
774
775 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
776 StringRef Line = *I;
777 StringRef CommandStr, Rest;
778 std::tie(CommandStr, Rest) = Line.split(' ');
779 Rest = Rest.trim();
780 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
781 Rest = Rest.drop_front().drop_back();
782 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
783 .Case("addlib", MRICommand::AddLib)
784 .Case("addmod", MRICommand::AddMod)
785 .Case("create", MRICommand::Create)
786 .Case("save", MRICommand::Save)
787 .Case("end", MRICommand::End)
788 .Default(MRICommand::Invalid);
789
790 switch (Command) {
791 case MRICommand::AddLib: {
792 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
793 failIfError(BufOrErr.getError(), "Could not open library");
794 ArchiveBuffers.push_back(std::move(*BufOrErr));
795 auto LibOrErr =
796 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
797 failIfError(errorToErrorCode(LibOrErr.takeError()),
798 "Could not parse library");
799 Archives.push_back(std::move(*LibOrErr));
800 object::Archive &Lib = *Archives.back();
801 {
802 Error Err = Error::success();
803 for (auto &Member : Lib.children(Err))
804 addMember(NewMembers, Member);
805 failIfError(std::move(Err));
806 }
807 break;
808 }
809 case MRICommand::AddMod:
810 addMember(NewMembers, Rest);
811 break;
812 case MRICommand::Create:
813 Create = true;
814 if (!ArchiveName.empty())
815 fail("Editing multiple archives not supported");
816 if (Saved)
817 fail("File already saved");
818 ArchiveName = Rest;
819 break;
820 case MRICommand::Save:
821 Saved = true;
822 break;
823 case MRICommand::End:
824 break;
825 case MRICommand::Invalid:
826 fail("Unknown command: " + CommandStr);
827 }
828 }
829
830 // Nothing to do if not saved.
831 if (Saved)
832 performOperation(ReplaceOrInsert, &NewMembers);
833 exit(0);
834}
835
836static int ar_main() {
837 // Do our own parsing of the command line because the CommandLine utility
838 // can't handle the grouped positional parameters without a dash.
839 ArchiveOperation Operation = parseCommandLine();
840 return performOperation(Operation, nullptr);
841}
842
843static int ranlib_main() {
844 if (RestOfArgs.size() != 1)
1
Assuming the condition is false
2
Taking false branch
845 fail(ToolName + " takes just one archive as an argument");
846 ArchiveName = RestOfArgs[0];
847 return performOperation(CreateSymTab, nullptr);
3
Calling 'performOperation'
848}
849
850int main(int argc, char **argv) {
851 ToolName = argv[0];
852 // Print a stack trace if we signal out.
853 sys::PrintStackTraceOnErrorSignal(argv[0]);
854 PrettyStackTraceProgram X(argc, argv);
855 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
856
857 llvm::InitializeAllTargetInfos();
858 llvm::InitializeAllTargetMCs();
859 llvm::InitializeAllAsmParsers();
860
861 StringRef Stem = sys::path::stem(ToolName);
862 if (Stem.find("ranlib") == StringRef::npos &&
863 Stem.find("lib") != StringRef::npos)
864 return libDriverMain(makeArrayRef(argv, argc));
865
866 // Have the command line options parsed and handle things
867 // like --help and --version.
868 cl::ParseCommandLineOptions(argc, argv,
869 "LLVM Archiver (llvm-ar)\n\n"
870 " This program archives bitcode files into single libraries\n"
871 );
872
873 if (Stem.find("ranlib") != StringRef::npos)
874 return ranlib_main();
875 if (Stem.find("ar") != StringRef::npos)
876 return ar_main();
877 fail("Not ranlib, ar or lib!");
878}