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