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