1 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a family of utility functions which are useful for doing
10 // various things with files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Support/FileUtilities.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Error.h"
19 #include "llvm/Support/ErrorOr.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <cctype>
24 #include <cmath>
25 #include <cstdint>
26 #include <cstdlib>
27 #include <cstring>
28 #include <memory>
29 #include <system_error>
30 
31 using namespace llvm;
32 
isSignedChar(char C)33 static bool isSignedChar(char C) {
34   return (C == '+' || C == '-');
35 }
36 
isExponentChar(char C)37 static bool isExponentChar(char C) {
38   switch (C) {
39   case 'D':  // Strange exponential notation.
40   case 'd':  // Strange exponential notation.
41   case 'e':
42   case 'E': return true;
43   default: return false;
44   }
45 }
46 
isNumberChar(char C)47 static bool isNumberChar(char C) {
48   switch (C) {
49   case '0': case '1': case '2': case '3': case '4':
50   case '5': case '6': case '7': case '8': case '9':
51   case '.': return true;
52   default: return isSignedChar(C) || isExponentChar(C);
53   }
54 }
55 
BackupNumber(const char * Pos,const char * FirstChar)56 static const char *BackupNumber(const char *Pos, const char *FirstChar) {
57   // If we didn't stop in the middle of a number, don't backup.
58   if (!isNumberChar(*Pos)) return Pos;
59 
60   // Otherwise, return to the start of the number.
61   bool HasPeriod = false;
62   while (Pos > FirstChar && isNumberChar(Pos[-1])) {
63     // Backup over at most one period.
64     if (Pos[-1] == '.') {
65       if (HasPeriod)
66         break;
67       HasPeriod = true;
68     }
69 
70     --Pos;
71     if (Pos > FirstChar && isSignedChar(Pos[0]) && !isExponentChar(Pos[-1]))
72       break;
73   }
74   return Pos;
75 }
76 
77 /// EndOfNumber - Return the first character that is not part of the specified
78 /// number.  This assumes that the buffer is null terminated, so it won't fall
79 /// off the end.
EndOfNumber(const char * Pos)80 static const char *EndOfNumber(const char *Pos) {
81   while (isNumberChar(*Pos))
82     ++Pos;
83   return Pos;
84 }
85 
86 /// 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)87 static bool CompareNumbers(const char *&F1P, const char *&F2P,
88                            const char *F1End, const char *F2End,
89                            double AbsTolerance, double RelTolerance,
90                            std::string *ErrorMsg) {
91   const char *F1NumEnd, *F2NumEnd;
92   double V1 = 0.0, V2 = 0.0;
93 
94   // If one of the positions is at a space and the other isn't, chomp up 'til
95   // the end of the space.
96   while (isSpace(static_cast<unsigned char>(*F1P)) && F1P != F1End)
97     ++F1P;
98   while (isSpace(static_cast<unsigned char>(*F2P)) && F2P != F2End)
99     ++F2P;
100 
101   // If we stop on numbers, compare their difference.
102   if (!isNumberChar(*F1P) || !isNumberChar(*F2P)) {
103     // The diff failed.
104     F1NumEnd = F1P;
105     F2NumEnd = F2P;
106   } else {
107     // Note that some ugliness is built into this to permit support for numbers
108     // that use "D" or "d" as their exponential marker, e.g. "1.234D45".  This
109     // occurs in 200.sixtrack in spec2k.
110     V1 = strtod(F1P, const_cast<char**>(&F1NumEnd));
111     V2 = strtod(F2P, const_cast<char**>(&F2NumEnd));
112 
113     if (*F1NumEnd == 'D' || *F1NumEnd == 'd') {
114       // Copy string into tmp buffer to replace the 'D' with an 'e'.
115       SmallString<200> StrTmp(F1P, EndOfNumber(F1NumEnd)+1);
116       // Strange exponential notation!
117       StrTmp[static_cast<unsigned>(F1NumEnd-F1P)] = 'e';
118 
119       V1 = strtod(&StrTmp[0], const_cast<char**>(&F1NumEnd));
120       F1NumEnd = F1P + (F1NumEnd-&StrTmp[0]);
121     }
122 
123     if (*F2NumEnd == 'D' || *F2NumEnd == 'd') {
124       // Copy string into tmp buffer to replace the 'D' with an 'e'.
125       SmallString<200> StrTmp(F2P, EndOfNumber(F2NumEnd)+1);
126       // Strange exponential notation!
127       StrTmp[static_cast<unsigned>(F2NumEnd-F2P)] = 'e';
128 
129       V2 = strtod(&StrTmp[0], const_cast<char**>(&F2NumEnd));
130       F2NumEnd = F2P + (F2NumEnd-&StrTmp[0]);
131     }
132   }
133 
134   if (F1NumEnd == F1P || F2NumEnd == F2P) {
135     if (ErrorMsg) {
136       *ErrorMsg = "FP Comparison failed, not a numeric difference between '";
137       *ErrorMsg += F1P[0];
138       *ErrorMsg += "' and '";
139       *ErrorMsg += F2P[0];
140       *ErrorMsg += "'";
141     }
142     return true;
143   }
144 
145   // Check to see if these are inside the absolute tolerance
146   if (AbsTolerance < std::abs(V1-V2)) {
147     // Nope, check the relative tolerance...
148     double Diff;
149     if (V2)
150       Diff = std::abs(V1/V2 - 1.0);
151     else if (V1)
152       Diff = std::abs(V2/V1 - 1.0);
153     else
154       Diff = 0;  // Both zero.
155     if (Diff > RelTolerance) {
156       if (ErrorMsg) {
157         raw_string_ostream(*ErrorMsg)
158           << "Compared: " << V1 << " and " << V2 << '\n'
159           << "abs. diff = " << std::abs(V1-V2) << " rel.diff = " << Diff << '\n'
160           << "Out of tolerance: rel/abs: " << RelTolerance << '/'
161           << AbsTolerance;
162       }
163       return true;
164     }
165   }
166 
167   // Otherwise, advance our read pointers to the end of the numbers.
168   F1P = F1NumEnd;  F2P = F2NumEnd;
169   return false;
170 }
171 
172 /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the
173 /// files match, 1 if they are different, and 2 if there is a file error.  This
174 /// function differs from DiffFiles in that you can specify an absolete and
175 /// relative FP error that is allowed to exist.  If you specify a string to fill
176 /// in for the error option, it will set the string to an error message if an
177 /// error occurs, allowing the caller to distinguish between a failed diff and a
178 /// file system error.
179 ///
DiffFilesWithTolerance(StringRef NameA,StringRef NameB,double AbsTol,double RelTol,std::string * Error)180 int llvm::DiffFilesWithTolerance(StringRef NameA,
181                                  StringRef NameB,
182                                  double AbsTol, double RelTol,
183                                  std::string *Error) {
184   // Now its safe to mmap the files into memory because both files
185   // have a non-zero size.
186   ErrorOr<std::unique_ptr<MemoryBuffer>> F1OrErr = MemoryBuffer::getFile(NameA);
187   if (std::error_code EC = F1OrErr.getError()) {
188     if (Error)
189       *Error = EC.message();
190     return 2;
191   }
192   MemoryBuffer &F1 = *F1OrErr.get();
193 
194   ErrorOr<std::unique_ptr<MemoryBuffer>> F2OrErr = MemoryBuffer::getFile(NameB);
195   if (std::error_code EC = F2OrErr.getError()) {
196     if (Error)
197       *Error = EC.message();
198     return 2;
199   }
200   MemoryBuffer &F2 = *F2OrErr.get();
201 
202   // Okay, now that we opened the files, scan them for the first difference.
203   const char *File1Start = F1.getBufferStart();
204   const char *File2Start = F2.getBufferStart();
205   const char *File1End = F1.getBufferEnd();
206   const char *File2End = F2.getBufferEnd();
207   const char *F1P = File1Start;
208   const char *F2P = File2Start;
209   uint64_t A_size = F1.getBufferSize();
210   uint64_t B_size = F2.getBufferSize();
211 
212   // Are the buffers identical?  Common case: Handle this efficiently.
213   if (A_size == B_size &&
214       std::memcmp(File1Start, File2Start, A_size) == 0)
215     return 0;
216 
217   // Otherwise, we are done a tolerances are set.
218   if (AbsTol == 0 && RelTol == 0) {
219     if (Error)
220       *Error = "Files differ without tolerance allowance";
221     return 1;   // Files different!
222   }
223 
224   bool CompareFailed = false;
225   while (true) {
226     // Scan for the end of file or next difference.
227     while (F1P < File1End && F2P < File2End && *F1P == *F2P) {
228       ++F1P;
229       ++F2P;
230     }
231 
232     if (F1P >= File1End || F2P >= File2End) break;
233 
234     // Okay, we must have found a difference.  Backup to the start of the
235     // current number each stream is at so that we can compare from the
236     // beginning.
237     F1P = BackupNumber(F1P, File1Start);
238     F2P = BackupNumber(F2P, File2Start);
239 
240     // Now that we are at the start of the numbers, compare them, exiting if
241     // they don't match.
242     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) {
243       CompareFailed = true;
244       break;
245     }
246   }
247 
248   // Okay, we reached the end of file.  If both files are at the end, we
249   // succeeded.
250   bool F1AtEnd = F1P >= File1End;
251   bool F2AtEnd = F2P >= File2End;
252   if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) {
253     // Else, we might have run off the end due to a number: backup and retry.
254     if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;
255     if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;
256     F1P = BackupNumber(F1P, File1Start);
257     F2P = BackupNumber(F2P, File2Start);
258 
259     // Now that we are at the start of the numbers, compare them, exiting if
260     // they don't match.
261     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error))
262       CompareFailed = true;
263 
264     // If we found the end, we succeeded.
265     if (F1P < File1End || F2P < File2End)
266       CompareFailed = true;
267   }
268 
269   return CompareFailed;
270 }
271 
log(raw_ostream & OS) const272 void llvm::AtomicFileWriteError::log(raw_ostream &OS) const {
273   OS << "atomic_write_error: ";
274   switch (Error) {
275   case atomic_write_error::failed_to_create_uniq_file:
276     OS << "failed_to_create_uniq_file";
277     return;
278   case atomic_write_error::output_stream_error:
279     OS << "output_stream_error";
280     return;
281   case atomic_write_error::failed_to_rename_temp_file:
282     OS << "failed_to_rename_temp_file";
283     return;
284   }
285   llvm_unreachable("unknown atomic_write_error value in "
286                    "failed_to_rename_temp_file::log()");
287 }
288 
writeFileAtomically(StringRef TempPathModel,StringRef FinalPath,StringRef Buffer)289 llvm::Error llvm::writeFileAtomically(StringRef TempPathModel,
290                                       StringRef FinalPath, StringRef Buffer) {
291   return writeFileAtomically(TempPathModel, FinalPath,
292                              [&Buffer](llvm::raw_ostream &OS) {
293                                OS.write(Buffer.data(), Buffer.size());
294                                return llvm::Error::success();
295                              });
296 }
297 
writeFileAtomically(StringRef TempPathModel,StringRef FinalPath,std::function<llvm::Error (llvm::raw_ostream &)> Writer)298 llvm::Error llvm::writeFileAtomically(
299     StringRef TempPathModel, StringRef FinalPath,
300     std::function<llvm::Error(llvm::raw_ostream &)> Writer) {
301   SmallString<128> GeneratedUniqPath;
302   int TempFD;
303   if (sys::fs::createUniqueFile(TempPathModel.str(), TempFD,
304                                 GeneratedUniqPath)) {
305     return llvm::make_error<AtomicFileWriteError>(
306         atomic_write_error::failed_to_create_uniq_file);
307   }
308   llvm::FileRemover RemoveTmpFileOnFail(GeneratedUniqPath);
309 
310   raw_fd_ostream OS(TempFD, /*shouldClose=*/true);
311   if (llvm::Error Err = Writer(OS)) {
312     return Err;
313   }
314 
315   OS.close();
316   if (OS.has_error()) {
317     OS.clear_error();
318     return llvm::make_error<AtomicFileWriteError>(
319         atomic_write_error::output_stream_error);
320   }
321 
322   if (sys::fs::rename(/*from=*/GeneratedUniqPath.c_str(),
323                       /*to=*/FinalPath.str().c_str())) {
324     return llvm::make_error<AtomicFileWriteError>(
325         atomic_write_error::failed_to_rename_temp_file);
326   }
327 
328   RemoveTmpFileOnFail.releaseFile();
329   return Error::success();
330 }
331 
332 char llvm::AtomicFileWriteError::ID;
333