Reduce sys::Path usage in llvm-ar.
[oota-llvm.git] / tools / llvm-ar / Archive.cpp
1 //===-- Archive.cpp - Generic LLVM archive functions ------------*- C++ -*-===//
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 // This file contains the implementation of the Archive and ArchiveMember
11 // classes that is common to both reading and writing archives..
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Archive.h"
16 #include "ArchiveInternals.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Process.h"
22 #include "llvm/Support/system_error.h"
23 #include <cstring>
24 #include <memory>
25 using namespace llvm;
26
27 // getMemberSize - compute the actual physical size of the file member as seen
28 // on disk. This isn't the size of member's payload. Use getSize() for that.
29 unsigned
30 ArchiveMember::getMemberSize() const {
31   // Basically its the file size plus the header size
32   unsigned result =  info.fileSize + sizeof(ArchiveMemberHeader);
33
34   // If it has a long filename, include the name length
35   if (hasLongFilename())
36     result += path.length() + 1;
37
38   // If its now odd lengthed, include the padding byte
39   if (result % 2 != 0 )
40     result++;
41
42   return result;
43 }
44
45 // This default constructor is only use by the ilist when it creates its
46 // sentry node. We give it specific static values to make it stand out a bit.
47 ArchiveMember::ArchiveMember()
48   : parent(0), path("--invalid--"), flags(0), data(0)
49 {
50   info.user = sys::Process::GetCurrentUserId();
51   info.group = sys::Process::GetCurrentGroupId();
52   info.mode = 0777;
53   info.fileSize = 0;
54   info.modTime = sys::TimeValue::now();
55 }
56
57 // This is the constructor that the Archive class uses when it is building or
58 // reading an archive. It just defaults a few things and ensures the parent is
59 // set for the iplist. The Archive class fills in the ArchiveMember's data.
60 // This is required because correctly setting the data may depend on other
61 // things in the Archive.
62 ArchiveMember::ArchiveMember(Archive* PAR)
63   : parent(PAR), path(), flags(0), data(0)
64 {
65 }
66
67 // This method allows an ArchiveMember to be replaced with the data for a
68 // different file, presumably as an update to the member. It also makes sure
69 // the flags are reset correctly.
70 bool ArchiveMember::replaceWith(const sys::Path& newFile, std::string* ErrMsg) {
71   bool Exists;
72   if (sys::fs::exists(newFile.str(), Exists) || !Exists) {
73     if (ErrMsg)
74       *ErrMsg = "Can not replace an archive member with a non-existent file";
75     return true;
76   }
77
78   data = 0;
79   path = newFile.str();
80
81   // SVR4 symbol tables have an empty name
82   if (path == ARFILE_SVR4_SYMTAB_NAME)
83     flags |= SVR4SymbolTableFlag;
84   else
85     flags &= ~SVR4SymbolTableFlag;
86
87   // BSD4.4 symbol tables have a special name
88   if (path == ARFILE_BSD4_SYMTAB_NAME)
89     flags |= BSD4SymbolTableFlag;
90   else
91     flags &= ~BSD4SymbolTableFlag;
92
93   // String table name
94   if (path == ARFILE_STRTAB_NAME)
95     flags |= StringTableFlag;
96   else
97     flags &= ~StringTableFlag;
98
99   // If it has a slash then it has a path
100   bool hasSlash = path.find('/') != std::string::npos;
101   if (hasSlash)
102     flags |= HasPathFlag;
103   else
104     flags &= ~HasPathFlag;
105
106   // If it has a slash or its over 15 chars then its a long filename format
107   if (hasSlash || path.length() > 15)
108     flags |= HasLongFilenameFlag;
109   else
110     flags &= ~HasLongFilenameFlag;
111
112   // Get the signature and status info
113   const char* signature = (const char*) data;
114   SmallString<4> magic;
115   if (!signature) {
116     sys::fs::get_magic(path, magic.capacity(), magic);
117     signature = magic.c_str();
118     sys::PathWithStatus PWS(path);
119     const sys::FileStatus *FSinfo = PWS.getFileStatus(false, ErrMsg);
120     if (FSinfo)
121       info = *FSinfo;
122     else
123       return true;
124   }
125
126   // Determine what kind of file it is.
127   if (sys::fs::identify_magic(StringRef(signature, 4)) ==
128       sys::fs::file_magic::bitcode)
129     flags |= BitcodeFlag;
130   else
131     flags &= ~BitcodeFlag;
132
133   return false;
134 }
135
136 // Archive constructor - this is the only constructor that gets used for the
137 // Archive class. Everything else (default,copy) is deprecated. This just
138 // initializes and maps the file into memory, if requested.
139 Archive::Archive(const sys::Path& filename, LLVMContext& C)
140   : archPath(filename), members(), mapfile(0), base(0), symTab(), strtab(),
141     symTabSize(0), firstFileOffset(0), modules(), foreignST(0), Context(C) {
142 }
143
144 bool
145 Archive::mapToMemory(std::string* ErrMsg) {
146   OwningPtr<MemoryBuffer> File;
147   if (error_code ec = MemoryBuffer::getFile(archPath.c_str(), File)) {
148     if (ErrMsg)
149       *ErrMsg = ec.message();
150     return true;
151   }
152   mapfile = File.take();
153   base = mapfile->getBufferStart();
154   return false;
155 }
156
157 void Archive::cleanUpMemory() {
158   // Shutdown the file mapping
159   delete mapfile;
160   mapfile = 0;
161   base = 0;
162
163   // Forget the entire symbol table
164   symTab.clear();
165   symTabSize = 0;
166
167   firstFileOffset = 0;
168
169   // Free the foreign symbol table member
170   if (foreignST) {
171     delete foreignST;
172     foreignST = 0;
173   }
174
175   // Delete any Modules and ArchiveMember's we've allocated as a result of
176   // symbol table searches.
177   for (ModuleMap::iterator I=modules.begin(), E=modules.end(); I != E; ++I ) {
178     delete I->second.first;
179     delete I->second.second;
180   }
181 }
182
183 // Archive destructor - just clean up memory
184 Archive::~Archive() {
185   cleanUpMemory();
186 }
187
188
189
190 static void getSymbols(Module*M, std::vector<std::string>& symbols) {
191   // Loop over global variables
192   for (Module::global_iterator GI = M->global_begin(), GE=M->global_end(); GI != GE; ++GI)
193     if (!GI->isDeclaration() && !GI->hasLocalLinkage())
194       if (!GI->getName().empty())
195         symbols.push_back(GI->getName());
196
197   // Loop over functions
198   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
199     if (!FI->isDeclaration() && !FI->hasLocalLinkage())
200       if (!FI->getName().empty())
201         symbols.push_back(FI->getName());
202
203   // Loop over aliases
204   for (Module::alias_iterator AI = M->alias_begin(), AE = M->alias_end();
205        AI != AE; ++AI) {
206     if (AI->hasName())
207       symbols.push_back(AI->getName());
208   }
209 }
210
211 // Get just the externally visible defined symbols from the bitcode
212 bool llvm::GetBitcodeSymbols(const sys::Path& fName,
213                              LLVMContext& Context,
214                              std::vector<std::string>& symbols,
215                              std::string* ErrMsg) {
216   OwningPtr<MemoryBuffer> Buffer;
217   if (error_code ec = MemoryBuffer::getFileOrSTDIN(fName.c_str(), Buffer)) {
218     if (ErrMsg) *ErrMsg = "Could not open file '" + fName.str() + "'" + ": "
219                         + ec.message();
220     return true;
221   }
222
223   Module *M = ParseBitcodeFile(Buffer.get(), Context, ErrMsg);
224   if (!M)
225     return true;
226
227   // Get the symbols
228   getSymbols(M, symbols);
229
230   // Done with the module.
231   delete M;
232   return true;
233 }
234
235 Module*
236 llvm::GetBitcodeSymbols(const char *BufPtr, unsigned Length,
237                         const std::string& ModuleID,
238                         LLVMContext& Context,
239                         std::vector<std::string>& symbols,
240                         std::string* ErrMsg) {
241   // Get the module.
242   OwningPtr<MemoryBuffer> Buffer(
243     MemoryBuffer::getMemBufferCopy(StringRef(BufPtr, Length),ModuleID.c_str()));
244
245   Module *M = ParseBitcodeFile(Buffer.get(), Context, ErrMsg);
246   if (!M)
247     return 0;
248
249   // Get the symbols
250   getSymbols(M, symbols);
251
252   // Done with the module. Note that it's the caller's responsibility to delete
253   // the Module.
254   return M;
255 }