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/SmallString.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Error.h"
18 #include "llvm/Support/ErrorOr.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/Process.h"
21 #include "llvm/Support/raw_ostream.h"
27 #include <system_error>
31 static bool isSignedChar(char C
) {
32 return (C
== '+' || C
== '-');
35 static bool isExponentChar(char C
) {
37 case 'D': // Strange exponential notation.
38 case 'd': // Strange exponential notation.
40 case 'E': return true;
41 default: return false;
45 static bool isNumberChar(char C
) {
47 case '0': case '1': case '2': case '3': case '4':
48 case '5': case '6': case '7': case '8': case '9':
49 case '.': return true;
50 default: return isSignedChar(C
) || isExponentChar(C
);
54 static const char *BackupNumber(const char *Pos
, const char *FirstChar
) {
55 // If we didn't stop in the middle of a number, don't backup.
56 if (!isNumberChar(*Pos
)) return Pos
;
58 // Otherwise, return to the start of the number.
59 bool HasPeriod
= false;
60 while (Pos
> FirstChar
&& isNumberChar(Pos
[-1])) {
61 // Backup over at most one period.
69 if (Pos
> FirstChar
&& isSignedChar(Pos
[0]) && !isExponentChar(Pos
[-1]))
75 /// EndOfNumber - Return the first character that is not part of the specified
76 /// number. This assumes that the buffer is null terminated, so it won't fall
78 static const char *EndOfNumber(const char *Pos
) {
79 while (isNumberChar(*Pos
))
84 /// CompareNumbers - compare two numbers, returning true if they are different.
85 static bool CompareNumbers(const char *&F1P
, const char *&F2P
,
86 const char *F1End
, const char *F2End
,
87 double AbsTolerance
, double RelTolerance
,
88 std::string
*ErrorMsg
) {
89 const char *F1NumEnd
, *F2NumEnd
;
90 double V1
= 0.0, V2
= 0.0;
92 // If one of the positions is at a space and the other isn't, chomp up 'til
93 // the end of the space.
94 while (isSpace(static_cast<unsigned char>(*F1P
)) && F1P
!= F1End
)
96 while (isSpace(static_cast<unsigned char>(*F2P
)) && F2P
!= F2End
)
99 // If we stop on numbers, compare their difference.
100 if (!isNumberChar(*F1P
) || !isNumberChar(*F2P
)) {
105 // Note that some ugliness is built into this to permit support for numbers
106 // that use "D" or "d" as their exponential marker, e.g. "1.234D45". This
107 // occurs in 200.sixtrack in spec2k.
108 V1
= strtod(F1P
, const_cast<char**>(&F1NumEnd
));
109 V2
= strtod(F2P
, const_cast<char**>(&F2NumEnd
));
111 if (*F1NumEnd
== 'D' || *F1NumEnd
== 'd') {
112 // Copy string into tmp buffer to replace the 'D' with an 'e'.
113 SmallString
<200> StrTmp(F1P
, EndOfNumber(F1NumEnd
)+1);
114 // Strange exponential notation!
115 StrTmp
[static_cast<unsigned>(F1NumEnd
-F1P
)] = 'e';
117 V1
= strtod(&StrTmp
[0], const_cast<char**>(&F1NumEnd
));
118 F1NumEnd
= F1P
+ (F1NumEnd
-&StrTmp
[0]);
121 if (*F2NumEnd
== 'D' || *F2NumEnd
== 'd') {
122 // Copy string into tmp buffer to replace the 'D' with an 'e'.
123 SmallString
<200> StrTmp(F2P
, EndOfNumber(F2NumEnd
)+1);
124 // Strange exponential notation!
125 StrTmp
[static_cast<unsigned>(F2NumEnd
-F2P
)] = 'e';
127 V2
= strtod(&StrTmp
[0], const_cast<char**>(&F2NumEnd
));
128 F2NumEnd
= F2P
+ (F2NumEnd
-&StrTmp
[0]);
132 if (F1NumEnd
== F1P
|| F2NumEnd
== F2P
) {
134 *ErrorMsg
= "FP Comparison failed, not a numeric difference between '";
136 *ErrorMsg
+= "' and '";
143 // Check to see if these are inside the absolute tolerance
144 if (AbsTolerance
< std::abs(V1
-V2
)) {
145 // Nope, check the relative tolerance...
148 Diff
= std::abs(V1
/V2
- 1.0);
150 Diff
= std::abs(V2
/V1
- 1.0);
152 Diff
= 0; // Both zero.
153 if (Diff
> RelTolerance
) {
155 raw_string_ostream(*ErrorMsg
)
156 << "Compared: " << V1
<< " and " << V2
<< '\n'
157 << "abs. diff = " << std::abs(V1
-V2
) << " rel.diff = " << Diff
<< '\n'
158 << "Out of tolerance: rel/abs: " << RelTolerance
<< '/'
165 // Otherwise, advance our read pointers to the end of the numbers.
166 F1P
= F1NumEnd
; F2P
= F2NumEnd
;
170 /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the
171 /// files match, 1 if they are different, and 2 if there is a file error. This
172 /// function differs from DiffFiles in that you can specify an absolute and
173 /// relative FP error that is allowed to exist. If you specify a string to fill
174 /// in for the error option, it will set the string to an error message if an
175 /// error occurs, allowing the caller to distinguish between a failed diff and a
176 /// file system error.
178 int llvm::DiffFilesWithTolerance(StringRef NameA
,
180 double AbsTol
, double RelTol
,
181 std::string
*Error
) {
182 // Now its safe to mmap the files into memory because both files
183 // have a non-zero size.
184 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> F1OrErr
= MemoryBuffer::getFile(NameA
);
185 if (std::error_code EC
= F1OrErr
.getError()) {
187 *Error
= EC
.message();
190 MemoryBuffer
&F1
= *F1OrErr
.get();
192 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> F2OrErr
= MemoryBuffer::getFile(NameB
);
193 if (std::error_code EC
= F2OrErr
.getError()) {
195 *Error
= EC
.message();
198 MemoryBuffer
&F2
= *F2OrErr
.get();
200 // Okay, now that we opened the files, scan them for the first difference.
201 const char *File1Start
= F1
.getBufferStart();
202 const char *File2Start
= F2
.getBufferStart();
203 const char *File1End
= F1
.getBufferEnd();
204 const char *File2End
= F2
.getBufferEnd();
205 const char *F1P
= File1Start
;
206 const char *F2P
= File2Start
;
207 uint64_t A_size
= F1
.getBufferSize();
208 uint64_t B_size
= F2
.getBufferSize();
210 // Are the buffers identical? Common case: Handle this efficiently.
211 if (A_size
== B_size
&&
212 std::memcmp(File1Start
, File2Start
, A_size
) == 0)
215 // Otherwise, we are done a tolerances are set.
216 if (AbsTol
== 0 && RelTol
== 0) {
218 *Error
= "Files differ without tolerance allowance";
219 return 1; // Files different!
222 bool CompareFailed
= false;
224 // Scan for the end of file or next difference.
225 while (F1P
< File1End
&& F2P
< File2End
&& *F1P
== *F2P
) {
230 if (F1P
>= File1End
|| F2P
>= File2End
) break;
232 // Okay, we must have found a difference. Backup to the start of the
233 // current number each stream is at so that we can compare from the
235 F1P
= BackupNumber(F1P
, File1Start
);
236 F2P
= BackupNumber(F2P
, File2Start
);
238 // Now that we are at the start of the numbers, compare them, exiting if
240 if (CompareNumbers(F1P
, F2P
, File1End
, File2End
, AbsTol
, RelTol
, Error
)) {
241 CompareFailed
= true;
246 // Okay, we reached the end of file. If both files are at the end, we
248 bool F1AtEnd
= F1P
>= File1End
;
249 bool F2AtEnd
= F2P
>= File2End
;
250 if (!CompareFailed
&& (!F1AtEnd
|| !F2AtEnd
)) {
251 // Else, we might have run off the end due to a number: backup and retry.
252 if (F1AtEnd
&& isNumberChar(F1P
[-1])) --F1P
;
253 if (F2AtEnd
&& isNumberChar(F2P
[-1])) --F2P
;
254 F1P
= BackupNumber(F1P
, File1Start
);
255 F2P
= BackupNumber(F2P
, File2Start
);
257 // Now that we are at the start of the numbers, compare them, exiting if
259 if (CompareNumbers(F1P
, F2P
, File1End
, File2End
, AbsTol
, RelTol
, Error
))
260 CompareFailed
= true;
262 // If we found the end, we succeeded.
263 if (F1P
< File1End
|| F2P
< File2End
)
264 CompareFailed
= true;
267 return CompareFailed
;
270 Expected
<FilePermissionsApplier
>
271 FilePermissionsApplier::create(StringRef InputFilename
) {
272 sys::fs::file_status Status
;
274 if (InputFilename
!= "-") {
275 if (auto EC
= sys::fs::status(InputFilename
, Status
))
276 return createFileError(InputFilename
, EC
);
278 Status
.permissions(static_cast<sys::fs::perms
>(0777));
281 return FilePermissionsApplier(InputFilename
, Status
);
284 Error
FilePermissionsApplier::apply(
285 StringRef OutputFilename
, bool CopyDates
,
286 std::optional
<sys::fs::perms
> OverwritePermissions
) {
287 sys::fs::file_status Status
= InputStatus
;
289 if (OverwritePermissions
)
290 Status
.permissions(*OverwritePermissions
);
294 // Writing to stdout should not be treated as an error here, just
295 // do not set access/modification times or permissions.
296 if (OutputFilename
== "-")
297 return Error::success();
299 if (std::error_code EC
= sys::fs::openFileForWrite(OutputFilename
, FD
,
300 sys::fs::CD_OpenExisting
))
301 return createFileError(OutputFilename
, EC
);
304 if (std::error_code EC
= sys::fs::setLastAccessAndModificationTime(
305 FD
, Status
.getLastAccessedTime(), Status
.getLastModificationTime()))
306 return createFileError(OutputFilename
, EC
);
308 sys::fs::file_status OStat
;
309 if (std::error_code EC
= sys::fs::status(FD
, OStat
))
310 return createFileError(OutputFilename
, EC
);
311 if (OStat
.type() == sys::fs::file_type::regular_file
) {
313 // Keep ownership if llvm-objcopy is called under root.
314 if (OutputFilename
== InputFilename
&& OStat
.getUser() == 0)
315 sys::fs::changeFileOwnership(FD
, Status
.getUser(), Status
.getGroup());
318 sys::fs::perms Perm
= Status
.permissions();
319 if (OutputFilename
!= InputFilename
)
320 Perm
= static_cast<sys::fs::perms
>(Perm
& ~sys::fs::getUmask() & ~06000);
322 if (std::error_code EC
= sys::fs::setPermissions(OutputFilename
, Perm
))
324 if (std::error_code EC
= sys::fs::setPermissions(FD
, Perm
))
326 return createFileError(OutputFilename
, EC
);
329 if (std::error_code EC
= sys::Process::SafelyCloseFileDescriptor(FD
))
330 return createFileError(OutputFilename
, EC
);
332 return Error::success();