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/Support/Error.h"
18 #include "llvm/Support/ErrorOr.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/raw_ostream.h"
28 #include <system_error>
32 static bool isSignedChar(char C
) {
33 return (C
== '+' || C
== '-');
36 static bool isExponentChar(char C
) {
38 case 'D': // Strange exponential notation.
39 case 'd': // Strange exponential notation.
41 case 'E': return true;
42 default: return false;
46 static bool isNumberChar(char C
) {
48 case '0': case '1': case '2': case '3': case '4':
49 case '5': case '6': case '7': case '8': case '9':
50 case '.': return true;
51 default: return isSignedChar(C
) || isExponentChar(C
);
55 static const char *BackupNumber(const char *Pos
, const char *FirstChar
) {
56 // If we didn't stop in the middle of a number, don't backup.
57 if (!isNumberChar(*Pos
)) return Pos
;
59 // Otherwise, return to the start of the number.
60 bool HasPeriod
= false;
61 while (Pos
> FirstChar
&& isNumberChar(Pos
[-1])) {
62 // Backup over at most one period.
70 if (Pos
> FirstChar
&& isSignedChar(Pos
[0]) && !isExponentChar(Pos
[-1]))
76 /// EndOfNumber - Return the first character that is not part of the specified
77 /// number. This assumes that the buffer is null terminated, so it won't fall
79 static const char *EndOfNumber(const char *Pos
) {
80 while (isNumberChar(*Pos
))
85 /// CompareNumbers - compare two numbers, returning true if they are different.
86 static bool CompareNumbers(const char *&F1P
, const char *&F2P
,
87 const char *F1End
, const char *F2End
,
88 double AbsTolerance
, double RelTolerance
,
89 std::string
*ErrorMsg
) {
90 const char *F1NumEnd
, *F2NumEnd
;
91 double V1
= 0.0, V2
= 0.0;
93 // If one of the positions is at a space and the other isn't, chomp up 'til
94 // the end of the space.
95 while (isspace(static_cast<unsigned char>(*F1P
)) && F1P
!= F1End
)
97 while (isspace(static_cast<unsigned char>(*F2P
)) && F2P
!= F2End
)
100 // If we stop on numbers, compare their difference.
101 if (!isNumberChar(*F1P
) || !isNumberChar(*F2P
)) {
106 // Note that some ugliness is built into this to permit support for numbers
107 // that use "D" or "d" as their exponential marker, e.g. "1.234D45". This
108 // occurs in 200.sixtrack in spec2k.
109 V1
= strtod(F1P
, const_cast<char**>(&F1NumEnd
));
110 V2
= strtod(F2P
, const_cast<char**>(&F2NumEnd
));
112 if (*F1NumEnd
== 'D' || *F1NumEnd
== 'd') {
113 // Copy string into tmp buffer to replace the 'D' with an 'e'.
114 SmallString
<200> StrTmp(F1P
, EndOfNumber(F1NumEnd
)+1);
115 // Strange exponential notation!
116 StrTmp
[static_cast<unsigned>(F1NumEnd
-F1P
)] = 'e';
118 V1
= strtod(&StrTmp
[0], const_cast<char**>(&F1NumEnd
));
119 F1NumEnd
= F1P
+ (F1NumEnd
-&StrTmp
[0]);
122 if (*F2NumEnd
== 'D' || *F2NumEnd
== 'd') {
123 // Copy string into tmp buffer to replace the 'D' with an 'e'.
124 SmallString
<200> StrTmp(F2P
, EndOfNumber(F2NumEnd
)+1);
125 // Strange exponential notation!
126 StrTmp
[static_cast<unsigned>(F2NumEnd
-F2P
)] = 'e';
128 V2
= strtod(&StrTmp
[0], const_cast<char**>(&F2NumEnd
));
129 F2NumEnd
= F2P
+ (F2NumEnd
-&StrTmp
[0]);
133 if (F1NumEnd
== F1P
|| F2NumEnd
== F2P
) {
135 *ErrorMsg
= "FP Comparison failed, not a numeric difference between '";
137 *ErrorMsg
+= "' and '";
144 // Check to see if these are inside the absolute tolerance
145 if (AbsTolerance
< std::abs(V1
-V2
)) {
146 // Nope, check the relative tolerance...
149 Diff
= std::abs(V1
/V2
- 1.0);
151 Diff
= std::abs(V2
/V1
- 1.0);
153 Diff
= 0; // Both zero.
154 if (Diff
> RelTolerance
) {
156 raw_string_ostream(*ErrorMsg
)
157 << "Compared: " << V1
<< " and " << V2
<< '\n'
158 << "abs. diff = " << std::abs(V1
-V2
) << " rel.diff = " << Diff
<< '\n'
159 << "Out of tolerance: rel/abs: " << RelTolerance
<< '/'
166 // Otherwise, advance our read pointers to the end of the numbers.
167 F1P
= F1NumEnd
; F2P
= F2NumEnd
;
171 /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the
172 /// files match, 1 if they are different, and 2 if there is a file error. This
173 /// function differs from DiffFiles in that you can specify an absolete and
174 /// relative FP error that is allowed to exist. If you specify a string to fill
175 /// in for the error option, it will set the string to an error message if an
176 /// error occurs, allowing the caller to distinguish between a failed diff and a
177 /// file system error.
179 int llvm::DiffFilesWithTolerance(StringRef NameA
,
181 double AbsTol
, double RelTol
,
182 std::string
*Error
) {
183 // Now its safe to mmap the files into memory because both files
184 // have a non-zero size.
185 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> F1OrErr
= MemoryBuffer::getFile(NameA
);
186 if (std::error_code EC
= F1OrErr
.getError()) {
188 *Error
= EC
.message();
191 MemoryBuffer
&F1
= *F1OrErr
.get();
193 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> F2OrErr
= MemoryBuffer::getFile(NameB
);
194 if (std::error_code EC
= F2OrErr
.getError()) {
196 *Error
= EC
.message();
199 MemoryBuffer
&F2
= *F2OrErr
.get();
201 // Okay, now that we opened the files, scan them for the first difference.
202 const char *File1Start
= F1
.getBufferStart();
203 const char *File2Start
= F2
.getBufferStart();
204 const char *File1End
= F1
.getBufferEnd();
205 const char *File2End
= F2
.getBufferEnd();
206 const char *F1P
= File1Start
;
207 const char *F2P
= File2Start
;
208 uint64_t A_size
= F1
.getBufferSize();
209 uint64_t B_size
= F2
.getBufferSize();
211 // Are the buffers identical? Common case: Handle this efficiently.
212 if (A_size
== B_size
&&
213 std::memcmp(File1Start
, File2Start
, A_size
) == 0)
216 // Otherwise, we are done a tolerances are set.
217 if (AbsTol
== 0 && RelTol
== 0) {
219 *Error
= "Files differ without tolerance allowance";
220 return 1; // Files different!
223 bool CompareFailed
= false;
225 // Scan for the end of file or next difference.
226 while (F1P
< File1End
&& F2P
< File2End
&& *F1P
== *F2P
) {
231 if (F1P
>= File1End
|| F2P
>= File2End
) break;
233 // Okay, we must have found a difference. Backup to the start of the
234 // current number each stream is at so that we can compare from the
236 F1P
= BackupNumber(F1P
, File1Start
);
237 F2P
= BackupNumber(F2P
, File2Start
);
239 // Now that we are at the start of the numbers, compare them, exiting if
241 if (CompareNumbers(F1P
, F2P
, File1End
, File2End
, AbsTol
, RelTol
, Error
)) {
242 CompareFailed
= true;
247 // Okay, we reached the end of file. If both files are at the end, we
249 bool F1AtEnd
= F1P
>= File1End
;
250 bool F2AtEnd
= F2P
>= File2End
;
251 if (!CompareFailed
&& (!F1AtEnd
|| !F2AtEnd
)) {
252 // Else, we might have run off the end due to a number: backup and retry.
253 if (F1AtEnd
&& isNumberChar(F1P
[-1])) --F1P
;
254 if (F2AtEnd
&& isNumberChar(F2P
[-1])) --F2P
;
255 F1P
= BackupNumber(F1P
, File1Start
);
256 F2P
= BackupNumber(F2P
, File2Start
);
258 // Now that we are at the start of the numbers, compare them, exiting if
260 if (CompareNumbers(F1P
, F2P
, File1End
, File2End
, AbsTol
, RelTol
, Error
))
261 CompareFailed
= true;
263 // If we found the end, we succeeded.
264 if (F1P
< File1End
|| F2P
< File2End
)
265 CompareFailed
= true;
268 return CompareFailed
;
271 void llvm::AtomicFileWriteError::log(raw_ostream
&OS
) const {
272 OS
<< "atomic_write_error: ";
274 case atomic_write_error::failed_to_create_uniq_file
:
275 OS
<< "failed_to_create_uniq_file";
277 case atomic_write_error::output_stream_error
:
278 OS
<< "output_stream_error";
280 case atomic_write_error::failed_to_rename_temp_file
:
281 OS
<< "failed_to_rename_temp_file";
284 llvm_unreachable("unknown atomic_write_error value in "
285 "failed_to_rename_temp_file::log()");
288 llvm::Error
llvm::writeFileAtomically(StringRef TempPathModel
,
289 StringRef FinalPath
, StringRef Buffer
) {
290 return writeFileAtomically(TempPathModel
, FinalPath
,
291 [&Buffer
](llvm::raw_ostream
&OS
) {
292 OS
.write(Buffer
.data(), Buffer
.size());
293 return llvm::Error::success();
297 llvm::Error
llvm::writeFileAtomically(
298 StringRef TempPathModel
, StringRef FinalPath
,
299 std::function
<llvm::Error(llvm::raw_ostream
&)> Writer
) {
300 SmallString
<128> GeneratedUniqPath
;
302 if (sys::fs::createUniqueFile(TempPathModel
.str(), TempFD
,
303 GeneratedUniqPath
)) {
304 return llvm::make_error
<AtomicFileWriteError
>(
305 atomic_write_error::failed_to_create_uniq_file
);
307 llvm::FileRemover
RemoveTmpFileOnFail(GeneratedUniqPath
);
309 raw_fd_ostream
OS(TempFD
, /*shouldClose=*/true);
310 if (llvm::Error Err
= Writer(OS
)) {
315 if (OS
.has_error()) {
317 return llvm::make_error
<AtomicFileWriteError
>(
318 atomic_write_error::output_stream_error
);
321 if (const std::error_code Error
=
322 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
;