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