#include "butil/build_config.h"
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include "butil/scoped_lock.h"
namespace butil {
const int ERRNO_BEGIN = -32768;
const int ERRNO_END = 32768;
static const char* errno_desc[ERRNO_END - ERRNO_BEGIN] = {};
static pthread_mutex_t modify_desc_mutex = PTHREAD_MUTEX_INITIALIZER;
const size_t ERROR_BUFSIZE = 64;
__thread char tls_error_buf[ERROR_BUFSIZE];
int DescribeCustomizedErrno(
int error_code, const char* error_name, const char* description) {
BAIDU_SCOPED_LOCK(modify_desc_mutex);
if (error_code < ERRNO_BEGIN || error_code >= ERRNO_END) {
fprintf(stderr, "Fail to define %s(%d) which is out of range, abort.",
error_name, error_code);
_exit(1);
}
const char* desc = errno_desc[error_code - ERRNO_BEGIN];
if (desc) {
if (strcmp(desc, description) == 0) {
fprintf(stderr, "WARNING: Detected shared library loading\n");
return -1;
}
} else {
#if defined(OS_MACOSX)
const int rc = strerror_r(error_code, tls_error_buf, ERROR_BUFSIZE);
if (rc != EINVAL)
#else
desc = strerror_r(error_code, tls_error_buf, ERROR_BUFSIZE);
if (desc && strncmp(desc, "Unknown error", 13) != 0)
#endif
{
fprintf(stderr, "WARNING: Fail to define %s(%d) which is already defined as `%s'",
error_name, error_code, desc);
}
}
errno_desc[error_code - ERRNO_BEGIN] = description;
return 0;
}
}
const char* berror(int error_code) {
if (error_code == -1) {
return "General error -1";
}
if (error_code >= butil::ERRNO_BEGIN && error_code < butil::ERRNO_END) {
const char* s = butil::errno_desc[error_code - butil::ERRNO_BEGIN];
if (s) {
return s;
}
#if defined(OS_MACOSX)
const int rc = strerror_r(error_code, butil::tls_error_buf, butil::ERROR_BUFSIZE);
if (rc == 0 || rc == ERANGE) {
return butil::tls_error_buf;
}
#else
s = strerror_r(error_code, butil::tls_error_buf, butil::ERROR_BUFSIZE);
if (s) {
return s;
}
#endif
}
snprintf(butil::tls_error_buf, butil::ERROR_BUFSIZE,
"Unknown error %d", error_code);
return butil::tls_error_buf;
}
const char* berror() {
return berror(errno);
}