• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* $OpenBSD: strerror_r.c,v 1.6 2005/08/08 08:05:37 espie Exp $ */
2 /* Public Domain <marc@snafu.org> */
3 
4 #include <errno.h>
5 #include <limits.h>
6 #include <signal.h>
7 #include <stdio.h>
8 #include <string.h>
9 
10 #include "private/ErrnoRestorer.h"
11 
12 struct Pair {
13   int code;
14   const char* msg;
15 };
16 
__code_string_lookup(const Pair * strings,int code)17 static const char* __code_string_lookup(const Pair* strings, int code) {
18   for (size_t i = 0; strings[i].msg != NULL; ++i) {
19     if (strings[i].code == code) {
20       return strings[i].msg;
21     }
22   }
23   return NULL;
24 }
25 
26 static const Pair _sys_error_strings[] = {
27 #define  __BIONIC_ERRDEF(x,y,z)  { x, z },
28 #include <sys/_errdefs.h>
29   { 0, NULL }
30 };
31 
__strerror_lookup(int error_number)32 extern "C" __LIBC_HIDDEN__ const char* __strerror_lookup(int error_number) {
33   return __code_string_lookup(_sys_error_strings, error_number);
34 }
35 
36 static const Pair _sys_signal_strings[] = {
37 #define  __BIONIC_SIGDEF(x,y,z)  { y, z },
38 #include <sys/_sigdefs.h>
39   { 0, NULL }
40 };
41 
__strsignal_lookup(int signal_number)42 extern "C" __LIBC_HIDDEN__ const char* __strsignal_lookup(int signal_number) {
43   return __code_string_lookup(_sys_signal_strings, signal_number);
44 }
45 
strerror_r(int error_number,char * buf,size_t buf_len)46 int strerror_r(int error_number, char* buf, size_t buf_len) {
47   ErrnoRestorer errno_restorer;
48   size_t length;
49 
50   const char* error_name = __strerror_lookup(error_number);
51   if (error_name != NULL) {
52     length = snprintf(buf, buf_len, "%s", error_name);
53   } else {
54     length = snprintf(buf, buf_len, "Unknown error %d", error_number);
55   }
56   if (length >= buf_len) {
57     errno_restorer.override(ERANGE);
58     return -1;
59   }
60 
61   return 0;
62 }
63 
__strsignal(int signal_number,char * buf,size_t buf_len)64 extern "C" __LIBC_HIDDEN__ const char* __strsignal(int signal_number, char* buf, size_t buf_len) {
65   const char* signal_name = __strsignal_lookup(signal_number);
66   if (signal_name != NULL) {
67     return signal_name;
68   }
69 
70   const char* prefix = "Unknown";
71   if (signal_number >= SIGRTMIN && signal_number <= SIGRTMAX) {
72     prefix = "Real-time";
73     signal_number -= SIGRTMIN;
74   }
75   size_t length = snprintf(buf, buf_len, "%s signal %d", prefix, signal_number);
76   if (length >= buf_len) {
77     return NULL;
78   }
79   return buf;
80 }
81