LLVM API Documentation

FileUtilities.cpp

Go to the documentation of this file.
00001 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a family of utility functions which are useful for doing
00011 // various things with files.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Support/FileUtilities.h"
00016 #include "llvm/System/Path.h"
00017 #include "llvm/Support/MemoryBuffer.h"
00018 #include "llvm/ADT/OwningPtr.h"
00019 #include "llvm/ADT/SmallString.h"
00020 #include "llvm/ADT/StringExtras.h"
00021 #include <cstdlib>
00022 #include <cstring>
00023 #include <cctype>
00024 using namespace llvm;
00025 
00026 static bool isSignedChar(char C) {
00027   return (C == '+' || C == '-');
00028 }
00029 
00030 static bool isExponentChar(char C) {
00031   switch (C) {
00032   case 'D':  // Strange exponential notation.
00033   case 'd':  // Strange exponential notation.
00034   case 'e':
00035   case 'E': return true;
00036   default: return false;
00037   }
00038 }
00039 
00040 static bool isNumberChar(char C) {
00041   switch (C) {
00042   case '0': case '1': case '2': case '3': case '4':
00043   case '5': case '6': case '7': case '8': case '9':
00044   case '.': return true;
00045   default: return isSignedChar(C) || isExponentChar(C);
00046   }
00047 }
00048 
00049 static const char *BackupNumber(const char *Pos, const char *FirstChar) {
00050   // If we didn't stop in the middle of a number, don't backup.
00051   if (!isNumberChar(*Pos)) return Pos;
00052 
00053   // Otherwise, return to the start of the number.
00054   while (Pos > FirstChar && isNumberChar(Pos[-1])) {
00055     --Pos;
00056     if (Pos > FirstChar && isSignedChar(Pos[0]) && !isExponentChar(Pos[-1]))
00057       break;
00058   }
00059   return Pos;
00060 }
00061 
00062 /// EndOfNumber - Return the first character that is not part of the specified
00063 /// number.  This assumes that the buffer is null terminated, so it won't fall
00064 /// off the end.
00065 static const char *EndOfNumber(const char *Pos) {
00066   while (isNumberChar(*Pos))
00067     ++Pos;
00068   return Pos;
00069 }
00070 
00071 /// CompareNumbers - compare two numbers, returning true if they are different.
00072 static bool CompareNumbers(const char *&F1P, const char *&F2P,
00073                            const char *F1End, const char *F2End,
00074                            double AbsTolerance, double RelTolerance,
00075                            std::string *ErrorMsg) {
00076   const char *F1NumEnd, *F2NumEnd;
00077   double V1 = 0.0, V2 = 0.0;
00078 
00079   // If one of the positions is at a space and the other isn't, chomp up 'til
00080   // the end of the space.
00081   while (isspace(*F1P) && F1P != F1End)
00082     ++F1P;
00083   while (isspace(*F2P) && F2P != F2End)
00084     ++F2P;
00085 
00086   // If we stop on numbers, compare their difference.
00087   if (!isNumberChar(*F1P) || !isNumberChar(*F2P)) {
00088     // The diff failed.
00089     F1NumEnd = F1P;
00090     F2NumEnd = F2P;
00091   } else {
00092     // Note that some ugliness is built into this to permit support for numbers
00093     // that use "D" or "d" as their exponential marker, e.g. "1.234D45".  This
00094     // occurs in 200.sixtrack in spec2k.
00095     V1 = strtod(F1P, const_cast<char**>(&F1NumEnd));
00096     V2 = strtod(F2P, const_cast<char**>(&F2NumEnd));
00097 
00098     if (*F1NumEnd == 'D' || *F1NumEnd == 'd') {
00099       // Copy string into tmp buffer to replace the 'D' with an 'e'.
00100       SmallString<200> StrTmp(F1P, EndOfNumber(F1NumEnd)+1);
00101       // Strange exponential notation!
00102       StrTmp[static_cast<unsigned>(F1NumEnd-F1P)] = 'e';
00103       
00104       V1 = strtod(&StrTmp[0], const_cast<char**>(&F1NumEnd));
00105       F1NumEnd = F1P + (F1NumEnd-&StrTmp[0]);
00106     }
00107     
00108     if (*F2NumEnd == 'D' || *F2NumEnd == 'd') {
00109       // Copy string into tmp buffer to replace the 'D' with an 'e'.
00110       SmallString<200> StrTmp(F2P, EndOfNumber(F2NumEnd)+1);
00111       // Strange exponential notation!
00112       StrTmp[static_cast<unsigned>(F2NumEnd-F2P)] = 'e';
00113       
00114       V2 = strtod(&StrTmp[0], const_cast<char**>(&F2NumEnd));
00115       F2NumEnd = F2P + (F2NumEnd-&StrTmp[0]);
00116     }
00117   }
00118 
00119   if (F1NumEnd == F1P || F2NumEnd == F2P) {
00120     if (ErrorMsg) {
00121       *ErrorMsg = "FP Comparison failed, not a numeric difference between '";
00122       *ErrorMsg += F1P[0];
00123       *ErrorMsg += "' and '";
00124       *ErrorMsg += F2P[0];
00125       *ErrorMsg += "'";
00126     }
00127     return true;
00128   }
00129 
00130   // Check to see if these are inside the absolute tolerance
00131   if (AbsTolerance < std::abs(V1-V2)) {
00132     // Nope, check the relative tolerance...
00133     double Diff;
00134     if (V2)
00135       Diff = std::abs(V1/V2 - 1.0);
00136     else if (V1)
00137       Diff = std::abs(V2/V1 - 1.0);
00138     else
00139       Diff = 0;  // Both zero.
00140     if (Diff > RelTolerance) {
00141       if (ErrorMsg) {
00142         *ErrorMsg = "Compared: " + ftostr(V1) + " and " + ftostr(V2) + "\n";
00143         *ErrorMsg += "abs. diff = " + ftostr(std::abs(V1-V2)) + 
00144                      " rel.diff = " + ftostr(Diff) + "\n";
00145         *ErrorMsg += "Out of tolerance: rel/abs: " + ftostr(RelTolerance) +
00146                      "/" + ftostr(AbsTolerance);
00147       }
00148       return true;
00149     }
00150   }
00151 
00152   // Otherwise, advance our read pointers to the end of the numbers.
00153   F1P = F1NumEnd;  F2P = F2NumEnd;
00154   return false;
00155 }
00156 
00157 /// DiffFilesWithTolerance - Compare the two files specified, returning 0 if the
00158 /// files match, 1 if they are different, and 2 if there is a file error.  This
00159 /// function differs from DiffFiles in that you can specify an absolete and
00160 /// relative FP error that is allowed to exist.  If you specify a string to fill
00161 /// in for the error option, it will set the string to an error message if an
00162 /// error occurs, allowing the caller to distinguish between a failed diff and a
00163 /// file system error.
00164 ///
00165 int llvm::DiffFilesWithTolerance(const sys::PathWithStatus &FileA,
00166                                  const sys::PathWithStatus &FileB,
00167                                  double AbsTol, double RelTol,
00168                                  std::string *Error) {
00169   const sys::FileStatus *FileAStat = FileA.getFileStatus(false, Error);
00170   if (!FileAStat)
00171     return 2;
00172   const sys::FileStatus *FileBStat = FileB.getFileStatus(false, Error);
00173   if (!FileBStat)
00174     return 2;
00175 
00176   // Check for zero length files because some systems croak when you try to
00177   // mmap an empty file.
00178   size_t A_size = FileAStat->getSize();
00179   size_t B_size = FileBStat->getSize();
00180 
00181   // If they are both zero sized then they're the same
00182   if (A_size == 0 && B_size == 0)
00183     return 0;
00184 
00185   // If only one of them is zero sized then they can't be the same
00186   if ((A_size == 0 || B_size == 0)) {
00187     if (Error)
00188       *Error = "Files differ: one is zero-sized, the other isn't";
00189     return 1;
00190   }
00191 
00192   // Now its safe to mmap the files into memory becasue both files
00193   // have a non-zero size.
00194   OwningPtr<MemoryBuffer> F1(MemoryBuffer::getFile(FileA.c_str(), Error));
00195   OwningPtr<MemoryBuffer> F2(MemoryBuffer::getFile(FileB.c_str(), Error));
00196   if (F1 == 0 || F2 == 0)
00197     return 2;
00198   
00199   // Okay, now that we opened the files, scan them for the first difference.
00200   const char *File1Start = F1->getBufferStart();
00201   const char *File2Start = F2->getBufferStart();
00202   const char *File1End = F1->getBufferEnd();
00203   const char *File2End = F2->getBufferEnd();
00204   const char *F1P = File1Start;
00205   const char *F2P = File2Start;
00206 
00207   if (A_size == B_size) {
00208     // Are the buffers identical?  Common case: Handle this efficiently.
00209     if (std::memcmp(File1Start, File2Start, A_size) == 0)
00210       return 0;
00211 
00212     if (AbsTol == 0 && RelTol == 0) {
00213       if (Error)
00214         *Error = "Files differ without tolerance allowance";
00215       return 1;   // Files different!
00216     }
00217   }
00218 
00219   bool CompareFailed = false;
00220   while (1) {
00221     // Scan for the end of file or next difference.
00222     while (F1P < File1End && F2P < File2End && *F1P == *F2P)
00223       ++F1P, ++F2P;
00224 
00225     if (F1P >= File1End || F2P >= File2End) break;
00226 
00227     // Okay, we must have found a difference.  Backup to the start of the
00228     // current number each stream is at so that we can compare from the
00229     // beginning.
00230     F1P = BackupNumber(F1P, File1Start);
00231     F2P = BackupNumber(F2P, File2Start);
00232 
00233     // Now that we are at the start of the numbers, compare them, exiting if
00234     // they don't match.
00235     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) {
00236       CompareFailed = true;
00237       break;
00238     }
00239   }
00240 
00241   // Okay, we reached the end of file.  If both files are at the end, we
00242   // succeeded.
00243   bool F1AtEnd = F1P >= File1End;
00244   bool F2AtEnd = F2P >= File2End;
00245   if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) {
00246     // Else, we might have run off the end due to a number: backup and retry.
00247     if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;
00248     if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;
00249     F1P = BackupNumber(F1P, File1Start);
00250     F2P = BackupNumber(F2P, File2Start);
00251 
00252     // Now that we are at the start of the numbers, compare them, exiting if
00253     // they don't match.
00254     if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error))
00255       CompareFailed = true;
00256 
00257     // If we found the end, we succeeded.
00258     if (F1P < File1End || F2P < File2End)
00259       CompareFailed = true;
00260   }
00261 
00262   return CompareFailed;
00263 }



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.