1 /* -*- mode: c; indent-tabs-mode: nil -*- */
2 /* include/k5-platform.h */
4 * Copyright 2003, 2004, 2005, 2007, 2008, 2009 Massachusetts Institute of Technology.
7 * Export of this software from the United States of America may
8 * require a specific license from the United States Government.
9 * It is the responsibility of any person or organization contemplating
10 * export to obtain such a license before exporting.
12 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
13 * distribute this software and its documentation for any purpose and
14 * without fee is hereby granted, provided that the above copyright
15 * notice appear in all copies and that both that copyright notice and
16 * this permission notice appear in supporting documentation, and that
17 * the name of M.I.T. not be used in advertising or publicity pertaining
18 * to distribution of the software without specific, written prior
19 * permission. Furthermore if you modify this software you must label
20 * your software as modified software and not distribute it in such a
21 * fashion that it might be confused with the original M.I.T. software.
22 * M.I.T. makes no representations about the suitability of
23 * this software for any purpose. It is provided "as is" without express
24 * or implied warranty.
28 * Some platform-dependent definitions to sync up the C support level.
29 * Some to a C99-ish level, some related utility code.
32 * + [u]int{8,16,32}_t types
33 * + 64-bit types and load/store code
35 * + shared library init/fini hooks
36 * + consistent getpwnam/getpwuid interfaces
37 * + va_copy fudged if not provided
43 * + zap (support function and macro)
44 * + constant time memory comparison
46 * + _, N_, dgettext, bindtextdomain (for localization)
48 * + fetching filenames from a directory
73 #define CAN_COPY_VA_LIST
76 /* This attribute prevents unused function warnings in gcc and clang. */
78 #define UNUSED __attribute__((__unused__))
83 #if defined(macintosh) || (defined(__MACH__) && defined(__APPLE__))
84 #include <TargetConditionals.h>
87 /* Initialization and finalization function support for libraries.
89 At top level, before the functions are defined or even declared:
90 MAKE_INIT_FUNCTION(init_fn);
91 MAKE_FINI_FUNCTION(fini_fn);
93 int init_fn(void) { ... }
94 void fini_fn(void) { if (INITIALIZER_RAN(init_fn)) ... }
95 In code, in the same file:
96 err = CALL_INIT_FUNCTION(init_fn);
98 To trigger or verify the initializer invocation from another file,
99 a helper function must be created.
101 This model handles both the load-time execution (Windows) and
102 delayed execution (pthread_once) approaches, and should be able to
103 guarantee in both cases that the init function is run once, in one
104 thread, before other stuff in the library is done; furthermore, the
105 finalization code should only run if the initialization code did.
106 (Maybe I could've made the "if INITIALIZER_RAN" test implicit, via
107 another function hidden in macros, but this is hairy enough
110 The init_fn and fini_fn names should be chosen such that any
111 exported names staring with those names, and optionally followed by
112 additional characters, fits in with any namespace constraints on
113 the library in question.
116 There's also PROGRAM_EXITING() currently always defined as zero.
117 If there's some trivial way to find out if the fini function is
118 being called because the program that the library is linked into is
119 exiting, we can just skip all the work because the resources are
120 about to be freed up anyways. Generally this is likely to be the
121 same as distinguishing whether the library was loaded dynamically
122 while the program was running, or loaded as part of program
123 startup. On most platforms, I don't think we can distinguish these
124 cases easily, and it's probably not worth expending any significant
125 effort. (Note in particular that atexit() won't do, because if the
126 library is explicitly loaded and unloaded, it would have to be able
127 to deregister the atexit callback function. Also, the system limit
128 on atexit callbacks may be small.)
131 Implementation outline:
133 Windows: MAKE_FINI_FUNCTION creates a symbol with a magic name that
134 is sought at library build time, and code is added to invoke the
135 function when the library is unloaded. MAKE_INIT_FUNCTION does
136 likewise, but the function is invoked when the library is loaded,
137 and an extra variable is declared to hold an error code and a "yes
138 the initializer ran" flag. CALL_INIT_FUNCTION blows up if the flag
139 isn't set, otherwise returns the error code.
141 UNIX: MAKE_INIT_FUNCTION creates and initializes a variable with a
142 name derived from the function name, containing a k5_once_t
143 (pthread_once_t or int), an error code, and a pointer to the
144 function. The function itself is declared static, but the
145 associated variable has external linkage. CALL_INIT_FUNCTION
146 ensures thath the function is called exactly once (pthread_once or
147 just check the flag) and returns the stored error code (or the
150 (That's the basic idea. With some debugging assert() calls and
151 such, it's a bit more complicated. And we also need to handle
152 doing the pthread test at run time on systems where that works, so
153 we use the k5_once_t stuff instead.)
155 UNIX, with compiler support: MAKE_FINI_FUNCTION declares the
156 function as a destructor, and the run time linker support or
157 whatever will cause it to be invoked when the library is unloaded,
158 the program ends, etc.
160 UNIX, with linker support: MAKE_FINI_FUNCTION creates a symbol with
161 a magic name that is sought at library build time, and linker
162 options are used to mark it as a finalization function for the
163 library. The symbol must be exported.
165 UNIX, no library finalization support: The finalization function
166 never runs, and we leak memory. Tough.
168 DELAY_INITIALIZER will be defined by the configure script if we
169 want to use k5_once instead of load-time initialization. That'll
170 be the preferred method on most systems except Windows, where we
171 have to initialize some mutexes.
176 For maximum flexibility in defining the macros, the function name
177 parameter should be a simple name, not even a macro defined as
178 another name. The function should have a unique name, and should
179 conform to whatever namespace is used by the library in question.
180 (We do have export lists, but (1) they're not used for all
181 platforms, and (2) they're not used for static libraries.)
183 If the macro expansion needs the function to have been declared, it
184 must include a declaration. If it is not necessary for the symbol
185 name to be exported from the object file, the macro should declare
186 it as "static". Hence the signature must exactly match "void
187 foo(void)". (ANSI C allows a static declaration followed by a
188 non-static one; the result is internal linkage.) The macro
189 expansion has to come before the function, because gcc apparently
190 won't act on "__attribute__((constructor))" if it comes after the
193 This is going to be compiler- and environment-specific, and may
194 require some support at library build time, and/or "asm"
195 statements. But through macro expansion and auxiliary functions,
196 we should be able to handle most things except #pragma.
198 It's okay for this code to require that the library be built
199 with the same compiler and compiler options throughout, but
200 we shouldn't require that the library and application use the
203 For static libraries, we don't really care about cleanup too much,
204 since it's all memory handling and mutex allocation which will all
205 be cleaned up when the program exits. Thus, it's okay if gcc-built
206 static libraries don't play nicely with cc-built executables when
207 it comes to static constructors, just as long as it doesn't cause
210 For dynamic libraries on UNIX, we'll use pthread_once-type support
211 to do delayed initialization, so if finalization can't be made to
212 work, we'll only have memory leaks in a load/use/unload cycle. If
213 anyone (like, say, the OS vendor) complains about this, they can
214 tell us how to get a shared library finalization function invoked
217 Currently there's --disable-delayed-initialization for preventing
218 the initialization from being delayed on UNIX, but that's mainly
219 just for testing the linker options for initialization, and will
220 probably be removed at some point. */
224 # define JOIN__2_2(A,B) A ## _ ## _ ## B
225 # define JOIN__2(A,B) JOIN__2_2(A,B)
227 /* XXX Should test USE_LINKER_INIT_OPTION early, and if it's set,
228 always provide a function by the expected name, even if we're
229 delaying initialization. */
231 #if defined(DELAY_INITIALIZER)
233 /* Run the initialization code during program execution, at the latest
234 possible moment. This means multiple threads may be active. */
235 # include "k5-thread.h"
236 typedef struct { k5_once_t once; int error, did_run; void (*fn)(void); } k5_init_t;
237 # ifdef USE_LINKER_INIT_OPTION
238 # define MAYBE_DUMMY_INIT(NAME) \
239 void JOIN__2(NAME, auxinit) () { }
241 # define MAYBE_DUMMY_INIT(NAME)
244 /* Do it in macro form so we get the file/line of the invocation if
245 the assertion fails. */
246 # define k5_call_init_function(I) \
248 k5_init_t *k5int_i = (I); \
249 int k5int_err = k5_once(&k5int_i->once, k5int_i->fn); \
252 : (assert(k5int_i->did_run != 0), k5int_i->error)); \
254 # define MAYBE_DEFINE_CALLINIT_FUNCTION
256 # define MAYBE_DEFINE_CALLINIT_FUNCTION \
257 static inline int k5_call_init_function(k5_init_t *i) \
260 err = k5_once(&i->once, i->fn); \
263 assert (i->did_run != 0); \
267 # define MAKE_INIT_FUNCTION(NAME) \
268 static int NAME(void); \
269 MAYBE_DUMMY_INIT(NAME) \
270 /* forward declaration for use in initializer */ \
271 static void JOIN__2(NAME, aux) (void); \
272 static k5_init_t JOIN__2(NAME, once) = \
273 { K5_ONCE_INIT, 0, 0, JOIN__2(NAME, aux) }; \
274 MAYBE_DEFINE_CALLINIT_FUNCTION \
275 static void JOIN__2(NAME, aux) (void) \
277 JOIN__2(NAME, once).did_run = 1; \
278 JOIN__2(NAME, once).error = NAME(); \
280 /* so ';' following macro use won't get error */ \
281 static int NAME(void)
282 # define CALL_INIT_FUNCTION(NAME) \
283 k5_call_init_function(& JOIN__2(NAME, once))
284 /* This should be called in finalization only, so we shouldn't have
285 multiple active threads mucking around in our library at this
286 point. So ignore the once_t object and just look at the flag.
288 XXX Could we have problems with memory coherence between processors
289 if we don't invoke mutex/once routines? Probably not, the
290 application code should already be coordinating things such that
291 the library code is not in use by this point, and memory
292 synchronization will be needed there. */
293 # define INITIALIZER_RAN(NAME) \
294 (JOIN__2(NAME, once).did_run && JOIN__2(NAME, once).error == 0)
296 # define PROGRAM_EXITING() (0)
298 #elif defined(__GNUC__) && !defined(_WIN32) && defined(CONSTRUCTOR_ATTR_WORKS)
300 /* Run initializer at load time, via GCC/C++ hook magic. */
302 # ifdef USE_LINKER_INIT_OPTION
303 /* Both gcc and linker option?? Favor gcc. */
304 # define MAYBE_DUMMY_INIT(NAME) \
305 void JOIN__2(NAME, auxinit) () { }
307 # define MAYBE_DUMMY_INIT(NAME)
310 typedef struct { int error; unsigned char did_run; } k5_init_t;
311 # define MAKE_INIT_FUNCTION(NAME) \
312 MAYBE_DUMMY_INIT(NAME) \
313 static k5_init_t JOIN__2(NAME, ran) \
315 static void JOIN__2(NAME, aux)(void) \
316 __attribute__((constructor)); \
317 static int NAME(void); \
318 static void JOIN__2(NAME, aux)(void) \
320 JOIN__2(NAME, ran).error = NAME(); \
321 JOIN__2(NAME, ran).did_run = 3; \
323 static int NAME(void)
324 # define CALL_INIT_FUNCTION(NAME) \
325 (JOIN__2(NAME, ran).did_run == 3 \
326 ? JOIN__2(NAME, ran).error \
328 # define INITIALIZER_RAN(NAME) (JOIN__2(NAME,ran).did_run == 3 && JOIN__2(NAME, ran).error == 0)
330 # define PROGRAM_EXITING() (0)
332 #elif defined(USE_LINKER_INIT_OPTION) || defined(_WIN32)
334 /* Run initializer at load time, via linker magic, or in the
335 case of WIN32, win_glue.c hard-coded knowledge. */
336 typedef struct { int error; unsigned char did_run; } k5_init_t;
337 # define MAKE_INIT_FUNCTION(NAME) \
338 static k5_init_t JOIN__2(NAME, ran) \
340 static int NAME(void); \
341 void JOIN__2(NAME, auxinit)() \
343 JOIN__2(NAME, ran).error = NAME(); \
344 JOIN__2(NAME, ran).did_run = 3; \
346 static int NAME(void)
347 # define CALL_INIT_FUNCTION(NAME) \
348 (JOIN__2(NAME, ran).did_run == 3 \
349 ? JOIN__2(NAME, ran).error \
351 # define INITIALIZER_RAN(NAME) \
352 (JOIN__2(NAME, ran).error == 0)
354 # define PROGRAM_EXITING() (0)
358 # error "Don't know how to do load-time initializers for this configuration."
360 # define PROGRAM_EXITING() (0)
366 #if defined(USE_LINKER_FINI_OPTION) || defined(_WIN32)
367 /* If we're told the linker option will be used, it doesn't really
368 matter what compiler we're using. Do it the same way
373 /* On HP-UX, we need this auxiliary function. At dynamic load or
374 unload time (but *not* program startup and termination for
375 link-time specified libraries), the linker-indicated function
376 is called with a handle on the library and a flag indicating
377 whether it's being loaded or unloaded.
379 The "real" fini function doesn't need to be exported, so
382 As usual, the final declaration is just for syntactic
383 convenience, so the top-level invocation of this macro can be
384 followed by a semicolon. */
387 # define MAKE_FINI_FUNCTION(NAME) \
388 static void NAME(void); \
389 void JOIN__2(NAME, auxfini)(shl_t, int); /* silence gcc warnings */ \
390 void JOIN__2(NAME, auxfini)(shl_t h, int l) { if (!l) NAME(); } \
391 static void NAME(void)
393 # else /* not hpux */
395 # define MAKE_FINI_FUNCTION(NAME) \
400 #elif !defined(SHARED)
403 * In this case, we just don't care about finalization. The code will still
404 * define the function, but we won't do anything with it.
406 # define MAKE_FINI_FUNCTION(NAME) \
407 static void NAME(void) UNUSED
409 #elif defined(__GNUC__) && defined(DESTRUCTOR_ATTR_WORKS)
410 /* If we're using gcc, if the C++ support works, the compiler should
411 build executables and shared libraries that support the use of
412 static constructors and destructors. The C compiler supports a
413 function attribute that makes use of the same facility as C++.
415 XXX How do we know if the C++ support actually works? */
416 # define MAKE_FINI_FUNCTION(NAME) \
417 static void NAME(void) __attribute__((destructor))
421 # error "Don't know how to do unload-time finalization for this configuration."
426 # define SIZE_MAX ((size_t)((size_t)0 - 1))
430 # define SSIZE_MAX ((ssize_t)(SIZE_MAX/2))
433 /* Read and write integer values as (unaligned) octet strings in
434 specific byte orders. Add per-platform optimizations as
439 #elif HAVE_MACHINE_ENDIAN_H
440 # include <machine/endian.h>
442 /* Check for BIG/LITTLE_ENDIAN macros. If exactly one is defined, use
443 it. If both are defined, then BYTE_ORDER should be defined and
444 match one of them. Try those symbols, then try again with an
445 underscore prefix. */
446 #if defined(BIG_ENDIAN) && defined(LITTLE_ENDIAN)
447 # if BYTE_ORDER == BIG_ENDIAN
450 # if BYTE_ORDER == LITTLE_ENDIAN
453 #elif defined(BIG_ENDIAN)
455 #elif defined(LITTLE_ENDIAN)
457 #elif defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN)
458 # if _BYTE_ORDER == _BIG_ENDIAN
461 # if _BYTE_ORDER == _LITTLE_ENDIAN
464 #elif defined(_BIG_ENDIAN)
466 #elif defined(_LITTLE_ENDIAN)
468 #elif defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__)
470 #elif defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)
473 #if !defined(K5_BE) && !defined(K5_LE)
474 /* Look for some architectures we know about.
476 MIPS can use either byte order, but the preprocessor tells us which
477 mode we're compiling for. The GCC config files indicate that
478 variants of Alpha and IA64 might be out there with both byte
479 orders, but until we encounter the "wrong" ones in the real world,
480 just go with the default (unless there are cpp predefines to help
483 As far as I know, only PDP11 and ARM (which we don't handle here)
484 have strange byte orders where an 8-byte value isn't laid out as
485 either 12345678 or 87654321. */
486 # if defined(__i386__) || defined(_MIPSEL) || defined(__alpha__) || (defined(__ia64__) && !defined(__hpux))
489 # if defined(__hppa__) || defined(__rs6000__) || defined(__sparc__) || defined(_MIPSEB) || defined(__m68k__) || defined(__sparc64__) || defined(__ppc__) || defined(__ppc64__) || (defined(__hpux) && defined(__ia64__))
493 #if defined(K5_BE) && defined(K5_LE)
494 # error "oops, check the byte order macros"
497 /* Optimize for GCC on platforms with known byte orders.
499 GCC's packed structures can be written to with any alignment; the
500 compiler will use byte operations, unaligned-word operations, or
501 normal memory ops as appropriate for the architecture.
503 This assumes the availability of uint##_t types, which should work
504 on most of our platforms except Windows, where we're not using
507 # define PUT(SIZE,PTR,VAL) (((struct { uint##SIZE##_t i; } __attribute__((packed)) *)(PTR))->i = (VAL))
508 # define GET(SIZE,PTR) (((const struct { uint##SIZE##_t i; } __attribute__((packed)) *)(PTR))->i)
509 # define PUTSWAPPED(SIZE,PTR,VAL) PUT(SIZE,PTR,SWAP##SIZE(VAL))
510 # define GETSWAPPED(SIZE,PTR) SWAP##SIZE(GET(SIZE,PTR))
512 /* To do: Define SWAP16, SWAP32, SWAP64 macros to byte-swap values
513 with the indicated numbers of bits.
515 Linux: byteswap.h, bswap_16 etc.
517 macOS: machine/endian.h or byte_order.h, NXSwap{Short,Int,LongLong}
518 NetBSD: sys/bswap.h, bswap16 etc. */
520 #if defined(HAVE_BYTESWAP_H) && defined(HAVE_BSWAP_16)
521 # include <byteswap.h>
522 # define SWAP16 bswap_16
523 # define SWAP32 bswap_32
524 # ifdef HAVE_BSWAP_64
525 # define SWAP64 bswap_64
528 # include <architecture/byte_order.h>
529 # define SWAP16 k5_swap16
530 static inline unsigned int k5_swap16 (unsigned int x) {
532 return (x >> 8) | ((x & 0xff) << 8);
534 # define SWAP32 OSSwapInt32
535 # define SWAP64 OSSwapInt64
536 #elif defined(HAVE_SYS_BSWAP_H)
537 /* XXX NetBSD/x86 5.0.1 defines bswap16 and bswap32 as inline
538 functions only, so autoconf doesn't pick up on their existence.
539 So, no feature macro test for them here. The 64-bit version isn't
540 inline at all, though, for whatever reason. */
541 # include <sys/bswap.h>
542 # define SWAP16 bswap16
543 # define SWAP32 bswap32
544 /* However, bswap64 causes lots of warnings about 'long long'
545 constants; probably only on 32-bit platforms. */
546 # if LONG_MAX > 0x7fffffffL
547 # define SWAP64 bswap64
551 /* Note that on Windows at least this file can be included from C++
552 source, so casts *from* void* are required. */
554 store_16_be (unsigned int val, void *vp)
556 unsigned char *p = (unsigned char *) vp;
557 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
559 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)
560 PUTSWAPPED(16,p,val);
562 p[0] = (val >> 8) & 0xff;
563 p[1] = (val ) & 0xff;
567 store_32_be (unsigned int val, void *vp)
569 unsigned char *p = (unsigned char *) vp;
570 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
572 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)
573 PUTSWAPPED(32,p,val);
575 p[0] = (val >> 24) & 0xff;
576 p[1] = (val >> 16) & 0xff;
577 p[2] = (val >> 8) & 0xff;
578 p[3] = (val ) & 0xff;
582 store_64_be (uint64_t val, void *vp)
584 unsigned char *p = (unsigned char *) vp;
585 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
587 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)
588 PUTSWAPPED(64,p,val);
590 p[0] = (unsigned char)((val >> 56) & 0xff);
591 p[1] = (unsigned char)((val >> 48) & 0xff);
592 p[2] = (unsigned char)((val >> 40) & 0xff);
593 p[3] = (unsigned char)((val >> 32) & 0xff);
594 p[4] = (unsigned char)((val >> 24) & 0xff);
595 p[5] = (unsigned char)((val >> 16) & 0xff);
596 p[6] = (unsigned char)((val >> 8) & 0xff);
597 p[7] = (unsigned char)((val ) & 0xff);
600 static inline unsigned short
601 load_16_be (const void *cvp)
603 const unsigned char *p = (const unsigned char *) cvp;
604 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
606 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)
607 return GETSWAPPED(16,p);
609 return (p[1] | (p[0] << 8));
612 static inline unsigned int
613 load_32_be (const void *cvp)
615 const unsigned char *p = (const unsigned char *) cvp;
616 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
618 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)
619 return GETSWAPPED(32,p);
621 return (p[3] | (p[2] << 8)
622 | ((uint32_t) p[1] << 16)
623 | ((uint32_t) p[0] << 24));
626 static inline uint64_t
627 load_64_be (const void *cvp)
629 const unsigned char *p = (const unsigned char *) cvp;
630 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
632 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)
633 return GETSWAPPED(64,p);
635 return ((uint64_t)load_32_be(p) << 32) | load_32_be(p+4);
639 store_16_le (unsigned int val, void *vp)
641 unsigned char *p = (unsigned char *) vp;
642 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
644 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)
645 PUTSWAPPED(16,p,val);
647 p[1] = (val >> 8) & 0xff;
648 p[0] = (val ) & 0xff;
652 store_32_le (unsigned int val, void *vp)
654 unsigned char *p = (unsigned char *) vp;
655 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
657 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)
658 PUTSWAPPED(32,p,val);
660 p[3] = (val >> 24) & 0xff;
661 p[2] = (val >> 16) & 0xff;
662 p[1] = (val >> 8) & 0xff;
663 p[0] = (val ) & 0xff;
667 store_64_le (uint64_t val, void *vp)
669 unsigned char *p = (unsigned char *) vp;
670 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
672 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)
673 PUTSWAPPED(64,p,val);
675 p[7] = (unsigned char)((val >> 56) & 0xff);
676 p[6] = (unsigned char)((val >> 48) & 0xff);
677 p[5] = (unsigned char)((val >> 40) & 0xff);
678 p[4] = (unsigned char)((val >> 32) & 0xff);
679 p[3] = (unsigned char)((val >> 24) & 0xff);
680 p[2] = (unsigned char)((val >> 16) & 0xff);
681 p[1] = (unsigned char)((val >> 8) & 0xff);
682 p[0] = (unsigned char)((val ) & 0xff);
685 static inline unsigned short
686 load_16_le (const void *cvp)
688 const unsigned char *p = (const unsigned char *) cvp;
689 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
691 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)
692 return GETSWAPPED(16,p);
694 return (p[0] | (p[1] << 8));
697 static inline unsigned int
698 load_32_le (const void *cvp)
700 const unsigned char *p = (const unsigned char *) cvp;
701 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
703 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)
704 return GETSWAPPED(32,p);
706 return (p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));
709 static inline uint64_t
710 load_64_le (const void *cvp)
712 const unsigned char *p = (const unsigned char *) cvp;
713 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
715 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)
716 return GETSWAPPED(64,p);
718 return ((uint64_t)load_32_le(p+4) << 32) | load_32_le(p);
722 #define UINT16_TYPE uint16_t
723 #define UINT32_TYPE uint32_t
726 store_16_n (unsigned int val, void *vp)
732 store_32_n (unsigned int val, void *vp)
738 store_64_n (uint64_t val, void *vp)
743 static inline unsigned short
744 load_16_n (const void *p)
750 static inline unsigned int
751 load_32_n (const void *p)
757 static inline uint64_t
758 load_64_n (const void *p)
767 /* Assume for simplicity that these swaps are identical. */
768 static inline uint64_t
769 k5_htonll (uint64_t val)
773 #elif defined K5_LE && defined SWAP64
776 return load_64_be ((unsigned char *)&val);
779 static inline uint64_t
780 k5_ntohll (uint64_t val)
782 return k5_htonll (val);
785 /* Make the interfaces to getpwnam and getpwuid consistent.
786 Model the wrappers on the POSIX thread-safe versions, but
787 use the unsafe system versions if the safe ones don't exist
788 or we can't figure out their interfaces. */
790 /* int k5_getpwnam_r(const char *, blah blah) */
791 #ifdef HAVE_GETPWNAM_R
792 # ifndef GETPWNAM_R_4_ARGS
794 # define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \
795 (getpwnam_r(NAME,REC,BUF,BUFSIZE,OUT) == 0 \
796 ? (*(OUT) == NULL ? -1 : 0) : -1)
799 # ifdef GETPWNAM_R_RETURNS_INT
800 # define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \
801 (getpwnam_r(NAME,REC,BUF,BUFSIZE) == 0 \
802 ? (*(OUT) = REC, 0) \
803 : (*(OUT) = NULL, -1))
805 # define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \
806 (*(OUT) = getpwnam_r(NAME,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)
809 #else /* no getpwnam_r, or can't figure out #args or return type */
810 /* Will get warnings about unused variables. */
811 # define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \
812 (*(OUT) = getpwnam(NAME), *(OUT) == NULL ? -1 : 0)
815 /* int k5_getpwuid_r(uid_t, blah blah) */
816 #ifdef HAVE_GETPWUID_R
817 # ifndef GETPWUID_R_4_ARGS
819 # define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \
820 (getpwuid_r(UID,REC,BUF,BUFSIZE,OUT) == 0 \
821 ? (*(OUT) == NULL ? -1 : 0) : -1)
823 /* POSIX drafts? Yes, I mean to test GETPWNAM... here. Less junk to
824 do at configure time. */
825 # ifdef GETPWNAM_R_RETURNS_INT
826 # define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \
827 (getpwuid_r(UID,REC,BUF,BUFSIZE) == 0 \
828 ? (*(OUT) = REC, 0) \
829 : (*(OUT) = NULL, -1))
831 # define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \
832 (*(OUT) = getpwuid_r(UID,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)
835 #else /* no getpwuid_r, or can't figure out #args or return type */
836 /* Will get warnings about unused variables. */
837 # define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \
838 (*(OUT) = getpwuid(UID), *(OUT) == NULL ? -1 : 0)
841 /* Ensure, if possible, that the indicated file descriptor won't be
842 kept open if we exec another process (e.g., launching a ccapi
843 server). If we don't know how to do it... well, just go about our
844 business. Probably most callers won't check the return status
847 /* Macros make the Sun compiler happier, and all variants of this do a
848 single evaluation of the argument, and fcntl and fileno should
849 produce reasonable error messages on type mismatches, on any system
853 # define set_cloexec_fd(FD) ((void)fcntl((FD), F_SETFD, FD_CLOEXEC))
855 # define set_cloexec_fd(FD) ((void)fcntl((FD), F_SETFD, 1))
858 # define set_cloexec_fd(FD) ((void)(FD))
860 #define set_cloexec_file(F) set_cloexec_fd(fileno(F))
862 /* Since the original ANSI C spec left it undefined whether or
863 how you could copy around a va_list, C 99 added va_copy.
864 For old implementations, let's do our best to fake it.
866 XXX Doesn't yet handle implementations with __va_copy (early draft)
867 or GCC's __builtin_va_copy. */
868 #if defined(HAS_VA_COPY) || defined(va_copy)
870 #elif defined(CAN_COPY_VA_LIST)
871 #define va_copy(dest, src) ((dest) = (src))
873 /* Assume array type, but still simply copyable.
875 There is, theoretically, the possibility that va_start will
876 allocate some storage pointed to by the va_list, and in that case
877 we'll just lose. If anyone cares, we could try to devise a test
879 #define va_copy(dest, src) memcpy(dest, src, sizeof(va_list))
882 /* Provide strlcpy/strlcat interfaces. */
884 #define strlcpy krb5int_strlcpy
885 #define strlcat krb5int_strlcat
886 extern size_t krb5int_strlcpy(char *dst, const char *src, size_t siz);
887 extern size_t krb5int_strlcat(char *dst, const char *src, size_t siz);
890 /* Provide fnmatch interface. */
892 #define fnmatch k5_fnmatch
893 int k5_fnmatch(const char *pattern, const char *string, int flags);
894 #define FNM_NOMATCH 1 /* Match failed. */
895 #define FNM_NOSYS 2 /* Function not implemented. */
896 #define FNM_NORES 3 /* Out of resources */
897 #define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */
898 #define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */
899 #define FNM_PERIOD 0x04 /* Period must be matched by period. */
900 #define FNM_CASEFOLD 0x08 /* Pattern is matched case-insensitive */
901 #define FNM_LEADING_DIR 0x10 /* Ignore /<tail> after Imatch. */
904 /* Provide [v]asprintf interfaces. */
905 #ifndef HAVE_VSNPRINTF
908 vsnprintf(char *str, size_t size, const char *format, va_list args)
913 va_copy(args_copy, args);
914 length = _vscprintf(format, args_copy);
917 _vsnprintf(str, size, format, args);
918 str[size - 1] = '\0';
923 snprintf(char *str, size_t size, const char *format, ...)
928 va_start(args, format);
929 n = vsnprintf(str, size, format, args);
933 #else /* not win32 */
934 #error We need an implementation of vsnprintf.
936 #endif /* no vsnprintf */
938 #ifndef HAVE_VASPRINTF
940 extern int krb5int_vasprintf(char **, const char *, va_list)
941 #if !defined(__cplusplus) && (__GNUC__ > 2)
942 __attribute__((__format__(__printf__, 2, 0)))
945 extern int krb5int_asprintf(char **, const char *, ...)
946 #if !defined(__cplusplus) && (__GNUC__ > 2)
947 __attribute__((__format__(__printf__, 2, 3)))
951 #define vasprintf krb5int_vasprintf
952 /* Assume HAVE_ASPRINTF iff HAVE_VASPRINTF. */
953 #define asprintf krb5int_asprintf
955 #elif defined(NEED_VASPRINTF_PROTO)
957 extern int vasprintf(char **, const char *, va_list)
958 #if !defined(__cplusplus) && (__GNUC__ > 2)
959 __attribute__((__format__(__printf__, 2, 0)))
962 extern int asprintf(char **, const char *, ...)
963 #if !defined(__cplusplus) && (__GNUC__ > 2)
964 __attribute__((__format__(__printf__, 2, 3)))
968 #endif /* have vasprintf and prototype? */
970 /* Return true if the snprintf return value RESULT reflects a buffer
971 overflow for the buffer size SIZE.
973 We cast the result to unsigned int for two reasons. First, old
974 implementations of snprintf (such as the one in Solaris 9 and
975 prior) return -1 on a buffer overflow. Casting the result to -1
976 will convert that value to UINT_MAX, which should compare larger
977 than any reasonable buffer size. Second, comparing signed and
978 unsigned integers will generate warnings with some compilers, and
979 can have unpredictable results, particularly when the relative
980 widths of the types is not known (size_t may be the same width as
983 #define SNPRINTF_OVERFLOW(result, size) \
984 ((unsigned int)(result) >= (size_t)(size))
986 #if defined(_WIN32) || !defined(HAVE_STRERROR_R) || defined(STRERROR_R_CHAR_P)
987 #define strerror_r k5_strerror_r
989 extern int k5_strerror_r(int errnum, char *buf, size_t buflen);
992 extern int krb5int_mkstemp(char *);
993 #define mkstemp krb5int_mkstemp
996 #ifndef HAVE_GETTIMEOFDAY
997 extern int krb5int_gettimeofday(struct timeval *tp, void *ignore);
998 #define gettimeofday krb5int_gettimeofday
1002 * Attempt to zero memory in a way that compilers won't optimize out.
1004 * This mechanism should work even for heap storage about to be freed,
1005 * or automatic storage right before we return from a function.
1007 * Then, even if we leak uninitialized memory someplace, or UNIX
1008 * "core" files get created with world-read access, some of the most
1009 * sensitive data in the process memory will already be safely wiped.
1011 * We're not going so far -- yet -- as to try to protect key data that
1012 * may have been written into swap space....
1015 # define zap(ptr, len) SecureZeroMemory(ptr, len)
1016 #elif defined(__STDC_LIB_EXT1__)
1018 * Use memset_s() which cannot be optimized out. Avoid memset_s(NULL, 0, 0, 0)
1019 * which would cause a runtime constraint violation.
1021 static inline void zap(void *ptr, size_t len)
1024 memset_s(ptr, len, 0, len);
1026 #elif defined(__GNUC__) || defined(__clang__)
1028 * Use an asm statement which declares a memory clobber to force the memset to
1029 * be carried out. Avoid memset(NULL, 0, 0) which has undefined behavior.
1031 static inline void zap(void *ptr, size_t len)
1034 memset(ptr, 0, len);
1035 __asm__ __volatile__("" : : "r" (ptr) : "memory");
1039 * Use a function from libkrb5support to defeat inlining unless link-time
1040 * optimization is used. The function uses a volatile pointer, which prevents
1041 * current compilers from optimizing out the memset.
1043 # define zap(ptr, len) krb5int_zap(ptr, len)
1046 extern void krb5int_zap(void *ptr, size_t len);
1049 * Return 0 if the n-byte memory regions p1 and p2 are equal, and nonzero if
1050 * they are not. The function is intended to take the same amount of time
1051 * regardless of how many bytes of p1 and p2 are equal.
1053 int k5_bcmp(const void *p1, const void *p2, size_t n);
1056 * Split a path into parent directory and basename. Either output parameter
1057 * may be NULL if the caller doesn't need it. parent_out will be empty if path
1058 * has no basename. basename_out will be empty if path ends with a path
1059 * separator. Returns 0 on success or ENOMEM on allocation failure.
1061 long k5_path_split(const char *path, char **parent_out, char **basename_out);
1064 * Compose two path components, inserting the platform-appropriate path
1065 * separator if needed. If path2 is an absolute path, path1 will be discarded
1066 * and path_out will be a copy of path2. Returns 0 on success or ENOMEM on
1067 * allocation failure.
1069 long k5_path_join(const char *path1, const char *path2, char **path_out);
1071 /* Return 1 if path is absolute, 0 if it is relative. */
1072 int k5_path_isabs(const char *path);
1075 * Localization macros. If we have gettext, define _ appropriately for
1076 * translating a string. If we do not have gettext, define _ and
1077 * bindtextdomain as no-ops. N_ is always a no-op; it marks a string for
1078 * extraction to pot files but does not translate it.
1081 #include <libintl.h>
1082 #define KRB5_TEXTDOMAIN "mit-krb5"
1083 #define _(s) dgettext(KRB5_TEXTDOMAIN, s)
1086 #define dgettext(d, m) m
1087 #define ngettext(m1, m2, n) (((n) == 1) ? m1 : m2)
1088 #define bindtextdomain(p, d)
1092 #if !defined(HAVE_GETOPT) || !defined(HAVE_UNISTD_H)
1093 /* Data objects imported from DLLs must be declared as such on Windows. */
1094 #if defined(_WIN32) && !defined(K5_GETOPT_C)
1095 #define K5_GETOPT_DECL __declspec(dllimport)
1097 #define K5_GETOPT_DECL
1099 K5_GETOPT_DECL extern int k5_opterr;
1100 K5_GETOPT_DECL extern int k5_optind;
1101 K5_GETOPT_DECL extern int k5_optopt;
1102 K5_GETOPT_DECL extern char *k5_optarg;
1103 #define opterr k5_opterr
1104 #define optind k5_optind
1105 #define optopt k5_optopt
1106 #define optarg k5_optarg
1108 extern int k5_getopt(int nargc, char * const nargv[], const char *ostr);
1109 #define getopt k5_getopt
1110 #endif /* HAVE_GETOPT */
1112 #ifdef HAVE_GETOPT_LONG
1124 #define no_argument 0
1125 #define required_argument 1
1126 #define optional_argument 2
1128 extern int k5_getopt_long(int nargc, char **nargv, char *options,
1129 struct option *long_options, int *index);
1130 #define getopt_long k5_getopt_long
1131 #endif /* HAVE_GETOPT_LONG */
1133 /* Set *fnames_out to a null-terminated list of filenames within dirname,
1134 * sorted according to strcmp(). Return 0 on success, or ENOENT/ENOMEM. */
1135 int k5_dir_filenames(const char *dirname, char ***fnames_out);
1136 void k5_free_filenames(char **fnames);
1138 #endif /* K5_PLATFORM_H */