Put all LLVM code into the llvm namespace, as per bug 109.
[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 /// FileOpenable - Returns true IFF Filename names an existing regular
56 /// file which we can successfully open.
57 ///
58 bool FileOpenable (const std::string &Filename) {
59   struct stat s;
60   if (stat (Filename.c_str (), &s) == -1)
61     return false; // Cannot stat file
62   if (!S_ISREG (s.st_mode))
63     return false; // File is not a regular file
64   std::ifstream FileStream (Filename.c_str ());
65   if (!FileStream)
66     return false; // File is not openable
67   return true;
68 }
69
70 /// DiffFiles - Compare the two files specified, returning true if they are
71 /// different or if there is a file error.  If you specify a string to fill in
72 /// for the error option, it will set the string to an error message if an error
73 /// occurs, allowing the caller to distinguish between a failed diff and a file
74 /// system error.
75 ///
76 bool DiffFiles(const std::string &FileA, const std::string &FileB,
77                std::string *Error) {
78   std::ifstream FileAStream(FileA.c_str());
79   if (!FileAStream) {
80     if (Error) *Error = "Couldn't open file '" + FileA + "'";
81     return true;
82   }
83
84   std::ifstream FileBStream(FileB.c_str());
85   if (!FileBStream) {
86     if (Error) *Error = "Couldn't open file '" + FileB + "'";
87     return true;
88   }
89
90   // Compare the two files...
91   int C1, C2;
92   do {
93     C1 = FileAStream.get();
94     C2 = FileBStream.get();
95     if (C1 != C2) return true;
96   } while (C1 != EOF);
97
98   return false;
99 }
100
101
102 /// MoveFileOverIfUpdated - If the file specified by New is different than Old,
103 /// or if Old does not exist, move the New file over the Old file.  Otherwise,
104 /// remove the New file.
105 ///
106 void MoveFileOverIfUpdated(const std::string &New, const std::string &Old) {
107   if (DiffFiles(New, Old)) {
108     if (std::rename(New.c_str(), Old.c_str()))
109       std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n";
110   } else {
111     std::remove(New.c_str());
112   }  
113 }
114
115 /// removeFile - Delete the specified file
116 ///
117 void removeFile(const std::string &Filename) {
118   std::remove(Filename.c_str());
119 }
120
121 /// getUniqueFilename - Return a filename with the specified prefix.  If the
122 /// file does not exist yet, return it, otherwise add a suffix to make it
123 /// unique.
124 ///
125 std::string getUniqueFilename(const std::string &FilenameBase) {
126   if (!std::ifstream(FilenameBase.c_str()))
127     return FilenameBase;    // Couldn't open the file? Use it!
128
129   // Create a pattern for mkstemp...
130   char *FNBuffer = new char[FilenameBase.size()+8];
131   strcpy(FNBuffer, FilenameBase.c_str());
132   strcpy(FNBuffer+FilenameBase.size(), "-XXXXXX");
133
134   // Agree on a temporary file name to use....
135   int TempFD;
136   if ((TempFD = mkstemp(FNBuffer)) == -1) {
137     std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current "
138               << " directory!\n";
139     exit(1);
140   }
141
142   // We don't need to hold the temp file descriptor... we will trust that no one
143   // will overwrite/delete the file while we are working on it...
144   close(TempFD);
145   std::string Result(FNBuffer);
146   delete[] FNBuffer;
147   return Result;
148 }
149
150 static bool AddPermissionsBits (const std::string &Filename, mode_t bits) {
151   // Get the umask value from the operating system.  We want to use it
152   // when changing the file's permissions. Since calling umask() sets
153   // the umask and returns its old value, we must call it a second
154   // time to reset it to the user's preference.
155   mode_t mask = umask (0777); // The arg. to umask is arbitrary...
156   umask (mask);
157
158   // Get the file's current mode.
159   struct stat st;
160   if ((stat (Filename.c_str(), &st)) == -1)
161     return false;
162
163   // Change the file to have whichever permissions bits from 'bits'
164   // that the umask would not disable.
165   if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
166     return false;
167
168   return true;
169 }
170
171 /// MakeFileExecutable - Make the file named Filename executable by
172 /// setting whichever execute permissions bits the process's current
173 /// umask would allow. Filename must name an existing file or
174 /// directory.  Returns true on success, false on error.
175 ///
176 bool MakeFileExecutable (const std::string &Filename) {
177   return AddPermissionsBits (Filename, 0111);
178 }
179
180 /// MakeFileReadable - Make the file named Filename readable by
181 /// setting whichever read permissions bits the process's current
182 /// umask would allow. Filename must name an existing file or
183 /// directory.  Returns true on success, false on error.
184 ///
185 bool MakeFileReadable (const std::string &Filename) {
186   return AddPermissionsBits (Filename, 0444);
187 }
188
189 } // End llvm namespace