LLVM  14.0.0git
FileUtilities.cpp
Go to the documentation of this file.
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 
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"
21 #include "llvm/Support/Path.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 
33 static bool isSignedChar(char C) {
34  return (C == '+' || C == '-');
35 }
36 
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 
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 
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.
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.
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 ///
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.
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 
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 
273  OS << "atomic_write_error: ";
274  switch (Error) {
276  OS << "failed_to_create_uniq_file";
277  return;
279  OS << "output_stream_error";
280  return;
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 
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 
299  StringRef TempPathModel, StringRef FinalPath,
301  SmallString<128> GeneratedUniqPath;
302  int TempFD;
303  if (sys::fs::createUniqueFile(TempPathModel, TempFD, GeneratedUniqPath)) {
304  return llvm::make_error<AtomicFileWriteError>(
306  }
307  llvm::FileRemover RemoveTmpFileOnFail(GeneratedUniqPath);
308 
309  raw_fd_ostream OS(TempFD, /*shouldClose=*/true);
310  if (llvm::Error Err = Writer(OS)) {
311  return Err;
312  }
313 
314  OS.close();
315  if (OS.has_error()) {
316  OS.clear_error();
317  return llvm::make_error<AtomicFileWriteError>(
319  }
320 
321  if (sys::fs::rename(/*from=*/GeneratedUniqPath, /*to=*/FinalPath)) {
322  return llvm::make_error<AtomicFileWriteError>(
324  }
325 
326  RemoveTmpFileOnFail.releaseFile();
327  return Error::success();
328 }
329 
MemoryBuffer.h
BackupNumber
static const char * BackupNumber(const char *Pos, const char *FirstChar)
Definition: FileUtilities.cpp:56
llvm
This file implements support for optimizing divisions by a constant.
Definition: AllocatorList.h:23
llvm::raw_fd_ostream::close
void close()
Manually flush the stream and close the file.
Definition: raw_ostream.cpp:793
llvm::atomic_write_error::output_stream_error
@ output_stream_error
llvm::FileRemover
FileRemover - This class is a simple object meant to be stack allocated.
Definition: FileUtilities.h:42
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:625
llvm::FileRemover::releaseFile
void releaseFile()
releaseFile - Take ownership of the file away from the FileRemover so it will not be removed when the...
Definition: FileUtilities.h:76
Path.h
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:331
memcmp
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:888
Error.h
llvm::AtomicFileWriteError::ID
static char ID
Definition: FileUtilities.h:92
llvm::sys::fs::createUniqueFile
std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None, unsigned Mode=all_read|all_write)
Create a uniquely named file.
Definition: Path.cpp:815
llvm::MemoryBuffer
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:50
isExponentChar
static bool isExponentChar(char C)
Definition: FileUtilities.cpp:37
llvm::MemoryBuffer::getFile
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: MemoryBuffer.cpp:246
llvm::writeFileAtomically
llvm::Error writeFileAtomically(StringRef TempPathModel, StringRef FinalPath, StringRef Buffer)
Creates a unique file with name according to the given TempPathModel, writes content of Buffer to the...
Definition: FileUtilities.cpp:289
llvm::MemoryBuffer::getBufferEnd
const char * getBufferEnd() const
Definition: MemoryBuffer.h:66
llvm::raw_fd_ostream::has_error
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
Definition: raw_ostream.h:531
SmallString.h
llvm::MemoryBuffer::getBufferSize
size_t getBufferSize() const
Definition: MemoryBuffer.h:67
isSignedChar
static bool isSignedChar(char C)
Definition: FileUtilities.cpp:33
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::raw_fd_ostream::clear_error
void clear_error()
Set the flag read by has_error() to false.
Definition: raw_ostream.h:542
llvm::ErrorOr::getError
std::error_code getError() const
Definition: ErrorOr.h:153
llvm::atomic_write_error::failed_to_rename_temp_file
@ failed_to_rename_temp_file
llvm::raw_ostream::write
raw_ostream & write(unsigned char C)
Definition: raw_ostream.cpp:220
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::SmallString
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:25
uint64_t
ErrorOr.h
StringExtras.h
function
print Print MemDeps of function
Definition: MemDepPrinter.cpp:83
FileUtilities.h
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:134
llvm::sys::fs::rename
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
llvm::AtomicFileWriteError::log
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: FileUtilities.cpp:272
llvm::atomic_write_error::failed_to_create_uniq_file
@ failed_to_create_uniq_file
llvm::raw_fd_ostream
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:443
llvm::NVPTX::PTXLdStInstCode::V2
@ V2
Definition: NVPTX.h:123
llvm::MemoryBuffer::getBufferStart
const char * getBufferStart() const
Definition: MemoryBuffer.h:65
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
llvm::DiffFilesWithTolerance
int DiffFilesWithTolerance(StringRef FileA, StringRef FileB, double AbsTol, double RelTol, std::string *Error=nullptr)
DiffFilesWithTolerance - Compare the two files specified, returning 0 if the files match,...
Definition: FileUtilities.cpp:180
CompareNumbers
static bool CompareNumbers(const char *&F1P, const char *&F2P, const char *F1End, const char *F2End, double AbsTolerance, double RelTolerance, std::string *ErrorMsg)
CompareNumbers - compare two numbers, returning true if they are different.
Definition: FileUtilities.cpp:87
llvm::ErrorOr::get
reference get()
Definition: ErrorOr.h:150
llvm::ErrorOr
Represents either an error or a value T.
Definition: ErrorOr.h:56
ScopeExit.h
llvm::StringRef::data
const LLVM_NODISCARD char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:149
isNumberChar
static bool isNumberChar(char C)
Definition: FileUtilities.cpp:47
EndOfNumber
static const char * EndOfNumber(const char *Pos)
EndOfNumber - Return the first character that is not part of the specified number.
Definition: FileUtilities.cpp:80
raw_ostream.h
llvm::StringRef::size
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:157
llvm::abs
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition: APFloat.h:1282