Home | History | Annotate | Line # | Download | only in libntp
      1 /*	$NetBSD: lib_strbuf.c,v 1.6 2024/08/18 20:47:13 christos Exp $	*/
      2 
      3 /*
      4  * lib_strbuf.c - init_lib() and library string storage
      5  */
      6 #ifdef HAVE_CONFIG_H
      7 #include <config.h>
      8 #endif
      9 
     10 #include <isc/mutex.h>
     11 #include <isc/net.h>
     12 #include <isc/result.h>
     13 
     14 #include "ntp_fp.h"
     15 #include "ntp_stdlib.h"
     16 #include "lib_strbuf.h"
     17 
     18 #define LIB_NUMBUF	10
     19 
     20 /*
     21  * Storage declarations
     22  */
     23 static char		lib_stringbuf_storage[LIB_NUMBUF][LIB_BUFLENGTH];
     24 static char *		lib_stringbuf[LIB_NUMBUF];
     25 int			lib_inited;
     26 static isc_mutex_t	lib_mutex;
     27 int			ipv4_works;
     28 int			ipv6_works;
     29 int			debug;
     30 
     31 /*
     32  * initialization routine.  Might be needed if the code is ROMized.
     33  */
     34 void
     35 init_lib(void)
     36 {
     37 	u_int	u;
     38 
     39 	if (lib_inited) {
     40 		return;
     41 	}
     42 	ipv4_works = (ISC_R_SUCCESS == isc_net_probeipv4());
     43 	ipv6_works = (ISC_R_SUCCESS == isc_net_probeipv6());
     44 	init_systime();
     45 	/*
     46 	 * Avoid -Wrestrict warnings by keeping a pointer to each buffer
     47 	 * so the compiler can see copying from one buffer to another is
     48 	 * not violating restrict qualifiers on, e.g. memcpy() args.
     49 	 */
     50 	for (u = 0; u < COUNTOF(lib_stringbuf); u++) {
     51 		lib_stringbuf[u] = lib_stringbuf_storage[u];
     52 	}
     53 	(void)isc_mutex_init(&lib_mutex);
     54 	lib_inited = TRUE;
     55 }
     56 
     57 
     58 char *
     59 lib_getbuf(void)
     60 {
     61 	static int	lib_nextbuf;
     62 	int		mybuf;
     63 
     64 	if (!lib_inited) {
     65 		init_lib();
     66 	}
     67 	isc_mutex_lock(&lib_mutex);
     68 	mybuf = lib_nextbuf;
     69 	lib_nextbuf = (1 + mybuf) % COUNTOF(lib_stringbuf);
     70 	isc_mutex_unlock(&lib_mutex);
     71 	zero_mem(lib_stringbuf[mybuf], LIB_BUFLENGTH);
     72 
     73 	return lib_stringbuf[mybuf];
     74 }
     75