1 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "llvm/Support/FileUtilities.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <cctype>
21 #include <cstdlib>
22 #include <cstring>
23 #include <system_error>
24 using namespace llvm;
25 
isSignedChar(char C)26 static bool isSignedChar(char C) {
27   return (C == '+' || C == '-');
28 }
29 
isExponentChar(char C)30 static bool isExponentChar(char C) {
31   switch (C) {
32   case 'D':  // Strange exponential notation.
33   case 'd':  // Strange exponential notation.
34   case 'e':
35   case 'E': return true;
36   default: return false;
37   }
38 }
39 
isNumberChar(char C)40 static bool isNumberChar(char C) {
41   switch (C) {
42   case '0': case '1': case '2': case '3': case '4':
43   case '5': case '6': case '7': case '8': case '9':
44   case '.': return true;
45   default: return isSignedChar(C) || isExponentChar(C);
46   }
47 }
48 
BackupNumber(const char * Pos,const char * FirstChar)49 static const char *BackupNumber(const char *Pos, const char *FirstChar) {
50   // If we didn't stop in the middle of a number, don't backup.
51   if (!isNumberChar(*Pos)) return Pos;
52 
53   // Otherwise, return to the start of the number.
54   bool HasPeriod = false;
55   while (Pos > FirstChar && isNumberChar(Pos[-1])) {
56     // Backup over at most one period.
57     if (Pos[-1] == '.') {
58       if (HasPeriod)
59         break;
60       HasPeriod = true;
61     }
62 
63     --Pos;
64     if (Pos > FirstChar && isSignedChar(Pos[0]) && !isExponentChar(Pos[-1]))
65       break;
66   }
67   return Pos;
68 }
69 
70 /// EndOfNumber - Return the first character that is not part of the specified
71 /// number.  This assumes that the buffer is null terminated, so it won't fall
72 /// off the end.
EndOfNumber(const char * Pos)73 static const char *EndOfNumber(const char *Pos) {
74   while (isNumberChar(*Pos))
75     ++Pos;
76   return Pos;
77 }
78 
79 /// CompareNumbers - compare two numbers, returning true if they are different.
CompareNumbers(const char * & F1P,const char * & F2P,const char * F1End,const char * F2End,double AbsTolerance,double RelTolerance,std::string * ErrorMsg)80 static bool CompareNumbers(const char *&F1P, const char *&F2P,
81                            const char *F1End, const char *F2End,
82                            double AbsTolerance, double RelTolerance,
83                            std::string *ErrorMsg) {
84   const char *F1NumEnd, *F2NumEnd;
85   double V1 = 0.0, V2 = 0.0;
86 
87   // If one of the positions is at a space and the other isn't, chomp up 'til
88   // the end of the space.
89   while (isspace(static_cast<unsigned char>(*F1P)) && F1P != F1End)
90     ++F1P;
91   while (isspace(static_cast<unsigned char>(*F2P)) && F2P != F2End)
92     ++F2P;
93 
94   // If we stop on numbers, compare their difference.
95   if (!isNumberChar(*F1P) || !isNumberChar(*F2P)) {
96     // The diff failed.
97     F1NumEnd = F1P;
98     F2NumEnd = F2P;
99   } else {
100     // Note that some ugliness is built into this to permit support for numbers
101     // that use "D" or "d" as their exponential marker, e.g. "1.234D45".  This
102     // occurs in 200.sixtrack in spec2k.
103     V1 = strtod(F1P, const_cast<char**>(&F1NumEnd));
104     V2 = strtod(F2P, const_cast<char**>(&F2NumEnd));
105 
106     if (*F1NumEnd == 'D' || *F1NumEnd == 'd') {
107       // Copy string into tmp buffer to replace the 'D' with an 'e'.
108       SmallString<200> StrTmp(F1P, EndOfNumber(F1NumEnd)+1);
109       // Strange exponential notation!
110       StrTmp[static_cast<unsigned>(F1NumEnd-F1P)] = 'e';
111 
112       V1 = strtod(&StrTmp[0], const_cast<char**>(&F1NumEnd));
113       F1NumEnd = F1P + (F1NumEnd-&StrTmp[0]);
114     }
115 
116     if (*F2NumEnd == 'D' || *F2NumEnd == 'd') {
117       // Copy string into tmp buffer to replace the 'D' with an 'e'.
118       SmallString<200> StrTmp(F2P, EndOfNumber(F2NumEnd)+1);
119       // Strange exponential notation!
120       StrTmp[static_cast<unsigned>(F2NumEnd-F2P)] = 'e';
121 
122       V2 = strtod(&StrTmp[0], const_cast<char**>(&F2NumEnd));
123       F2NumEnd = F2P + (F2NumEnd-&StrTmp[0]);
124     }
125   }
126 
127   if (F1NumEnd == F1P || F2NumEnd == F2P) {
128     if (ErrorMsg) {
129       *ErrorMsg = "FP Comparison failed, not a numeric difference between '";
130       *ErrorMsg += F1P[0];
131       *ErrorMsg += "' and '";
132       *ErrorMsg += F2P[0];
133       *ErrorMsg += "'";
134     }
135     return true;
136   }
137 
138   // Check to see if these are inside the absolute tolerance
139   if (AbsTolerance < std::abs(V1-V2)) {
140     // Nope, check the relative tolerance...
141     double Diff;
142     if (V2)
143       Diff = std::abs(V1/V2 - 1.0);
144     else if (V1)
145       Diff = std::abs(V2/V1 - 1.0);
146     else
147       Diff = 0;  // Both zero.
148     if (Diff > RelTolerance) {
149       if (ErrorMsg) {
150         raw_string_ostream(*ErrorMsg)
151           << "Compared: " << V1 << " and " << V2 << '\n'
152           << "abs. diff = " << std::abs(V1-V2) << " rel.diff = " << Diff << '\n'
153           << "Out of tolerance: rel/abs: " << RelTolerance << '/'
154           << AbsTolerance;
155       }
156       return true;
157     }
158   }
159 
160   // Otherwise, advance our read pointers to the end of the numbers.
161   F1P = F1NumEnd;  F2P = F2NumEnd;
162   return false;
163 }
164 
165 /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the
166 /// files match, 1 if they are different, and 2 if there is a file error.  This
167 /// function differs from DiffFiles in that you can specify an absolete and
168 /// relative FP error that is allowed to exist.  If you specify a string to fill
169 /// in for the error option, it will set the string to an error message if an
170 /// error occurs, allowing the caller to distinguish between a failed diff and a
171 /// file system error.
172 ///
DiffFilesWithTolerance(StringRef NameA,StringRef NameB,double AbsTol,double RelTol,std::string * Error)173 int llvm::DiffFilesWithTolerance(StringRef NameA,
174                                  StringRef NameB,
175                                  double AbsTol, double RelTol,
176                                  std::string *Error) {
177   // Now its safe to mmap the files into memory because both files
178   // have a non-zero size.
179   ErrorOr<std::unique_ptr<MemoryBuffer>> F1OrErr = MemoryBuffer::getFile(NameA);
180   if (std::error_code EC = F1OrErr.getError()) {
181     if (Error)
182       *Error = EC.message();
183     return 2;
184   }
185   MemoryBuffer &F1 = *F1OrErr.get();
186 
187   ErrorOr<std::unique_ptr<MemoryBuffer>> F2OrErr = MemoryBuffer::getFile(NameB);
188   if (std::error_code EC = F2OrErr.getError()) {
189     if (Error)
190       *Error = EC.message();
191     return 2;
192   }
193   MemoryBuffer &F2 = *F2OrErr.get();
194 
195   // Okay, now that we opened the files, scan them for the first difference.
196   const char *File1Start = F1.getBufferStart();
197   const char *File2Start = F2.getBufferStart();
198   const char *File1End = F1.getBufferEnd();
199   const char *File2End = F2.getBufferEnd();
200   const char *F1P = File1Start;
201   const char *F2P = File2Start;
202   uint64_t A_size = F1.getBufferSize();
203   uint64_t B_size = F2.getBufferSize();
204 
205   // Are the buffers identical?  Common case: Handle this efficiently.
206   if (A_size == B_size &&
207       std::memcmp(File1Start, File2Start, A_size) == 0)
208     return 0;
209 
210   // Otherwise, we are done a tolerances are set.
211   if (AbsTol == 0 && RelTol == 0) {
212     if (Error)
213       *Error = "Files differ without tolerance allowance";
214     return 1;   // Files different!
215   }
216 
217   bool CompareFailed = false;
218   while (1) {
219     // Scan for the end of file or next difference.
220     while (F1P < File1End && F2P < File2End && *F1P == *F2P) {
221       ++F1P;
222       ++F2P;
223     }
224 
225     if (F1P >= File1End || F2P >= File2End) break;
226 
227     // Okay, we must have found a difference.  Backup to the start of the
228     // current number each stream is at so that we can compare from the
229     // beginning.
230     F1P = BackupNumber(F1P, File1Start);
231     F2P = BackupNumber(F2P, File2Start);
232 
233     // Now that we are at the start of the numbers, compare them, exiting if
234     // they don't match.
235     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) {
236       CompareFailed = true;
237       break;
238     }
239   }
240 
241   // Okay, we reached the end of file.  If both files are at the end, we
242   // succeeded.
243   bool F1AtEnd = F1P >= File1End;
244   bool F2AtEnd = F2P >= File2End;
245   if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) {
246     // Else, we might have run off the end due to a number: backup and retry.
247     if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;
248     if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;
249     F1P = BackupNumber(F1P, File1Start);
250     F2P = BackupNumber(F2P, File2Start);
251 
252     // Now that we are at the start of the numbers, compare them, exiting if
253     // they don't match.
254     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error))
255       CompareFailed = true;
256 
257     // If we found the end, we succeeded.
258     if (F1P < File1End || F2P < File2End)
259       CompareFailed = true;
260   }
261 
262   return CompareFailed;
263 }
264