1 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements a family of utility functions which are useful for doing
11 // various things with files.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Support/FileUtilities.h"
16 #include "llvm/System/Path.h"
17 #include "llvm/System/MappedFile.h"
18 #include "llvm/ADT/StringExtras.h"
25 /// DiffFiles - Compare the two files specified, returning true if they are
26 /// different or if there is a file error. If you specify a string to fill in
27 /// for the error option, it will set the string to an error message if an error
28 /// occurs, allowing the caller to distinguish between a failed diff and a file
31 bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,
33 std::ios::openmode io_mode = std::ios::in | std::ios::binary;
34 std::ifstream FileAStream(FileA.c_str(), io_mode);
36 if (Error) *Error = "Couldn't open file '" + FileA + "'";
40 std::ifstream FileBStream(FileB.c_str(), io_mode);
42 if (Error) *Error = "Couldn't open file '" + FileB + "'";
46 // Compare the two files...
49 C1 = FileAStream.get();
50 C2 = FileBStream.get();
51 if (C1 != C2) return true;
57 /// MoveFileOverIfUpdated - If the file specified by New is different than Old,
58 /// or if Old does not exist, move the New file over the Old file. Otherwise,
59 /// remove the New file.
61 void llvm::MoveFileOverIfUpdated(const std::string &New,
62 const std::string &Old) {
63 if (DiffFiles(New, Old)) {
64 if (std::rename(New.c_str(), Old.c_str()))
65 std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n";
67 std::remove(New.c_str());
71 static bool isNumberChar(char C) {
73 case '0': case '1': case '2': case '3': case '4':
74 case '5': case '6': case '7': case '8': case '9':
75 case '.': case '+': case '-':
77 case 'E': return true;
78 default: return false;
82 static char *BackupNumber(char *Pos, char *FirstChar) {
83 // If we didn't stop in the middle of a number, don't backup.
84 if (!isNumberChar(*Pos)) return Pos;
86 // Otherwise, return to the start of the number.
87 while (Pos > FirstChar && isNumberChar(Pos[-1]))
92 /// CompareNumbers - compare two numbers, returning true if they are different.
93 static bool CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End,
94 double AbsTolerance, double RelTolerance,
95 std::string *ErrorMsg) {
96 char *F1NumEnd, *F2NumEnd;
97 double V1 = 0.0, V2 = 0.0;
98 // If we stop on numbers, compare their difference.
99 if (isNumberChar(*F1P) && isNumberChar(*F2P)) {
100 V1 = strtod(F1P, &F1NumEnd);
101 V2 = strtod(F2P, &F2NumEnd);
103 // Otherwise, the diff failed.
108 if (F1NumEnd == F1P || F2NumEnd == F2P) {
109 if (ErrorMsg) *ErrorMsg = "Comparison failed, not a numeric difference.";
113 // Check to see if these are inside the absolute tolerance
114 if (AbsTolerance < std::abs(V1-V2)) {
115 // Nope, check the relative tolerance...
118 Diff = std::abs(V1/V2 - 1.0);
120 Diff = std::abs(V2/V1 - 1.0);
122 Diff = 0; // Both zero.
123 if (Diff > RelTolerance) {
125 *ErrorMsg = "Compared: " + ftostr(V1) + " and " + ftostr(V2) +
126 ": diff = " + ftostr(Diff) + "\n";
127 *ErrorMsg += "Out of tolerance: rel/abs: " + ftostr(RelTolerance) +
128 "/" + ftostr(AbsTolerance);
134 // Otherwise, advance our read pointers to the end of the numbers.
135 F1P = F1NumEnd; F2P = F2NumEnd;
139 // PadFileIfNeeded - If the files are not identical, we will have to be doing
140 // numeric comparisons in here. There are bad cases involved where we (i.e.,
141 // strtod) might run off the beginning or end of the file if it starts or ends
142 // with a number. Because of this, if needed, we pad the file so that it starts
143 // and ends with a null character.
144 static void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) {
145 if (isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) {
146 unsigned FileLen = FileEnd-FileStart;
147 char *NewFile = new char[FileLen+2];
148 NewFile[0] = 0; // Add null padding
149 NewFile[FileLen+1] = 0; // Add null padding
150 memcpy(NewFile+1, FileStart, FileLen);
151 FP = NewFile+(FP-FileStart)+1;
152 FileStart = NewFile+1;
153 FileEnd = FileStart+FileLen;
157 /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the
158 /// files match, 1 if they are different, and 2 if there is a file error. This
159 /// function differs from DiffFiles in that you can specify an absolete and
160 /// relative FP error that is allowed to exist. If you specify a string to fill
161 /// in for the error option, it will set the string to an error message if an
162 /// error occurs, allowing the caller to distinguish between a failed diff and a
163 /// file system error.
165 int llvm::DiffFilesWithTolerance(const std::string &FileA,
166 const std::string &FileB,
167 double AbsTol, double RelTol,
168 std::string *Error) {
170 // Map in the files into memory.
171 sys::MappedFile F1((sys::Path(FileA)));
172 sys::MappedFile F2((sys::Path(FileB)));
176 // Okay, now that we opened the files, scan them for the first difference.
177 char *File1Start = F1.charBase();
178 char *File2Start = F2.charBase();
179 char *File1End = File1Start+F1.size();
180 char *File2End = File2Start+F2.size();
181 char *F1P = File1Start;
182 char *F2P = File2Start;
184 // Scan for the end of file or first difference.
185 while (F1P < File1End && F2P < File2End && *F1P == *F2P)
188 // Common case: identifical files.
189 if (F1P == File1End && F2P == File2End) return 0;
191 char *OrigFile1Start = File1Start;
192 char *OrigFile2Start = File2Start;
194 // If the files need padding, do so now.
195 PadFileIfNeeded(File1Start, File1End, F1P);
196 PadFileIfNeeded(File2Start, File2End, F2P);
198 bool CompareFailed = false;
200 // Scan for the end of file or next difference.
201 while (F1P < File1End && F2P < File2End && *F1P == *F2P)
204 if (F1P >= File1End || F2P >= File2End) break;
206 // Okay, we must have found a difference. Backup to the start of the
207 // current number each stream is at so that we can compare from the
209 F1P = BackupNumber(F1P, File1Start);
210 F2P = BackupNumber(F2P, File2Start);
212 // Now that we are at the start of the numbers, compare them, exiting if
214 if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) {
215 CompareFailed = true;
220 // Okay, we reached the end of file. If both files are at the end, we
222 bool F1AtEnd = F1P >= File1End;
223 bool F2AtEnd = F2P >= File2End;
224 if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) {
225 // Else, we might have run off the end due to a number: backup and retry.
226 if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;
227 if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;
228 F1P = BackupNumber(F1P, File1Start);
229 F2P = BackupNumber(F2P, File2Start);
231 // Now that we are at the start of the numbers, compare them, exiting if
233 if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error))
234 CompareFailed = true;
236 // If we found the end, we succeeded.
237 if (F1P < File1End || F2P < File2End)
238 CompareFailed = true;
241 if (OrigFile1Start != File1Start)
242 delete[] File1Start-1; // Back up past null byte
243 if (OrigFile2Start != File2Start)
244 delete[] File2Start-1; // Back up past null byte
245 return CompareFailed;
246 } catch (const std::string &Msg) {
247 if (Error) *Error = Msg;