FileUtilities.cpp 11 KB

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