Add ability to query if a file is a legitimate ELF shared object.
[oota-llvm.git] / lib / Support / FileUtilities.cpp
1 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a family of utility functions which are useful for doing
11 // various things with files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Support/FileUtilities.h"
16 #include "Config/unistd.h"
17 #include "Config/sys/stat.h"
18 #include "Config/sys/types.h"
19 #include <fstream>
20 #include <iostream>
21 #include <cstdio>
22
23 namespace llvm
24 {
25
26 /// CheckMagic - Returns true IFF the file named FN begins with Magic. FN must
27 /// name a readable file.
28 ///
29 bool CheckMagic (const std::string &FN, const std::string &Magic) {
30   char buf[1 + Magic.size ()];
31   std::ifstream f (FN.c_str ());
32   f.read (buf, Magic.size ());
33   buf[Magic.size ()] = '\0';
34   return Magic == buf;
35 }
36
37 /// IsArchive - Returns true IFF the file named FN appears to be a "ar" library
38 /// archive. The file named FN must exist.
39 ///
40 bool IsArchive(const std::string &FN) {
41   // Inspect the beginning of the file to see if it contains the "ar"
42   // library archive format magic string.
43   return CheckMagic (FN, "!<arch>\012");
44 }
45
46 /// IsBytecode - Returns true IFF the file named FN appears to be an LLVM
47 /// bytecode file. The file named FN must exist.
48 ///
49 bool IsBytecode(const std::string &FN) {
50   // Inspect the beginning of the file to see if it contains the LLVM
51   // bytecode format magic string.
52   return CheckMagic (FN, "llvm");
53 }
54
55 /// IsSharedObject - Returns trus IFF the file named FN appears to be a shared
56 /// object with an ELF header. The file named FN must exist.
57 ///
58 bool IsSharedObject(const std::string &FN) {
59   // Inspect the beginning of the file to see if it contains the LLVM
60   // bytecode format magic string.
61   static const char elfMagic[] = { 0x7f, 'E', 'L', 'F', '\0' };
62   return CheckMagic(FN, elfMagic);
63 }
64
65 /// FileOpenable - Returns true IFF Filename names an existing regular
66 /// file which we can successfully open.
67 ///
68 bool FileOpenable (const std::string &Filename) {
69   struct stat s;
70   if (stat (Filename.c_str (), &s) == -1)
71     return false; // Cannot stat file
72   if (!S_ISREG (s.st_mode))
73     return false; // File is not a regular file
74   std::ifstream FileStream (Filename.c_str ());
75   if (!FileStream)
76     return false; // File is not openable
77   return true;
78 }
79
80 /// DiffFiles - Compare the two files specified, returning true if they are
81 /// different or if there is a file error.  If you specify a string to fill in
82 /// for the error option, it will set the string to an error message if an error
83 /// occurs, allowing the caller to distinguish between a failed diff and a file
84 /// system error.
85 ///
86 bool DiffFiles(const std::string &FileA, const std::string &FileB,
87                std::string *Error) {
88   std::ifstream FileAStream(FileA.c_str());
89   if (!FileAStream) {
90     if (Error) *Error = "Couldn't open file '" + FileA + "'";
91     return true;
92   }
93
94   std::ifstream FileBStream(FileB.c_str());
95   if (!FileBStream) {
96     if (Error) *Error = "Couldn't open file '" + FileB + "'";
97     return true;
98   }
99
100   // Compare the two files...
101   int C1, C2;
102   do {
103     C1 = FileAStream.get();
104     C2 = FileBStream.get();
105     if (C1 != C2) return true;
106   } while (C1 != EOF);
107
108   return false;
109 }
110
111
112 /// MoveFileOverIfUpdated - If the file specified by New is different than Old,
113 /// or if Old does not exist, move the New file over the Old file.  Otherwise,
114 /// remove the New file.
115 ///
116 void MoveFileOverIfUpdated(const std::string &New, const std::string &Old) {
117   if (DiffFiles(New, Old)) {
118     if (std::rename(New.c_str(), Old.c_str()))
119       std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n";
120   } else {
121     std::remove(New.c_str());
122   }  
123 }
124
125 /// removeFile - Delete the specified file
126 ///
127 void removeFile(const std::string &Filename) {
128   std::remove(Filename.c_str());
129 }
130
131 /// getUniqueFilename - Return a filename with the specified prefix.  If the
132 /// file does not exist yet, return it, otherwise add a suffix to make it
133 /// unique.
134 ///
135 std::string getUniqueFilename(const std::string &FilenameBase) {
136   if (!std::ifstream(FilenameBase.c_str()))
137     return FilenameBase;    // Couldn't open the file? Use it!
138
139   // Create a pattern for mkstemp...
140   char *FNBuffer = new char[FilenameBase.size()+8];
141   strcpy(FNBuffer, FilenameBase.c_str());
142   strcpy(FNBuffer+FilenameBase.size(), "-XXXXXX");
143
144   // Agree on a temporary file name to use....
145   int TempFD;
146   if ((TempFD = mkstemp(FNBuffer)) == -1) {
147     std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current "
148               << " directory!\n";
149     exit(1);
150   }
151
152   // We don't need to hold the temp file descriptor... we will trust that no one
153   // will overwrite/delete the file while we are working on it...
154   close(TempFD);
155   std::string Result(FNBuffer);
156   delete[] FNBuffer;
157   return Result;
158 }
159
160 static bool AddPermissionsBits (const std::string &Filename, mode_t bits) {
161   // Get the umask value from the operating system.  We want to use it
162   // when changing the file's permissions. Since calling umask() sets
163   // the umask and returns its old value, we must call it a second
164   // time to reset it to the user's preference.
165   mode_t mask = umask (0777); // The arg. to umask is arbitrary...
166   umask (mask);
167
168   // Get the file's current mode.
169   struct stat st;
170   if ((stat (Filename.c_str(), &st)) == -1)
171     return false;
172
173   // Change the file to have whichever permissions bits from 'bits'
174   // that the umask would not disable.
175   if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
176     return false;
177
178   return true;
179 }
180
181 /// MakeFileExecutable - Make the file named Filename executable by
182 /// setting whichever execute permissions bits the process's current
183 /// umask would allow. Filename must name an existing file or
184 /// directory.  Returns true on success, false on error.
185 ///
186 bool MakeFileExecutable (const std::string &Filename) {
187   return AddPermissionsBits (Filename, 0111);
188 }
189
190 /// MakeFileReadable - Make the file named Filename readable by
191 /// setting whichever read permissions bits the process's current
192 /// umask would allow. Filename must name an existing file or
193 /// directory.  Returns true on success, false on error.
194 ///
195 bool MakeFileReadable (const std::string &Filename) {
196   return AddPermissionsBits (Filename, 0444);
197 }
198
199 } // End llvm namespace