xref: /netbsd-src/external/bsd/ntp/dist/libntp/lib/isc/unix/strerror.c (revision eabc0478de71e4e011a5b4e0392741e01d491794)
1 /*	$NetBSD: strerror.c,v 1.2 2024/08/18 20:47:16 christos Exp $	*/
2 
3 /*
4  * Copyright (C) 2004, 2005, 2007, 2009  Internet Systems Consortium, Inc. ("ISC")
5  * Copyright (C) 2001  Internet Software Consortium.
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17  * PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /* Id: strerror.c,v 1.10 2009/02/16 23:48:04 tbox Exp  */
21 
22 /*! \file */
23 
24 #include <config.h>
25 
26 #include <stdio.h>
27 #include <string.h>
28 
29 #include <isc/mutex.h>
30 #include <isc/once.h>
31 #include <isc/print.h>
32 #include <isc/strerror.h>
33 #include <isc/util.h>
34 
35 #include "l_stdlib.h"		/* NTP local change */
36 
37 #ifdef HAVE_STRERROR
38 /*%
39  * We need to do this this way for profiled locks.
40  */
41 static isc_mutex_t isc_strerror_lock;
42 static void init_lock(void) {
43 	RUNTIME_CHECK(isc_mutex_init(&isc_strerror_lock) == ISC_R_SUCCESS);
44 }
45 #else
46 extern const char * const sys_errlist[];
47 extern const int sys_nerr;
48 #endif
49 
50 void
51 isc__strerror(int num, char *buf, size_t size) {
52 #ifdef HAVE_STRERROR
53 	char *msg;
54 	unsigned int unum = (unsigned int)num;
55 	static isc_once_t once = ISC_ONCE_INIT;
56 
57 	REQUIRE(buf != NULL);
58 
59 	RUNTIME_CHECK(isc_once_do(&once, init_lock) == ISC_R_SUCCESS);
60 
61 	LOCK(&isc_strerror_lock);
62 	msg = strerror(num);
63 	if (msg != NULL)
64 		snprintf(buf, size, "%s", msg);
65 	else
66 		snprintf(buf, size, "Unknown error: %u", unum);
67 	UNLOCK(&isc_strerror_lock);
68 #else
69 	unsigned int unum = (unsigned int)num;
70 
71 	REQUIRE(buf != NULL);
72 
73 	if (num >= 0 && num < sys_nerr)
74 		snprintf(buf, size, "%s", sys_errlist[num]);
75 	else
76 		snprintf(buf, size, "Unknown error: %u", unum);
77 #endif
78 }
79