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 <cstring> 16 #include <errno.h> 17 18 //===----------------------------------------------------------------------===// 19 //=== WARNING: Implementation here must contain only TRULY operating system 20 //=== independent code. 21 //===----------------------------------------------------------------------===// 22 23 namespace llvm { 24 namespace sys { 25 26 std::string StrError() { 27 return StrError(errno); 28 } 29 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 40 #ifdef HAVE_STRERROR_R 41 // strerror_r is thread-safe. 42 #if defined(__GLIBC__) && defined(_GNU_SOURCE) 43 // glibc defines its own incompatible version of strerror_r 44 // which may not use the buffer supplied. 45 str = strerror_r(errnum, buffer, MaxErrStrLen - 1); 46 #else 47 strerror_r(errnum, buffer, MaxErrStrLen - 1); 48 str = buffer; 49 #endif 50 #elif HAVE_DECL_STRERROR_S // "Windows Secure API" 51 strerror_s(buffer, MaxErrStrLen - 1, errnum); 52 str = buffer; 53 #else 54 // Copy the thread un-safe result of strerror into 55 // the buffer as fast as possible to minimize impact 56 // of collision of strerror in multiple threads. 57 str = strerror(errnum); 58 #endif 59 return str; 60 } 61 62 } // namespace sys 63 } // namespace llvm 64