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