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