xref: /freebsd-src/contrib/llvm-project/llvm/lib/Support/FileUtilities.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
10b57cec5SDimitry Andric //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements a family of utility functions which are useful for doing
100b57cec5SDimitry Andric // various things with files.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/Support/FileUtilities.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
165ffd83dbSDimitry Andric #include "llvm/ADT/StringExtras.h"
178bcb0991SDimitry Andric #include "llvm/Support/Error.h"
180b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
190b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
2081ad6265SDimitry Andric #include "llvm/Support/Process.h"
210b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
22bdd1243dSDimitry Andric #include <cmath>
230b57cec5SDimitry Andric #include <cstdint>
240b57cec5SDimitry Andric #include <cstdlib>
250b57cec5SDimitry Andric #include <cstring>
260b57cec5SDimitry Andric #include <memory>
270b57cec5SDimitry Andric #include <system_error>
280b57cec5SDimitry Andric 
290b57cec5SDimitry Andric using namespace llvm;
300b57cec5SDimitry Andric 
isSignedChar(char C)310b57cec5SDimitry Andric static bool isSignedChar(char C) {
320b57cec5SDimitry Andric   return (C == '+' || C == '-');
330b57cec5SDimitry Andric }
340b57cec5SDimitry Andric 
isExponentChar(char C)350b57cec5SDimitry Andric static bool isExponentChar(char C) {
360b57cec5SDimitry Andric   switch (C) {
370b57cec5SDimitry Andric   case 'D':  // Strange exponential notation.
380b57cec5SDimitry Andric   case 'd':  // Strange exponential notation.
390b57cec5SDimitry Andric   case 'e':
400b57cec5SDimitry Andric   case 'E': return true;
410b57cec5SDimitry Andric   default: return false;
420b57cec5SDimitry Andric   }
430b57cec5SDimitry Andric }
440b57cec5SDimitry Andric 
isNumberChar(char C)450b57cec5SDimitry Andric static bool isNumberChar(char C) {
460b57cec5SDimitry Andric   switch (C) {
470b57cec5SDimitry Andric   case '0': case '1': case '2': case '3': case '4':
480b57cec5SDimitry Andric   case '5': case '6': case '7': case '8': case '9':
490b57cec5SDimitry Andric   case '.': return true;
500b57cec5SDimitry Andric   default: return isSignedChar(C) || isExponentChar(C);
510b57cec5SDimitry Andric   }
520b57cec5SDimitry Andric }
530b57cec5SDimitry Andric 
BackupNumber(const char * Pos,const char * FirstChar)540b57cec5SDimitry Andric static const char *BackupNumber(const char *Pos, const char *FirstChar) {
550b57cec5SDimitry Andric   // If we didn't stop in the middle of a number, don't backup.
560b57cec5SDimitry Andric   if (!isNumberChar(*Pos)) return Pos;
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric   // Otherwise, return to the start of the number.
590b57cec5SDimitry Andric   bool HasPeriod = false;
600b57cec5SDimitry Andric   while (Pos > FirstChar && isNumberChar(Pos[-1])) {
610b57cec5SDimitry Andric     // Backup over at most one period.
620b57cec5SDimitry Andric     if (Pos[-1] == '.') {
630b57cec5SDimitry Andric       if (HasPeriod)
640b57cec5SDimitry Andric         break;
650b57cec5SDimitry Andric       HasPeriod = true;
660b57cec5SDimitry Andric     }
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric     --Pos;
690b57cec5SDimitry Andric     if (Pos > FirstChar && isSignedChar(Pos[0]) && !isExponentChar(Pos[-1]))
700b57cec5SDimitry Andric       break;
710b57cec5SDimitry Andric   }
720b57cec5SDimitry Andric   return Pos;
730b57cec5SDimitry Andric }
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric /// EndOfNumber - Return the first character that is not part of the specified
760b57cec5SDimitry Andric /// number.  This assumes that the buffer is null terminated, so it won't fall
770b57cec5SDimitry Andric /// off the end.
EndOfNumber(const char * Pos)780b57cec5SDimitry Andric static const char *EndOfNumber(const char *Pos) {
790b57cec5SDimitry Andric   while (isNumberChar(*Pos))
800b57cec5SDimitry Andric     ++Pos;
810b57cec5SDimitry Andric   return Pos;
820b57cec5SDimitry Andric }
830b57cec5SDimitry Andric 
840b57cec5SDimitry 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)850b57cec5SDimitry Andric static bool CompareNumbers(const char *&F1P, const char *&F2P,
860b57cec5SDimitry Andric                            const char *F1End, const char *F2End,
870b57cec5SDimitry Andric                            double AbsTolerance, double RelTolerance,
880b57cec5SDimitry Andric                            std::string *ErrorMsg) {
890b57cec5SDimitry Andric   const char *F1NumEnd, *F2NumEnd;
900b57cec5SDimitry Andric   double V1 = 0.0, V2 = 0.0;
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   // If one of the positions is at a space and the other isn't, chomp up 'til
930b57cec5SDimitry Andric   // the end of the space.
945ffd83dbSDimitry Andric   while (isSpace(static_cast<unsigned char>(*F1P)) && F1P != F1End)
950b57cec5SDimitry Andric     ++F1P;
965ffd83dbSDimitry Andric   while (isSpace(static_cast<unsigned char>(*F2P)) && F2P != F2End)
970b57cec5SDimitry Andric     ++F2P;
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric   // If we stop on numbers, compare their difference.
1000b57cec5SDimitry Andric   if (!isNumberChar(*F1P) || !isNumberChar(*F2P)) {
1010b57cec5SDimitry Andric     // The diff failed.
1020b57cec5SDimitry Andric     F1NumEnd = F1P;
1030b57cec5SDimitry Andric     F2NumEnd = F2P;
1040b57cec5SDimitry Andric   } else {
1050b57cec5SDimitry Andric     // Note that some ugliness is built into this to permit support for numbers
1060b57cec5SDimitry Andric     // that use "D" or "d" as their exponential marker, e.g. "1.234D45".  This
1070b57cec5SDimitry Andric     // occurs in 200.sixtrack in spec2k.
1080b57cec5SDimitry Andric     V1 = strtod(F1P, const_cast<char**>(&F1NumEnd));
1090b57cec5SDimitry Andric     V2 = strtod(F2P, const_cast<char**>(&F2NumEnd));
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric     if (*F1NumEnd == 'D' || *F1NumEnd == 'd') {
1120b57cec5SDimitry Andric       // Copy string into tmp buffer to replace the 'D' with an 'e'.
1130b57cec5SDimitry Andric       SmallString<200> StrTmp(F1P, EndOfNumber(F1NumEnd)+1);
1140b57cec5SDimitry Andric       // Strange exponential notation!
1150b57cec5SDimitry Andric       StrTmp[static_cast<unsigned>(F1NumEnd-F1P)] = 'e';
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric       V1 = strtod(&StrTmp[0], const_cast<char**>(&F1NumEnd));
1180b57cec5SDimitry Andric       F1NumEnd = F1P + (F1NumEnd-&StrTmp[0]);
1190b57cec5SDimitry Andric     }
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric     if (*F2NumEnd == 'D' || *F2NumEnd == 'd') {
1220b57cec5SDimitry Andric       // Copy string into tmp buffer to replace the 'D' with an 'e'.
1230b57cec5SDimitry Andric       SmallString<200> StrTmp(F2P, EndOfNumber(F2NumEnd)+1);
1240b57cec5SDimitry Andric       // Strange exponential notation!
1250b57cec5SDimitry Andric       StrTmp[static_cast<unsigned>(F2NumEnd-F2P)] = 'e';
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric       V2 = strtod(&StrTmp[0], const_cast<char**>(&F2NumEnd));
1280b57cec5SDimitry Andric       F2NumEnd = F2P + (F2NumEnd-&StrTmp[0]);
1290b57cec5SDimitry Andric     }
1300b57cec5SDimitry Andric   }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric   if (F1NumEnd == F1P || F2NumEnd == F2P) {
1330b57cec5SDimitry Andric     if (ErrorMsg) {
1340b57cec5SDimitry Andric       *ErrorMsg = "FP Comparison failed, not a numeric difference between '";
1350b57cec5SDimitry Andric       *ErrorMsg += F1P[0];
1360b57cec5SDimitry Andric       *ErrorMsg += "' and '";
1370b57cec5SDimitry Andric       *ErrorMsg += F2P[0];
1380b57cec5SDimitry Andric       *ErrorMsg += "'";
1390b57cec5SDimitry Andric     }
1400b57cec5SDimitry Andric     return true;
1410b57cec5SDimitry Andric   }
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric   // Check to see if these are inside the absolute tolerance
1440b57cec5SDimitry Andric   if (AbsTolerance < std::abs(V1-V2)) {
1450b57cec5SDimitry Andric     // Nope, check the relative tolerance...
1460b57cec5SDimitry Andric     double Diff;
1470b57cec5SDimitry Andric     if (V2)
1480b57cec5SDimitry Andric       Diff = std::abs(V1/V2 - 1.0);
1490b57cec5SDimitry Andric     else if (V1)
1500b57cec5SDimitry Andric       Diff = std::abs(V2/V1 - 1.0);
1510b57cec5SDimitry Andric     else
1520b57cec5SDimitry Andric       Diff = 0;  // Both zero.
1530b57cec5SDimitry Andric     if (Diff > RelTolerance) {
1540b57cec5SDimitry Andric       if (ErrorMsg) {
1550b57cec5SDimitry Andric         raw_string_ostream(*ErrorMsg)
1560b57cec5SDimitry Andric           << "Compared: " << V1 << " and " << V2 << '\n'
1570b57cec5SDimitry Andric           << "abs. diff = " << std::abs(V1-V2) << " rel.diff = " << Diff << '\n'
1580b57cec5SDimitry Andric           << "Out of tolerance: rel/abs: " << RelTolerance << '/'
1590b57cec5SDimitry Andric           << AbsTolerance;
1600b57cec5SDimitry Andric       }
1610b57cec5SDimitry Andric       return true;
1620b57cec5SDimitry Andric     }
1630b57cec5SDimitry Andric   }
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   // Otherwise, advance our read pointers to the end of the numbers.
1660b57cec5SDimitry Andric   F1P = F1NumEnd;  F2P = F2NumEnd;
1670b57cec5SDimitry Andric   return false;
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the
1710b57cec5SDimitry Andric /// files match, 1 if they are different, and 2 if there is a file error.  This
172*06c3fb27SDimitry Andric /// function differs from DiffFiles in that you can specify an absolute and
1730b57cec5SDimitry Andric /// relative FP error that is allowed to exist.  If you specify a string to fill
1740b57cec5SDimitry Andric /// in for the error option, it will set the string to an error message if an
1750b57cec5SDimitry Andric /// error occurs, allowing the caller to distinguish between a failed diff and a
1760b57cec5SDimitry Andric /// file system error.
1770b57cec5SDimitry Andric ///
DiffFilesWithTolerance(StringRef NameA,StringRef NameB,double AbsTol,double RelTol,std::string * Error)1780b57cec5SDimitry Andric int llvm::DiffFilesWithTolerance(StringRef NameA,
1790b57cec5SDimitry Andric                                  StringRef NameB,
1800b57cec5SDimitry Andric                                  double AbsTol, double RelTol,
1810b57cec5SDimitry Andric                                  std::string *Error) {
1820b57cec5SDimitry Andric   // Now its safe to mmap the files into memory because both files
1830b57cec5SDimitry Andric   // have a non-zero size.
1840b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> F1OrErr = MemoryBuffer::getFile(NameA);
1850b57cec5SDimitry Andric   if (std::error_code EC = F1OrErr.getError()) {
1860b57cec5SDimitry Andric     if (Error)
1870b57cec5SDimitry Andric       *Error = EC.message();
1880b57cec5SDimitry Andric     return 2;
1890b57cec5SDimitry Andric   }
1900b57cec5SDimitry Andric   MemoryBuffer &F1 = *F1OrErr.get();
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> F2OrErr = MemoryBuffer::getFile(NameB);
1930b57cec5SDimitry Andric   if (std::error_code EC = F2OrErr.getError()) {
1940b57cec5SDimitry Andric     if (Error)
1950b57cec5SDimitry Andric       *Error = EC.message();
1960b57cec5SDimitry Andric     return 2;
1970b57cec5SDimitry Andric   }
1980b57cec5SDimitry Andric   MemoryBuffer &F2 = *F2OrErr.get();
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   // Okay, now that we opened the files, scan them for the first difference.
2010b57cec5SDimitry Andric   const char *File1Start = F1.getBufferStart();
2020b57cec5SDimitry Andric   const char *File2Start = F2.getBufferStart();
2030b57cec5SDimitry Andric   const char *File1End = F1.getBufferEnd();
2040b57cec5SDimitry Andric   const char *File2End = F2.getBufferEnd();
2050b57cec5SDimitry Andric   const char *F1P = File1Start;
2060b57cec5SDimitry Andric   const char *F2P = File2Start;
2070b57cec5SDimitry Andric   uint64_t A_size = F1.getBufferSize();
2080b57cec5SDimitry Andric   uint64_t B_size = F2.getBufferSize();
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric   // Are the buffers identical?  Common case: Handle this efficiently.
2110b57cec5SDimitry Andric   if (A_size == B_size &&
2120b57cec5SDimitry Andric       std::memcmp(File1Start, File2Start, A_size) == 0)
2130b57cec5SDimitry Andric     return 0;
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   // Otherwise, we are done a tolerances are set.
2160b57cec5SDimitry Andric   if (AbsTol == 0 && RelTol == 0) {
2170b57cec5SDimitry Andric     if (Error)
2180b57cec5SDimitry Andric       *Error = "Files differ without tolerance allowance";
2190b57cec5SDimitry Andric     return 1;   // Files different!
2200b57cec5SDimitry Andric   }
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric   bool CompareFailed = false;
2230b57cec5SDimitry Andric   while (true) {
2240b57cec5SDimitry Andric     // Scan for the end of file or next difference.
2250b57cec5SDimitry Andric     while (F1P < File1End && F2P < File2End && *F1P == *F2P) {
2260b57cec5SDimitry Andric       ++F1P;
2270b57cec5SDimitry Andric       ++F2P;
2280b57cec5SDimitry Andric     }
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric     if (F1P >= File1End || F2P >= File2End) break;
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric     // Okay, we must have found a difference.  Backup to the start of the
2330b57cec5SDimitry Andric     // current number each stream is at so that we can compare from the
2340b57cec5SDimitry Andric     // beginning.
2350b57cec5SDimitry Andric     F1P = BackupNumber(F1P, File1Start);
2360b57cec5SDimitry Andric     F2P = BackupNumber(F2P, File2Start);
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric     // Now that we are at the start of the numbers, compare them, exiting if
2390b57cec5SDimitry Andric     // they don't match.
2400b57cec5SDimitry Andric     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) {
2410b57cec5SDimitry Andric       CompareFailed = true;
2420b57cec5SDimitry Andric       break;
2430b57cec5SDimitry Andric     }
2440b57cec5SDimitry Andric   }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   // Okay, we reached the end of file.  If both files are at the end, we
2470b57cec5SDimitry Andric   // succeeded.
2480b57cec5SDimitry Andric   bool F1AtEnd = F1P >= File1End;
2490b57cec5SDimitry Andric   bool F2AtEnd = F2P >= File2End;
2500b57cec5SDimitry Andric   if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) {
2510b57cec5SDimitry Andric     // Else, we might have run off the end due to a number: backup and retry.
2520b57cec5SDimitry Andric     if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;
2530b57cec5SDimitry Andric     if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;
2540b57cec5SDimitry Andric     F1P = BackupNumber(F1P, File1Start);
2550b57cec5SDimitry Andric     F2P = BackupNumber(F2P, File2Start);
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     // Now that we are at the start of the numbers, compare them, exiting if
2580b57cec5SDimitry Andric     // they don't match.
2590b57cec5SDimitry Andric     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error))
2600b57cec5SDimitry Andric       CompareFailed = true;
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric     // If we found the end, we succeeded.
2630b57cec5SDimitry Andric     if (F1P < File1End || F2P < File2End)
2640b57cec5SDimitry Andric       CompareFailed = true;
2650b57cec5SDimitry Andric   }
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   return CompareFailed;
2680b57cec5SDimitry Andric }
2698bcb0991SDimitry Andric 
27081ad6265SDimitry Andric Expected<FilePermissionsApplier>
create(StringRef InputFilename)27181ad6265SDimitry Andric FilePermissionsApplier::create(StringRef InputFilename) {
27281ad6265SDimitry Andric   sys::fs::file_status Status;
27381ad6265SDimitry Andric 
27481ad6265SDimitry Andric   if (InputFilename != "-") {
27581ad6265SDimitry Andric     if (auto EC = sys::fs::status(InputFilename, Status))
27681ad6265SDimitry Andric       return createFileError(InputFilename, EC);
27781ad6265SDimitry Andric   } else {
27881ad6265SDimitry Andric     Status.permissions(static_cast<sys::fs::perms>(0777));
27981ad6265SDimitry Andric   }
28081ad6265SDimitry Andric 
28181ad6265SDimitry Andric   return FilePermissionsApplier(InputFilename, Status);
28281ad6265SDimitry Andric }
28381ad6265SDimitry Andric 
apply(StringRef OutputFilename,bool CopyDates,std::optional<sys::fs::perms> OverwritePermissions)28481ad6265SDimitry Andric Error FilePermissionsApplier::apply(
28581ad6265SDimitry Andric     StringRef OutputFilename, bool CopyDates,
286bdd1243dSDimitry Andric     std::optional<sys::fs::perms> OverwritePermissions) {
28781ad6265SDimitry Andric   sys::fs::file_status Status = InputStatus;
28881ad6265SDimitry Andric 
28981ad6265SDimitry Andric   if (OverwritePermissions)
29081ad6265SDimitry Andric     Status.permissions(*OverwritePermissions);
29181ad6265SDimitry Andric 
29281ad6265SDimitry Andric   int FD = 0;
29381ad6265SDimitry Andric 
29481ad6265SDimitry Andric   // Writing to stdout should not be treated as an error here, just
29581ad6265SDimitry Andric   // do not set access/modification times or permissions.
29681ad6265SDimitry Andric   if (OutputFilename == "-")
29781ad6265SDimitry Andric     return Error::success();
29881ad6265SDimitry Andric 
29981ad6265SDimitry Andric   if (std::error_code EC = sys::fs::openFileForWrite(OutputFilename, FD,
30081ad6265SDimitry Andric                                                      sys::fs::CD_OpenExisting))
30181ad6265SDimitry Andric     return createFileError(OutputFilename, EC);
30281ad6265SDimitry Andric 
30381ad6265SDimitry Andric   if (CopyDates)
30481ad6265SDimitry Andric     if (std::error_code EC = sys::fs::setLastAccessAndModificationTime(
30581ad6265SDimitry Andric             FD, Status.getLastAccessedTime(), Status.getLastModificationTime()))
30681ad6265SDimitry Andric       return createFileError(OutputFilename, EC);
30781ad6265SDimitry Andric 
30881ad6265SDimitry Andric   sys::fs::file_status OStat;
30981ad6265SDimitry Andric   if (std::error_code EC = sys::fs::status(FD, OStat))
31081ad6265SDimitry Andric     return createFileError(OutputFilename, EC);
31181ad6265SDimitry Andric   if (OStat.type() == sys::fs::file_type::regular_file) {
31281ad6265SDimitry Andric #ifndef _WIN32
31381ad6265SDimitry Andric     // Keep ownership if llvm-objcopy is called under root.
31481ad6265SDimitry Andric     if (OutputFilename == InputFilename && OStat.getUser() == 0)
31581ad6265SDimitry Andric       sys::fs::changeFileOwnership(FD, Status.getUser(), Status.getGroup());
31681ad6265SDimitry Andric #endif
31781ad6265SDimitry Andric 
31881ad6265SDimitry Andric     sys::fs::perms Perm = Status.permissions();
31981ad6265SDimitry Andric     if (OutputFilename != InputFilename)
32081ad6265SDimitry Andric       Perm = static_cast<sys::fs::perms>(Perm & ~sys::fs::getUmask() & ~06000);
32181ad6265SDimitry Andric #ifdef _WIN32
32281ad6265SDimitry Andric     if (std::error_code EC = sys::fs::setPermissions(OutputFilename, Perm))
32381ad6265SDimitry Andric #else
32481ad6265SDimitry Andric     if (std::error_code EC = sys::fs::setPermissions(FD, Perm))
32581ad6265SDimitry Andric #endif
32681ad6265SDimitry Andric       return createFileError(OutputFilename, EC);
32781ad6265SDimitry Andric   }
32881ad6265SDimitry Andric 
32981ad6265SDimitry Andric   if (std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD))
33081ad6265SDimitry Andric     return createFileError(OutputFilename, EC);
33181ad6265SDimitry Andric 
33281ad6265SDimitry Andric   return Error::success();
33381ad6265SDimitry Andric }
334