1 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements a family of utility functions which are useful for doing
10 // various things with files.
12 //===----------------------------------------------------------------------===//
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"
29 #include <system_error>
33 static bool isSignedChar(char C
) {
34 return (C
== '+' || C
== '-');
37 static bool isExponentChar(char C
) {
39 case 'D': // Strange exponential notation.
40 case 'd': // Strange exponential notation.
42 case 'E': return true;
43 default: return false;
47 static bool isNumberChar(char 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
);
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
;
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.
71 if (Pos
> FirstChar
&& isSignedChar(Pos
[0]) && !isExponentChar(Pos
[-1]))
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
80 static const char *EndOfNumber(const char *Pos
) {
81 while (isNumberChar(*Pos
))
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;
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
)
98 while (isSpace(static_cast<unsigned char>(*F2P
)) && F2P
!= F2End
)
101 // If we stop on numbers, compare their difference.
102 if (!isNumberChar(*F1P
) || !isNumberChar(*F2P
)) {
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
));
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';
119 V1
= strtod(&StrTmp
[0], const_cast<char**>(&F1NumEnd
));
120 F1NumEnd
= F1P
+ (F1NumEnd
-&StrTmp
[0]);
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';
129 V2
= strtod(&StrTmp
[0], const_cast<char**>(&F2NumEnd
));
130 F2NumEnd
= F2P
+ (F2NumEnd
-&StrTmp
[0]);
134 if (F1NumEnd
== F1P
|| F2NumEnd
== F2P
) {
136 *ErrorMsg
= "FP Comparison failed, not a numeric difference between '";
138 *ErrorMsg
+= "' and '";
145 // Check to see if these are inside the absolute tolerance
146 if (AbsTolerance
< std::abs(V1
-V2
)) {
147 // Nope, check the relative tolerance...
150 Diff
= std::abs(V1
/V2
- 1.0);
152 Diff
= std::abs(V2
/V1
- 1.0);
154 Diff
= 0; // Both zero.
155 if (Diff
> RelTolerance
) {
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
<< '/'
167 // Otherwise, advance our read pointers to the end of the numbers.
168 F1P
= F1NumEnd
; F2P
= F2NumEnd
;
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.
180 int llvm::DiffFilesWithTolerance(StringRef NameA
,
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()) {
189 *Error
= EC
.message();
192 MemoryBuffer
&F1
= *F1OrErr
.get();
194 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> F2OrErr
= MemoryBuffer::getFile(NameB
);
195 if (std::error_code EC
= F2OrErr
.getError()) {
197 *Error
= EC
.message();
200 MemoryBuffer
&F2
= *F2OrErr
.get();
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();
212 // Are the buffers identical? Common case: Handle this efficiently.
213 if (A_size
== B_size
&&
214 std::memcmp(File1Start
, File2Start
, A_size
) == 0)
217 // Otherwise, we are done a tolerances are set.
218 if (AbsTol
== 0 && RelTol
== 0) {
220 *Error
= "Files differ without tolerance allowance";
221 return 1; // Files different!
224 bool CompareFailed
= false;
226 // Scan for the end of file or next difference.
227 while (F1P
< File1End
&& F2P
< File2End
&& *F1P
== *F2P
) {
232 if (F1P
>= File1End
|| F2P
>= File2End
) break;
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
237 F1P
= BackupNumber(F1P
, File1Start
);
238 F2P
= BackupNumber(F2P
, File2Start
);
240 // Now that we are at the start of the numbers, compare them, exiting if
242 if (CompareNumbers(F1P
, F2P
, File1End
, File2End
, AbsTol
, RelTol
, Error
)) {
243 CompareFailed
= true;
248 // Okay, we reached the end of file. If both files are at the end, we
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
);
259 // Now that we are at the start of the numbers, compare them, exiting if
261 if (CompareNumbers(F1P
, F2P
, File1End
, File2End
, AbsTol
, RelTol
, Error
))
262 CompareFailed
= true;
264 // If we found the end, we succeeded.
265 if (F1P
< File1End
|| F2P
< File2End
)
266 CompareFailed
= true;
269 return CompareFailed
;
272 void llvm::AtomicFileWriteError::log(raw_ostream
&OS
) const {
273 OS
<< "atomic_write_error: ";
275 case atomic_write_error::failed_to_create_uniq_file
:
276 OS
<< "failed_to_create_uniq_file";
278 case atomic_write_error::output_stream_error
:
279 OS
<< "output_stream_error";
281 case atomic_write_error::failed_to_rename_temp_file
:
282 OS
<< "failed_to_rename_temp_file";
285 llvm_unreachable("unknown atomic_write_error value in "
286 "failed_to_rename_temp_file::log()");
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();
298 llvm::Error
llvm::writeFileAtomically(
299 StringRef TempPathModel
, StringRef FinalPath
,
300 std::function
<llvm::Error(llvm::raw_ostream
&)> Writer
) {
301 SmallString
<128> GeneratedUniqPath
;
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
);
308 llvm::FileRemover
RemoveTmpFileOnFail(GeneratedUniqPath
);
310 raw_fd_ostream
OS(TempFD
, /*shouldClose=*/true);
311 if (llvm::Error Err
= Writer(OS
)) {
316 if (OS
.has_error()) {
318 return llvm::make_error
<AtomicFileWriteError
>(
319 atomic_write_error::output_stream_error
);
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
);
328 RemoveTmpFileOnFail
.releaseFile();
329 return Error::success();
332 char llvm::AtomicFileWriteError::ID
;