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