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