llvm.org GIT mirror llvm / 4cbc548
Move this here from Bytecode/Archive.h git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@36865 91177308-0d34-0410-b5e6-96231b3b80d8 Chris Lattner 13 years ago
1 changed file(s) with 562 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 //===-- llvm/Bitcode/Archive.h - LLVM Bitcode Archive -----------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file was developed by Reid Spencer and is distributed under the
5 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This header file declares the Archive and ArchiveMember classes that provide
10 // manipulation of LLVM Archive files. The implementation is provided by the
11 // lib/Bitcode/Archive library. This library is used to read and write
12 // archive (*.a) files that contain LLVM bitcode files (or others).
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_BITECODE_ARCHIVE_H
17 #define LLVM_BITECODE_ARCHIVE_H
18
19 #include "llvm/ADT/ilist"
20 #include "llvm/System/Path.h"
21 #include "llvm/System/MappedFile.h"
22 #include
23 #include
24 #include
25
26 namespace llvm {
27
28 // Forward declare classes
29 class ModuleProvider; // From VMCore
30 class Module; // From VMCore
31 class Archive; // Declared below
32 class ArchiveMemberHeader; // Internal implementation class
33
34 /// This class is the main class manipulated by users of the Archive class. It
35 /// holds information about one member of the Archive. It is also the element
36 /// stored by the Archive's ilist, the Archive's main abstraction. Because of
37 /// the special requirements of archive files, users are not permitted to
38 /// construct ArchiveMember instances. You should obtain them from the methods
39 /// of the Archive class instead.
40 /// @brief This class represents a single archive member.
41 class ArchiveMember {
42 /// @name Types
43 /// @{
44 public:
45 /// These flags are used internally by the archive member to specify various
46 /// characteristics of the member. The various "is" methods below provide
47 /// access to the flags. The flags are not user settable.
48 enum Flags {
49 CompressedFlag = 1, ///< Member is a normal compressed file
50 SVR4SymbolTableFlag = 2, ///< Member is a SVR4 symbol table
51 BSD4SymbolTableFlag = 4, ///< Member is a BSD4 symbol table
52 LLVMSymbolTableFlag = 8, ///< Member is an LLVM symbol table
53 BytecodeFlag = 16, ///< Member is uncompressed bytecode
54 CompressedBytecodeFlag = 32, ///< Member is compressed bytecode
55 HasPathFlag = 64, ///< Member has a full or partial path
56 HasLongFilenameFlag = 128, ///< Member uses the long filename syntax
57 StringTableFlag = 256 ///< Member is an ar(1) format string table
58 };
59
60 /// @}
61 /// @name Accessors
62 /// @{
63 public:
64 /// @returns the parent Archive instance
65 /// @brief Get the archive associated with this member
66 Archive* getArchive() const { return parent; }
67
68 /// @returns the path to the Archive's file
69 /// @brief Get the path to the archive member
70 const sys::Path& getPath() const { return path; }
71
72 /// The "user" is the owner of the file per Unix security. This may not
73 /// have any applicability on non-Unix systems but is a required component
74 /// of the "ar" file format.
75 /// @brief Get the user associated with this archive member.
76 unsigned getUser() const { return info.getUser(); }
77
78 /// The "group" is the owning group of the file per Unix security. This
79 /// may not have any applicability on non-Unix systems but is a required
80 /// component of the "ar" file format.
81 /// @brief Get the group associated with this archive member.
82 unsigned getGroup() const { return info.getGroup(); }
83
84 /// The "mode" specifies the access permissions for the file per Unix
85 /// security. This may not have any applicabiity on non-Unix systems but is
86 /// a required component of the "ar" file format.
87 /// @brief Get the permission mode associated with this archive member.
88 unsigned getMode() const { return info.getMode(); }
89
90 /// This method returns the time at which the archive member was last
91 /// modified when it was not in the archive.
92 /// @brief Get the time of last modification of the archive member.
93 sys::TimeValue getModTime() const { return info.getTimestamp(); }
94
95 /// @returns the size of the archive member in bytes.
96 /// @brief Get the size of the archive member.
97 uint64_t getSize() const { return info.getSize(); }
98
99 /// This method returns the total size of the archive member as it
100 /// appears on disk. This includes the file content, the header, the
101 /// long file name if any, and the padding.
102 /// @brief Get total on-disk member size.
103 unsigned getMemberSize() const;
104
105 /// This method will return a pointer to the in-memory content of the
106 /// archive member, if it is available. If the data has not been loaded
107 /// into memory, the return value will be null.
108 /// @returns a pointer to the member's data.
109 /// @brief Get the data content of the archive member
110 const void* getData() const { return data; }
111
112 /// This method determines if the member is a regular compressed file. Note
113 /// that compressed bytecode files will yield "false" for this method.
114 /// @see isCompressedBytecode()
115 /// @returns true iff the archive member is a compressed regular file.
116 /// @brief Determine if the member is a compressed regular file.
117 bool isCompressed() const { return flags&CompressedFlag; }
118
119 /// @returns true iff the member is a SVR4 (non-LLVM) symbol table
120 /// @brief Determine if this member is a SVR4 symbol table.
121 bool isSVR4SymbolTable() const { return flags&SVR4SymbolTableFlag; }
122
123 /// @returns true iff the member is a BSD4.4 (non-LLVM) symbol table
124 /// @brief Determine if this member is a BSD4.4 symbol table.
125 bool isBSD4SymbolTable() const { return flags&BSD4SymbolTableFlag; }
126
127 /// @returns true iff the archive member is the LLVM symbol table
128 /// @brief Determine if this member is the LLVM symbol table.
129 bool isLLVMSymbolTable() const { return flags&LLVMSymbolTableFlag; }
130
131 /// @returns true iff the archive member is the ar(1) string table
132 /// @brief Determine if this member is the ar(1) string table.
133 bool isStringTable() const { return flags&StringTableFlag; }
134
135 /// @returns true iff the archive member is an uncompressed bytecode file.
136 /// @brief Determine if this member is a bytecode file.
137 bool isBytecode() const { return flags&BytecodeFlag; }
138
139 /// @returns true iff the archive member is a compressed bytecode file.
140 /// @brief Determine if the member is a compressed bytecode file.
141 bool isCompressedBytecode() const { return flags&CompressedBytecodeFlag;}
142
143 /// @returns true iff the file name contains a path (directory) component.
144 /// @brief Determine if the member has a path
145 bool hasPath() const { return flags&HasPathFlag; }
146
147 /// Long filenames are an artifact of the ar(1) file format which allows
148 /// up to sixteen characters in its header and doesn't allow a path
149 /// separator character (/). To avoid this, a "long format" member name is
150 /// allowed that doesn't have this restriction. This method determines if
151 /// that "long format" is used for this member.
152 /// @returns true iff the file name uses the long form
153 /// @brief Determin if the member has a long file name
154 bool hasLongFilename() const { return flags&HasLongFilenameFlag; }
155
156 /// This method returns the status info (like Unix stat(2)) for the archive
157 /// member. The status info provides the file's size, permissions, and
158 /// modification time. The contents of the Path::StatusInfo structure, other
159 /// than the size and modification time, may not have utility on non-Unix
160 /// systems.
161 /// @returns the status info for the archive member
162 /// @brief Obtain the status info for the archive member
163 const sys::FileStatus &getFileStatus() const { return info; }
164
165 /// This method causes the archive member to be replaced with the contents
166 /// of the file specified by \p File. The contents of \p this will be
167 /// updated to reflect the new data from \p File. The \p File must exist and
168 /// be readable on entry to this method.
169 /// @returns true if an error occurred, false otherwise
170 /// @brief Replace contents of archive member with a new file.
171 bool replaceWith(const sys::Path &aFile, std::string* ErrMsg);
172
173 /// @}
174 /// @name ilist methods - do not use
175 /// @{
176 public:
177 const ArchiveMember *getNext() const { return next; }
178 const ArchiveMember *getPrev() const { return prev; }
179 ArchiveMember *getNext() { return next; }
180 ArchiveMember *getPrev() { return prev; }
181 void setPrev(ArchiveMember* p) { prev = p; }
182 void setNext(ArchiveMember* n) { next = n; }
183
184 /// @}
185 /// @name Data
186 /// @{
187 private:
188 ArchiveMember* next; ///< Pointer to next archive member
189 ArchiveMember* prev; ///< Pointer to previous archive member
190 Archive* parent; ///< Pointer to parent archive
191 sys::PathWithStatus path; ///< Path of file containing the member
192 sys::FileStatus info; ///< Status info (size,mode,date)
193 unsigned flags; ///< Flags about the archive member
194 const void* data; ///< Data for the member
195
196 /// @}
197 /// @name Constructors
198 /// @{
199 public:
200 /// The default constructor is only used by the Archive's iplist when it
201 /// constructs the list's sentry node.
202 ArchiveMember();
203
204 private:
205 /// Used internally by the Archive class to construct an ArchiveMember.
206 /// The contents of the ArchiveMember are filled out by the Archive class.
207 ArchiveMember(Archive *PAR);
208
209 // So Archive can construct an ArchiveMember
210 friend class llvm::Archive;
211 /// @}
212 };
213
214 /// This class defines the interface to LLVM Archive files. The Archive class
215 /// presents the archive file as an ilist of ArchiveMember objects. The members
216 /// can be rearranged in any fashion either by directly editing the ilist or by
217 /// using editing methods on the Archive class (recommended). The Archive
218 /// class also provides several ways of accessing the archive file for various
219 /// purposes such as editing and linking. Full symbol table support is provided
220 /// for loading only those files that resolve symbols. Note that read
221 /// performance of this library is _crucial_ for performance of JIT type
222 /// applications and the linkers. Consequently, the implementation of the class
223 /// is optimized for reading.
224 class Archive {
225
226 /// @name Types
227 /// @{
228 public:
229 /// This is the ilist type over which users may iterate to examine
230 /// the contents of the archive
231 /// @brief The ilist type of ArchiveMembers that Archive contains.
232 typedef iplist MembersList;
233
234 /// @brief Forward mutable iterator over ArchiveMember
235 typedef MembersList::iterator iterator;
236
237 /// @brief Forward immutable iterator over ArchiveMember
238 typedef MembersList::const_iterator const_iterator;
239
240 /// @brief Reverse mutable iterator over ArchiveMember
241 typedef std::reverse_iterator reverse_iterator;
242
243 /// @brief Reverse immutable iterator over ArchiveMember
244 typedef std::reverse_iterator const_reverse_iterator;
245
246 /// @brief The in-memory version of the symbol table
247 typedef std::map SymTabType;
248
249 /// @}
250 /// @name ilist accessor methods
251 /// @{
252 public:
253 inline iterator begin() { return members.begin(); }
254 inline const_iterator begin() const { return members.begin(); }
255 inline iterator end () { return members.end(); }
256 inline const_iterator end () const { return members.end(); }
257
258 inline reverse_iterator rbegin() { return members.rbegin(); }
259 inline const_reverse_iterator rbegin() const { return members.rbegin(); }
260 inline reverse_iterator rend () { return members.rend(); }
261 inline const_reverse_iterator rend () const { return members.rend(); }
262
263 inline unsigned size() const { return members.size(); }
264 inline bool empty() const { return members.empty(); }
265 inline const ArchiveMember& front() const { return members.front(); }
266 inline ArchiveMember& front() { return members.front(); }
267 inline const ArchiveMember& back() const { return members.back(); }
268 inline ArchiveMember& back() { return members.back(); }
269
270 /// @}
271 /// @name ilist mutator methods
272 /// @{
273 public:
274 /// This method splices a \p src member from an archive (possibly \p this),
275 /// to a position just before the member given by \p dest in \p this. When
276 /// the archive is written, \p src will be written in its new location.
277 /// @brief Move a member to a new location
278 inline void splice(iterator dest, Archive& arch, iterator src)
279 { return members.splice(dest,arch.members,src); }
280
281 /// This method erases a \p target member from the archive. When the
282 /// archive is written, it will no longer contain \p target. The associated
283 /// ArchiveMember is deleted.
284 /// @brief Erase a member.
285 inline iterator erase(iterator target) { return members.erase(target); }
286
287 /// @}
288 /// @name Constructors
289 /// @{
290 public:
291 /// Create an empty archive file and associate it with the \p Filename. This
292 /// method does not actually create the archive disk file. It creates an
293 /// empty Archive object. If the writeToDisk method is called, the archive
294 /// file \p Filename will be created at that point, with whatever content
295 /// the returned Archive object has at that time.
296 /// @returns An Archive* that represents the new archive file.
297 /// @brief Create an empty Archive.
298 static Archive* CreateEmpty(
299 const sys::Path& Filename ///< Name of the archive to (eventually) create.
300 );
301
302 /// Open an existing archive and load its contents in preparation for
303 /// editing. After this call, the member ilist is completely populated based
304 /// on the contents of the archive file. You should use this form of open if
305 /// you intend to modify the archive or traverse its contents (e.g. for
306 /// printing).
307 /// @brief Open and load an archive file
308 static Archive* OpenAndLoad(
309 const sys::Path& filePath, ///< The file path to open and load
310 std::string* ErrorMessage ///< An optional error string
311 );
312
313 /// This method opens an existing archive file from \p Filename and reads in
314 /// its symbol table without reading in any of the archive's members. This
315 /// reduces both I/O and cpu time in opening the archive if it is to be used
316 /// solely for symbol lookup (e.g. during linking). The \p Filename must
317 /// exist and be an archive file or an exception will be thrown. This form
318 /// of opening the archive is intended for read-only operations that need to
319 /// locate members via the symbol table for link editing. Since the archve
320 /// members are not read by this method, the archive will appear empty upon
321 /// return. If editing operations are performed on the archive, they will
322 /// completely replace the contents of the archive! It is recommended that
323 /// if this form of opening the archive is used that only the symbol table
324 /// lookup methods (getSymbolTable, findModuleDefiningSymbol, and
325 /// findModulesDefiningSymbols) be used.
326 /// @throws std::string if an error occurs opening the file
327 /// @returns an Archive* that represents the archive file.
328 /// @brief Open an existing archive and load its symbols.
329 static Archive* OpenAndLoadSymbols(
330 const sys::Path& Filename, ///< Name of the archive file to open
331 std::string* ErrorMessage=0 ///< An optional error string
332 );
333
334 /// This destructor cleans up the Archive object, releases all memory, and
335 /// closes files. It does nothing with the archive file on disk. If you
336 /// haven't used the writeToDisk method by the time the destructor is
337 /// called, all changes to the archive will be lost.
338 /// @throws std::string if an error occurs
339 /// @brief Destruct in-memory archive
340 ~Archive();
341
342 /// @}
343 /// @name Accessors
344 /// @{
345 public:
346 /// @returns the path to the archive file.
347 /// @brief Get the archive path.
348 const sys::Path& getPath() { return archPath; }
349
350 /// This method is provided so that editing methods can be invoked directly
351 /// on the Archive's iplist of ArchiveMember. However, it is recommended
352 /// that the usual STL style iterator interface be used instead.
353 /// @returns the iplist of ArchiveMember
354 /// @brief Get the iplist of the members
355 MembersList& getMembers() { return members; }
356
357 /// This method allows direct query of the Archive's symbol table. The
358 /// symbol table is a std::map of std::string (the symbol) to unsigned (the
359 /// file offset). Note that for efficiency reasons, the offset stored in
360 /// the symbol table is not the actual offset. It is the offset from the
361 /// beginning of the first "real" file member (after the symbol table). Use
362 /// the getFirstFileOffset() to obtain that offset and add this value to the
363 /// offset in the symbol table to obtain the real file offset. Note that
364 /// there is purposefully no interface provided by Archive to look up
365 /// members by their offset. Use the findModulesDefiningSymbols and
366 /// findModuleDefiningSymbol methods instead.
367 /// @returns the Archive's symbol table.
368 /// @brief Get the archive's symbol table
369 const SymTabType& getSymbolTable() { return symTab; }
370
371 /// This method returns the offset in the archive file to the first "real"
372 /// file member. Archive files, on disk, have a signature and might have a
373 /// symbol table that precedes the first actual file member. This method
374 /// allows you to determine what the size of those fields are.
375 /// @returns the offset to the first "real" file member in the archive.
376 /// @brief Get the offset to the first "real" file member in the archive.
377 unsigned getFirstFileOffset() { return firstFileOffset; }
378
379 /// This method will scan the archive for bytecode modules, interpret them
380 /// and return a vector of the instantiated modules in \p Modules. If an
381 /// error occurs, this method will return true. If \p ErrMessage is not null
382 /// and an error occurs, \p *ErrMessage will be set to a string explaining
383 /// the error that occurred.
384 /// @returns true if an error occurred
385 /// @brief Instantiate all the bytecode modules located in the archive
386 bool getAllModules(std::vector& Modules, std::string* ErrMessage);
387
388 /// This accessor looks up the \p symbol in the archive's symbol table and
389 /// returns the associated module that defines that symbol. This method can
390 /// be called as many times as necessary. This is handy for linking the
391 /// archive into another module based on unresolved symbols. Note that the
392 /// ModuleProvider returned by this accessor should not be deleted by the
393 /// caller. It is managed internally by the Archive class. It is possible
394 /// that multiple calls to this accessor will return the same ModuleProvider
395 /// instance because the associated module defines multiple symbols.
396 /// @returns The ModuleProvider* found or null if the archive does not
397 /// contain a module that defines the \p symbol.
398 /// @brief Look up a module by symbol name.
399 ModuleProvider* findModuleDefiningSymbol(
400 const std::string& symbol, ///< Symbol to be sought
401 std::string* ErrMessage ///< Error message storage, if non-zero
402 );
403
404 /// This method is similar to findModuleDefiningSymbol but allows lookup of
405 /// more than one symbol at a time. If \p symbols contains a list of
406 /// undefined symbols in some module, then calling this method is like
407 /// making one complete pass through the archive to resolve symbols but is
408 /// more efficient than looking at the individual members. Note that on
409 /// exit, the symbols resolved by this method will be removed from \p
410 /// symbols to ensure they are not re-searched on a subsequent call. If
411 /// you need to retain the list of symbols, make a copy.
412 /// @brief Look up multiple symbols in the archive.
413 bool findModulesDefiningSymbols(
414 std::set& symbols, ///< Symbols to be sought
415 std::set& modules, ///< The modules matching \p symbols
416 std::string* ErrMessage ///< Error msg storage, if non-zero
417 );
418
419 /// This method determines whether the archive is a properly formed llvm
420 /// bytecode archive. It first makes sure the symbol table has been loaded
421 /// and has a non-zero size. If it does, then it is an archive. If not,
422 /// then it tries to load all the bytecode modules of the archive. Finally,
423 /// it returns whether it was successfull.
424 /// @returns true if the archive is a proper llvm bytecode archive
425 /// @brief Determine whether the archive is a proper llvm bytecode archive.
426 bool isBytecodeArchive();
427
428 /// @}
429 /// @name Mutators
430 /// @{
431 public:
432 /// This method is the only way to get the archive written to disk. It
433 /// creates or overwrites the file specified when \p this was created
434 /// or opened. The arguments provide options for writing the archive. If
435 /// \p CreateSymbolTable is true, the archive is scanned for bytecode files
436 /// and a symbol table of the externally visible function and global
437 /// variable names is created. If \p TruncateNames is true, the names of the
438 /// archive members will have their path component stripped and the file
439 /// name will be truncated at 15 characters. If \p Compress is specified,
440 /// all archive members will be compressed before being written. If
441 /// \p PrintSymTab is true, the symbol table will be printed to std::cout.
442 /// @returns true if an error occurred, \p error set to error message
443 /// @returns false if the writing succeeded.
444 /// @brief Write (possibly modified) archive contents to disk
445 bool writeToDisk(
446 bool CreateSymbolTable=false, ///< Create Symbol table
447 bool TruncateNames=false, ///< Truncate the filename to 15 chars
448 bool Compress=false, ///< Compress files
449 std::string* ErrMessage=0 ///< If non-null, where error msg is set
450 );
451
452 /// This method adds a new file to the archive. The \p filename is examined
453 /// to determine just enough information to create an ArchiveMember object
454 /// which is then inserted into the Archive object's ilist at the location
455 /// given by \p where.
456 /// @returns true if an error occured, false otherwise
457 /// @brief Add a file to the archive.
458 bool addFileBefore(
459 const sys::Path& filename, ///< The file to be added
460 iterator where, ///< Insertion point
461 std::string* ErrMsg ///< Optional error message location
462 );
463
464 /// @}
465 /// @name Implementation
466 /// @{
467 protected:
468 /// @brief Construct an Archive for \p filename and optionally map it
469 /// into memory.
470 Archive(const sys::Path& filename);
471
472 /// @param error Set to address of a std::string to get error messages
473 /// @returns false on error
474 /// @brief Parse the symbol table at \p data.
475 bool parseSymbolTable(const void* data,unsigned len,std::string* error);
476
477 /// @returns A fully populated ArchiveMember or 0 if an error occurred.
478 /// @brief Parse the header of a member starting at \p At
479 ArchiveMember* parseMemberHeader(
480 const char*&At, ///< The pointer to the location we're parsing
481 const char*End, ///< The pointer to the end of the archive
482 std::string* error ///< Optional error message catcher
483 );
484
485 /// @param error Set to address of a std::string to get error messages
486 /// @returns false on error
487 /// @brief Check that the archive signature is correct
488 bool checkSignature(std::string* ErrMessage);
489
490 /// @param error Set to address of a std::string to get error messages
491 /// @returns false on error
492 /// @brief Load the entire archive.
493 bool loadArchive(std::string* ErrMessage);
494
495 /// @param error Set to address of a std::string to get error messages
496 /// @returns false on error
497 /// @brief Load just the symbol table.
498 bool loadSymbolTable(std::string* ErrMessage);
499
500 /// @brief Write the symbol table to an ofstream.
501 void writeSymbolTable(std::ofstream& ARFile);
502
503 /// Writes one ArchiveMember to an ofstream. If an error occurs, returns
504 /// false, otherwise true. If an error occurs and error is non-null then
505 /// it will be set to an error message.
506 /// @returns false Writing member succeeded
507 /// @returns true Writing member failed, \p error set to error message
508 bool writeMember(
509 const ArchiveMember& member, ///< The member to be written
510 std::ofstream& ARFile, ///< The file to write member onto
511 bool CreateSymbolTable, ///< Should symbol table be created?
512 bool TruncateNames, ///< Should names be truncated to 11 chars?
513 bool ShouldCompress, ///< Should the member be compressed?
514 std::string* ErrMessage ///< If non-null, place were error msg is set
515 );
516
517 /// @brief Fill in an ArchiveMemberHeader from ArchiveMember.
518 bool fillHeader(const ArchiveMember&mbr,
519 ArchiveMemberHeader& hdr,int sz, bool TruncateNames) const;
520
521 /// @brief Maps archive into memory
522 bool mapToMemory(std::string* ErrMsg);
523
524 /// @brief Frees all the members and unmaps the archive file.
525 void cleanUpMemory();
526
527 /// This type is used to keep track of bytecode modules loaded from the
528 /// symbol table. It maps the file offset to a pair that consists of the
529 /// associated ArchiveMember and the ModuleProvider.
530 /// @brief Module mapping type
531 typedef std::map >
532 ModuleMap;
533
534
535 /// @}
536 /// @name Data
537 /// @{
538 protected:
539 sys::Path archPath; ///< Path to the archive file we read/write
540 MembersList members; ///< The ilist of ArchiveMember
541 sys::MappedFile* mapfile; ///< Raw Archive contents mapped into memory
542 const char* base; ///< Base of the memory mapped file data
543 SymTabType symTab; ///< The symbol table
544 std::string strtab; ///< The string table for long file names
545 unsigned symTabSize; ///< Size in bytes of symbol table
546 unsigned firstFileOffset; ///< Offset to first normal file.
547 ModuleMap modules; ///< The modules loaded via symbol lookup.
548 ArchiveMember* foreignST; ///< This holds the foreign symbol table.
549 /// @}
550 /// @name Hidden
551 /// @{
552 private:
553 Archive(); ///< Do not implement
554 Archive(const Archive&); ///< Do not implement
555 Archive& operator=(const Archive&); ///< Do not implement
556 /// @}
557 };
558
559 } // End llvm namespace
560
561 #endif