Errno.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //===- Errno.cpp - errno support --------------------------------*- C++ -*-===//
  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 the errno wrappers.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Support/Errno.h"
  13. #include "llvm/Config/config.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. #include <string.h>
  16. #if HAVE_ERRNO_H
  17. #include <errno.h>
  18. #endif
  19. //===----------------------------------------------------------------------===//
  20. //=== WARNING: Implementation here must contain only TRULY operating system
  21. //=== independent code.
  22. //===----------------------------------------------------------------------===//
  23. namespace llvm {
  24. namespace sys {
  25. #if HAVE_ERRNO_H
  26. std::string StrError() {
  27. return StrError(errno);
  28. }
  29. #endif // HAVE_ERRNO_H
  30. std::string StrError(int errnum) {
  31. std::string str;
  32. if (errnum == 0)
  33. return str;
  34. #if defined(HAVE_STRERROR_R) || HAVE_DECL_STRERROR_S
  35. const int MaxErrStrLen = 2000;
  36. char buffer[MaxErrStrLen];
  37. buffer[0] = '\0';
  38. #endif
  39. #ifdef HAVE_STRERROR_R
  40. // strerror_r is thread-safe.
  41. #if defined(__GLIBC__) && defined(_GNU_SOURCE)
  42. // glibc defines its own incompatible version of strerror_r
  43. // which may not use the buffer supplied.
  44. str = strerror_r(errnum, buffer, MaxErrStrLen - 1);
  45. #else
  46. strerror_r(errnum, buffer, MaxErrStrLen - 1);
  47. str = buffer;
  48. #endif
  49. #elif HAVE_DECL_STRERROR_S // "Windows Secure API"
  50. strerror_s(buffer, MaxErrStrLen - 1, errnum);
  51. str = buffer;
  52. #elif defined(HAVE_STRERROR)
  53. // Copy the thread un-safe result of strerror into
  54. // the buffer as fast as possible to minimize impact
  55. // of collision of strerror in multiple threads.
  56. str = strerror(errnum);
  57. #else
  58. // Strange that this system doesn't even have strerror
  59. // but, oh well, just use a generic message
  60. raw_string_ostream stream(str);
  61. stream << "Error #" << errnum;
  62. stream.flush();
  63. #endif
  64. return str;
  65. }
  66. } // namespace sys
  67. } // namespace llvm