1 /* -*- mode: c; indent-tabs-mode: nil -*- */
2 /* include/k5-platform.h */
3 /*
4 * Copyright 2003, 2004, 2005, 2007, 2008, 2009 Massachusetts Institute of Technology.
5 * All Rights Reserved.
6 *
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.
11 *
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.
25 */
26
27 /*
28 * Some platform-dependent definitions to sync up the C support level.
29 * Some to a C99-ish level, some related utility code.
30 *
31 * Currently:
32 * + [u]int{8,16,32}_t types
33 * + 64-bit types and load/store code
34 * + SIZE_MAX
35 * + shared library init/fini hooks
36 * + consistent getpwnam/getpwuid interfaces
37 * + va_copy fudged if not provided
38 * + strlcpy/strlcat
39 * + fnmatch
40 * + [v]asprintf
41 * + strerror_r
42 * + mkstemp
43 * + zap (support function and macro)
44 * + constant time memory comparison
45 * + path manipulation
46 * + _, N_, dgettext, bindtextdomain (for localization)
47 * + getopt_long
48 * + secure_getenv
49 * + fetching filenames from a directory
50 */
51
52 #ifndef K5_PLATFORM_H
53 #define K5_PLATFORM_H
54
55 #include "autoconf.h"
56 #include <assert.h>
57 #include <string.h>
58 #include <stdarg.h>
59 #include <stdint.h>
60 #include <limits.h>
61 #include <stdlib.h>
62 #include <stdio.h>
63 #include <fcntl.h>
64 #include <errno.h>
65 #ifdef HAVE_FNMATCH_H
66 #include <fnmatch.h>
67 #endif
68
69 #ifdef HAVE_UNISTD_H
70 #include <unistd.h>
71 #endif
72
73 #ifdef _WIN32
74 #define CAN_COPY_VA_LIST
75 #endif
76
77 /* This attribute prevents unused function warnings in gcc and clang. */
78 #ifdef __GNUC__
79 #define UNUSED __attribute__((__unused__))
80 #else
81 #define UNUSED
82 #endif
83
84 #if defined(macintosh) || (defined(__MACH__) && defined(__APPLE__))
85 #include <TargetConditionals.h>
86 #endif
87
88 /* Initialization and finalization function support for libraries.
89
90 At top level, before the functions are defined or even declared:
91 MAKE_INIT_FUNCTION(init_fn);
92 MAKE_FINI_FUNCTION(fini_fn);
93 Then:
94 int init_fn(void) { ... }
95 void fini_fn(void) { if (INITIALIZER_RAN(init_fn)) ... }
96 In code, in the same file:
97 err = CALL_INIT_FUNCTION(init_fn);
98
99 To trigger or verify the initializer invocation from another file,
100 a helper function must be created.
101
102 This model handles both the load-time execution (Windows) and
103 delayed execution (pthread_once) approaches, and should be able to
104 guarantee in both cases that the init function is run once, in one
105 thread, before other stuff in the library is done; furthermore, the
106 finalization code should only run if the initialization code did.
107 (Maybe I could've made the "if INITIALIZER_RAN" test implicit, via
108 another function hidden in macros, but this is hairy enough
109 already.)
110
111 The init_fn and fini_fn names should be chosen such that any
112 exported names staring with those names, and optionally followed by
113 additional characters, fits in with any namespace constraints on
114 the library in question.
115
116
117 There's also PROGRAM_EXITING() currently always defined as zero.
118 If there's some trivial way to find out if the fini function is
119 being called because the program that the library is linked into is
120 exiting, we can just skip all the work because the resources are
121 about to be freed up anyways. Generally this is likely to be the
122 same as distinguishing whether the library was loaded dynamically
123 while the program was running, or loaded as part of program
124 startup. On most platforms, I don't think we can distinguish these
125 cases easily, and it's probably not worth expending any significant
126 effort. (Note in particular that atexit() won't do, because if the
127 library is explicitly loaded and unloaded, it would have to be able
128 to deregister the atexit callback function. Also, the system limit
129 on atexit callbacks may be small.)
130
131
132 Implementation outline:
133
134 Windows: MAKE_FINI_FUNCTION creates a symbol with a magic name that
135 is sought at library build time, and code is added to invoke the
136 function when the library is unloaded. MAKE_INIT_FUNCTION does
137 likewise, but the function is invoked when the library is loaded,
138 and an extra variable is declared to hold an error code and a "yes
139 the initializer ran" flag. CALL_INIT_FUNCTION blows up if the flag
140 isn't set, otherwise returns the error code.
141
142 UNIX: MAKE_INIT_FUNCTION creates and initializes a variable with a
143 name derived from the function name, containing a k5_once_t
144 (pthread_once_t or int), an error code, and a pointer to the
145 function. The function itself is declared static, but the
146 associated variable has external linkage. CALL_INIT_FUNCTION
147 ensures thath the function is called exactly once (pthread_once or
148 just check the flag) and returns the stored error code (or the
149 pthread_once error).
150
151 (That's the basic idea. With some debugging assert() calls and
152 such, it's a bit more complicated. And we also need to handle
153 doing the pthread test at run time on systems where that works, so
154 we use the k5_once_t stuff instead.)
155
156 UNIX, with compiler support: MAKE_FINI_FUNCTION declares the
157 function as a destructor, and the run time linker support or
158 whatever will cause it to be invoked when the library is unloaded,
159 the program ends, etc.
160
161 UNIX, with linker support: MAKE_FINI_FUNCTION creates a symbol with
162 a magic name that is sought at library build time, and linker
163 options are used to mark it as a finalization function for the
164 library. The symbol must be exported.
165
166 UNIX, no library finalization support: The finalization function
167 never runs, and we leak memory. Tough.
168
169 DELAY_INITIALIZER will be defined by the configure script if we
170 want to use k5_once instead of load-time initialization. That'll
171 be the preferred method on most systems except Windows, where we
172 have to initialize some mutexes.
173
174
175
176
177 For maximum flexibility in defining the macros, the function name
178 parameter should be a simple name, not even a macro defined as
179 another name. The function should have a unique name, and should
180 conform to whatever namespace is used by the library in question.
181 (We do have export lists, but (1) they're not used for all
182 platforms, and (2) they're not used for static libraries.)
183
184 If the macro expansion needs the function to have been declared, it
185 must include a declaration. If it is not necessary for the symbol
186 name to be exported from the object file, the macro should declare
187 it as "static". Hence the signature must exactly match "void
188 foo(void)". (ANSI C allows a static declaration followed by a
189 non-static one; the result is internal linkage.) The macro
190 expansion has to come before the function, because gcc apparently
191 won't act on "__attribute__((constructor))" if it comes after the
192 function definition.
193
194 This is going to be compiler- and environment-specific, and may
195 require some support at library build time, and/or "asm"
196 statements. But through macro expansion and auxiliary functions,
197 we should be able to handle most things except #pragma.
198
199 It's okay for this code to require that the library be built
200 with the same compiler and compiler options throughout, but
201 we shouldn't require that the library and application use the
202 same compiler.
203
204 For static libraries, we don't really care about cleanup too much,
205 since it's all memory handling and mutex allocation which will all
206 be cleaned up when the program exits. Thus, it's okay if gcc-built
207 static libraries don't play nicely with cc-built executables when
208 it comes to static constructors, just as long as it doesn't cause
209 linking to fail.
210
211 For dynamic libraries on UNIX, we'll use pthread_once-type support
212 to do delayed initialization, so if finalization can't be made to
213 work, we'll only have memory leaks in a load/use/unload cycle. If
214 anyone (like, say, the OS vendor) complains about this, they can
215 tell us how to get a shared library finalization function invoked
216 automatically.
217
218 Currently there's --disable-delayed-initialization for preventing
219 the initialization from being delayed on UNIX, but that's mainly
220 just for testing the linker options for initialization, and will
221 probably be removed at some point. */
222
223 /* Helper macros. */
224
225 # define JOIN__2_2(A,B) A ## _ ## _ ## B
226 # define JOIN__2(A,B) JOIN__2_2(A,B)
227
228 /* XXX Should test USE_LINKER_INIT_OPTION early, and if it's set,
229 always provide a function by the expected name, even if we're
230 delaying initialization. */
231
232 #if defined(DELAY_INITIALIZER)
233
234 /* Run the initialization code during program execution, at the latest
235 possible moment. This means multiple threads may be active. */
236 # include "k5-thread.h"
237 typedef struct { k5_once_t once; int error, did_run; void (*fn)(void); } k5_init_t;
238 # ifdef USE_LINKER_INIT_OPTION
239 # define MAYBE_DUMMY_INIT(NAME) \
240 void JOIN__2(NAME, auxinit) () { }
241 # else
242 # define MAYBE_DUMMY_INIT(NAME)
243 # endif
244 # ifdef __GNUC__
245 /* Do it in macro form so we get the file/line of the invocation if
246 the assertion fails. */
247 # define k5_call_init_function(I) \
248 (__extension__ ({ \
249 k5_init_t *k5int_i = (I); \
250 int k5int_err = k5_once(&k5int_i->once, k5int_i->fn); \
251 (k5int_err \
252 ? k5int_err \
253 : (assert(k5int_i->did_run != 0), k5int_i->error)); \
254 }))
255 # define MAYBE_DEFINE_CALLINIT_FUNCTION
256 # else
257 # define MAYBE_DEFINE_CALLINIT_FUNCTION \
258 static inline int k5_call_init_function(k5_init_t *i) \
259 { \
260 int err; \
261 err = k5_once(&i->once, i->fn); \
262 if (err) \
263 return err; \
264 assert (i->did_run != 0); \
265 return i->error; \
266 }
267 # endif
268 # define MAKE_INIT_FUNCTION(NAME) \
269 static int NAME(void); \
270 MAYBE_DUMMY_INIT(NAME) \
271 /* forward declaration for use in initializer */ \
272 static void JOIN__2(NAME, aux) (void); \
273 static k5_init_t JOIN__2(NAME, once) = \
274 { K5_ONCE_INIT, 0, 0, JOIN__2(NAME, aux) }; \
275 MAYBE_DEFINE_CALLINIT_FUNCTION \
276 static void JOIN__2(NAME, aux) (void) \
277 { \
278 JOIN__2(NAME, once).did_run = 1; \
279 JOIN__2(NAME, once).error = NAME(); \
280 } \
281 /* so ';' following macro use won't get error */ \
282 static int NAME(void)
283 # define CALL_INIT_FUNCTION(NAME) \
284 k5_call_init_function(& JOIN__2(NAME, once))
285 /* This should be called in finalization only, so we shouldn't have
286 multiple active threads mucking around in our library at this
287 point. So ignore the once_t object and just look at the flag.
288
289 XXX Could we have problems with memory coherence between processors
290 if we don't invoke mutex/once routines? Probably not, the
291 application code should already be coordinating things such that
292 the library code is not in use by this point, and memory
293 synchronization will be needed there. */
294 # define INITIALIZER_RAN(NAME) \
295 (JOIN__2(NAME, once).did_run && JOIN__2(NAME, once).error == 0)
296
297 # define PROGRAM_EXITING() (0)
298
299 #elif defined(__GNUC__) && !defined(_WIN32) && defined(CONSTRUCTOR_ATTR_WORKS)
300
301 /* Run initializer at load time, via GCC/C++ hook magic. */
302
303 # ifdef USE_LINKER_INIT_OPTION
304 /* Both gcc and linker option?? Favor gcc. */
305 # define MAYBE_DUMMY_INIT(NAME) \
306 void JOIN__2(NAME, auxinit) () { }
307 # else
308 # define MAYBE_DUMMY_INIT(NAME)
309 # endif
310
311 typedef struct { int error; unsigned char did_run; } k5_init_t;
312 # define MAKE_INIT_FUNCTION(NAME) \
313 MAYBE_DUMMY_INIT(NAME) \
314 static k5_init_t JOIN__2(NAME, ran) \
315 = { 0, 2 }; \
316 static void JOIN__2(NAME, aux)(void) \
317 __attribute__((constructor)); \
318 static int NAME(void); \
319 static void JOIN__2(NAME, aux)(void) \
320 { \
321 JOIN__2(NAME, ran).error = NAME(); \
322 JOIN__2(NAME, ran).did_run = 3; \
323 } \
324 static int NAME(void)
325 # define CALL_INIT_FUNCTION(NAME) \
326 (JOIN__2(NAME, ran).did_run == 3 \
327 ? JOIN__2(NAME, ran).error \
328 : (abort(),0))
329 # define INITIALIZER_RAN(NAME) (JOIN__2(NAME,ran).did_run == 3 && JOIN__2(NAME, ran).error == 0)
330
331 # define PROGRAM_EXITING() (0)
332
333 #elif defined(USE_LINKER_INIT_OPTION) || defined(_WIN32)
334
335 /* Run initializer at load time, via linker magic, or in the
336 case of WIN32, win_glue.c hard-coded knowledge. */
337 typedef struct { int error; unsigned char did_run; } k5_init_t;
338 # define MAKE_INIT_FUNCTION(NAME) \
339 static k5_init_t JOIN__2(NAME, ran) \
340 = { 0, 2 }; \
341 static int NAME(void); \
342 void JOIN__2(NAME, auxinit)() \
343 { \
344 JOIN__2(NAME, ran).error = NAME(); \
345 JOIN__2(NAME, ran).did_run = 3; \
346 } \
347 static int NAME(void)
348 # define CALL_INIT_FUNCTION(NAME) \
349 (JOIN__2(NAME, ran).did_run == 3 \
350 ? JOIN__2(NAME, ran).error \
351 : (abort(),0))
352 # define INITIALIZER_RAN(NAME) \
353 (JOIN__2(NAME, ran).error == 0)
354
355 # define PROGRAM_EXITING() (0)
356
357 #else
358
359 # error "Don't know how to do load-time initializers for this configuration."
360
361 # define PROGRAM_EXITING() (0)
362
363 #endif
364
365
366
367 #if defined(USE_LINKER_FINI_OPTION) || defined(_WIN32)
368 /* If we're told the linker option will be used, it doesn't really
369 matter what compiler we're using. Do it the same way
370 regardless. */
371
372 # ifdef __hpux
373
374 /* On HP-UX, we need this auxiliary function. At dynamic load or
375 unload time (but *not* program startup and termination for
376 link-time specified libraries), the linker-indicated function
377 is called with a handle on the library and a flag indicating
378 whether it's being loaded or unloaded.
379
380 The "real" fini function doesn't need to be exported, so
381 declare it static.
382
383 As usual, the final declaration is just for syntactic
384 convenience, so the top-level invocation of this macro can be
385 followed by a semicolon. */
386
387 # include <dl.h>
388 # define MAKE_FINI_FUNCTION(NAME) \
389 static void NAME(void); \
390 void JOIN__2(NAME, auxfini)(shl_t, int); /* silence gcc warnings */ \
391 void JOIN__2(NAME, auxfini)(shl_t h, int l) { if (!l) NAME(); } \
392 static void NAME(void)
393
394 # else /* not hpux */
395
396 # define MAKE_FINI_FUNCTION(NAME) \
397 void NAME(void)
398
399 # endif
400
401 #elif !defined(SHARED)
402
403 /*
404 * In this case, we just don't care about finalization. The code will still
405 * define the function, but we won't do anything with it.
406 */
407 # define MAKE_FINI_FUNCTION(NAME) \
408 static void NAME(void) UNUSED
409
410 #elif defined(__GNUC__) && defined(DESTRUCTOR_ATTR_WORKS)
411 /* If we're using gcc, if the C++ support works, the compiler should
412 build executables and shared libraries that support the use of
413 static constructors and destructors. The C compiler supports a
414 function attribute that makes use of the same facility as C++.
415
416 XXX How do we know if the C++ support actually works? */
417 # define MAKE_FINI_FUNCTION(NAME) \
418 static void NAME(void) __attribute__((destructor))
419
420 #else
421
422 # error "Don't know how to do unload-time finalization for this configuration."
423
424 #endif
425
426 #ifndef SIZE_MAX
427 # define SIZE_MAX ((size_t)((size_t)0 - 1))
428 #endif
429
430 #ifdef _WIN32
431 # define SSIZE_MAX ((ssize_t)(SIZE_MAX/2))
432 #endif
433
434 /* Read and write integer values as (unaligned) octet strings in
435 specific byte orders. Add per-platform optimizations as
436 needed. */
437
438 #if HAVE_ENDIAN_H
439 # include <endian.h>
440 #elif HAVE_MACHINE_ENDIAN_H
441 # include <machine/endian.h>
442 #endif
443 /* Check for BIG/LITTLE_ENDIAN macros. If exactly one is defined, use
444 it. If both are defined, then BYTE_ORDER should be defined and
445 match one of them. Try those symbols, then try again with an
446 underscore prefix. */
447 #if defined(BIG_ENDIAN) && defined(LITTLE_ENDIAN)
448 # if BYTE_ORDER == BIG_ENDIAN
449 # define K5_BE
450 # endif
451 # if BYTE_ORDER == LITTLE_ENDIAN
452 # define K5_LE
453 # endif
454 #elif defined(BIG_ENDIAN)
455 # define K5_BE
456 #elif defined(LITTLE_ENDIAN)
457 # define K5_LE
458 #elif defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN)
459 # if _BYTE_ORDER == _BIG_ENDIAN
460 # define K5_BE
461 # endif
462 # if _BYTE_ORDER == _LITTLE_ENDIAN
463 # define K5_LE
464 # endif
465 #elif defined(_BIG_ENDIAN)
466 # define K5_BE
467 #elif defined(_LITTLE_ENDIAN)
468 # define K5_LE
469 #elif defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__)
470 # define K5_BE
471 #elif defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)
472 # define K5_LE
473 #endif
474 #if !defined(K5_BE) && !defined(K5_LE)
475 /* Look for some architectures we know about.
476
477 MIPS can use either byte order, but the preprocessor tells us which
478 mode we're compiling for. The GCC config files indicate that
479 variants of Alpha and IA64 might be out there with both byte
480 orders, but until we encounter the "wrong" ones in the real world,
481 just go with the default (unless there are cpp predefines to help
482 us there too).
483
484 As far as I know, only PDP11 and ARM (which we don't handle here)
485 have strange byte orders where an 8-byte value isn't laid out as
486 either 12345678 or 87654321. */
487 # if defined(__i386__) || defined(_MIPSEL) || defined(__alpha__) || (defined(__ia64__) && !defined(__hpux))
488 # define K5_LE
489 # endif
490 # if defined(__hppa__) || defined(__rs6000__) || defined(__sparc__) || defined(_MIPSEB) || defined(__m68k__) || defined(__sparc64__) || defined(__ppc__) || defined(__ppc64__) || (defined(__hpux) && defined(__ia64__))
491 # define K5_BE
492 # endif
493 #endif
494 #if defined(K5_BE) && defined(K5_LE)
495 # error "oops, check the byte order macros"
496 #endif
497
498 /* Optimize for GCC on platforms with known byte orders.
499
500 GCC's packed structures can be written to with any alignment; the
501 compiler will use byte operations, unaligned-word operations, or
502 normal memory ops as appropriate for the architecture.
503
504 This assumes the availability of uint##_t types, which should work
505 on most of our platforms except Windows, where we're not using
506 GCC. */
507 #ifdef __GNUC__
508 # define PUT(SIZE,PTR,VAL) (((struct { uint##SIZE##_t i; } __attribute__((packed)) *)(PTR))->i = (VAL))
509 # define GET(SIZE,PTR) (((const struct { uint##SIZE##_t i; } __attribute__((packed)) *)(PTR))->i)
510 # define PUTSWAPPED(SIZE,PTR,VAL) PUT(SIZE,PTR,SWAP##SIZE(VAL))
511 # define GETSWAPPED(SIZE,PTR) SWAP##SIZE(GET(SIZE,PTR))
512 #endif
513 /* To do: Define SWAP16, SWAP32, SWAP64 macros to byte-swap values
514 with the indicated numbers of bits.
515
516 Linux: byteswap.h, bswap_16 etc.
517 Solaris 10: none
518 macOS: machine/endian.h or byte_order.h, NXSwap{Short,Int,LongLong}
519 NetBSD: sys/bswap.h, bswap16 etc. */
520
521 #if defined(HAVE_BYTESWAP_H) && defined(HAVE_BSWAP_16)
522 # include <byteswap.h>
523 # define SWAP16 bswap_16
524 # define SWAP32 bswap_32
525 # ifdef HAVE_BSWAP_64
526 # define SWAP64 bswap_64
527 # endif
528 #elif TARGET_OS_MAC
529 # include <architecture/byte_order.h>
530 # define SWAP16 k5_swap16
k5_swap16(unsigned int x)531 static inline unsigned int k5_swap16 (unsigned int x) {
532 x &= 0xffff;
533 return (x >> 8) | ((x & 0xff) << 8);
534 }
535 # define SWAP32 OSSwapInt32
536 # define SWAP64 OSSwapInt64
537 #elif defined(HAVE_SYS_BSWAP_H)
538 /* XXX NetBSD/x86 5.0.1 defines bswap16 and bswap32 as inline
539 functions only, so autoconf doesn't pick up on their existence.
540 So, no feature macro test for them here. The 64-bit version isn't
541 inline at all, though, for whatever reason. */
542 # include <sys/bswap.h>
543 # define SWAP16 bswap16
544 # define SWAP32 bswap32
545 /* However, bswap64 causes lots of warnings about 'long long'
546 constants; probably only on 32-bit platforms. */
547 # if LONG_MAX > 0x7fffffffL
548 # define SWAP64 bswap64
549 # endif
550 #endif
551
552 /* Note that on Windows at least this file can be included from C++
553 source, so casts *from* void* are required. */
554 static inline void
store_16_be(unsigned int val,void * vp)555 store_16_be (unsigned int val, void *vp)
556 {
557 unsigned char *p = (unsigned char *) vp;
558 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
559 PUT(16,p,val);
560 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)
561 PUTSWAPPED(16,p,val);
562 #else
563 p[0] = (val >> 8) & 0xff;
564 p[1] = (val ) & 0xff;
565 #endif
566 }
567 static inline void
store_32_be(unsigned int val,void * vp)568 store_32_be (unsigned int val, void *vp)
569 {
570 unsigned char *p = (unsigned char *) vp;
571 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
572 PUT(32,p,val);
573 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)
574 PUTSWAPPED(32,p,val);
575 #else
576 p[0] = (val >> 24) & 0xff;
577 p[1] = (val >> 16) & 0xff;
578 p[2] = (val >> 8) & 0xff;
579 p[3] = (val ) & 0xff;
580 #endif
581 }
582 static inline void
store_64_be(uint64_t val,void * vp)583 store_64_be (uint64_t val, void *vp)
584 {
585 unsigned char *p = (unsigned char *) vp;
586 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
587 PUT(64,p,val);
588 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)
589 PUTSWAPPED(64,p,val);
590 #else
591 p[0] = (unsigned char)((val >> 56) & 0xff);
592 p[1] = (unsigned char)((val >> 48) & 0xff);
593 p[2] = (unsigned char)((val >> 40) & 0xff);
594 p[3] = (unsigned char)((val >> 32) & 0xff);
595 p[4] = (unsigned char)((val >> 24) & 0xff);
596 p[5] = (unsigned char)((val >> 16) & 0xff);
597 p[6] = (unsigned char)((val >> 8) & 0xff);
598 p[7] = (unsigned char)((val ) & 0xff);
599 #endif
600 }
601 static inline unsigned short
load_16_be(const void * cvp)602 load_16_be (const void *cvp)
603 {
604 const unsigned char *p = (const unsigned char *) cvp;
605 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
606 return GET(16,p);
607 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)
608 return GETSWAPPED(16,p);
609 #else
610 return (p[1] | (p[0] << 8));
611 #endif
612 }
613 static inline unsigned int
load_32_be(const void * cvp)614 load_32_be (const void *cvp)
615 {
616 const unsigned char *p = (const unsigned char *) cvp;
617 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
618 return GET(32,p);
619 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)
620 return GETSWAPPED(32,p);
621 #else
622 return (p[3] | (p[2] << 8)
623 | ((uint32_t) p[1] << 16)
624 | ((uint32_t) p[0] << 24));
625 #endif
626 }
627 static inline uint64_t
load_64_be(const void * cvp)628 load_64_be (const void *cvp)
629 {
630 const unsigned char *p = (const unsigned char *) cvp;
631 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
632 return GET(64,p);
633 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)
634 return GETSWAPPED(64,p);
635 #else
636 return ((uint64_t)load_32_be(p) << 32) | load_32_be(p+4);
637 #endif
638 }
639 static inline void
store_16_le(unsigned int val,void * vp)640 store_16_le (unsigned int val, void *vp)
641 {
642 unsigned char *p = (unsigned char *) vp;
643 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
644 PUT(16,p,val);
645 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)
646 PUTSWAPPED(16,p,val);
647 #else
648 p[1] = (val >> 8) & 0xff;
649 p[0] = (val ) & 0xff;
650 #endif
651 }
652 static inline void
store_32_le(unsigned int val,void * vp)653 store_32_le (unsigned int val, void *vp)
654 {
655 unsigned char *p = (unsigned char *) vp;
656 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
657 PUT(32,p,val);
658 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)
659 PUTSWAPPED(32,p,val);
660 #else
661 p[3] = (val >> 24) & 0xff;
662 p[2] = (val >> 16) & 0xff;
663 p[1] = (val >> 8) & 0xff;
664 p[0] = (val ) & 0xff;
665 #endif
666 }
667 static inline void
store_64_le(uint64_t val,void * vp)668 store_64_le (uint64_t val, void *vp)
669 {
670 unsigned char *p = (unsigned char *) vp;
671 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
672 PUT(64,p,val);
673 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)
674 PUTSWAPPED(64,p,val);
675 #else
676 p[7] = (unsigned char)((val >> 56) & 0xff);
677 p[6] = (unsigned char)((val >> 48) & 0xff);
678 p[5] = (unsigned char)((val >> 40) & 0xff);
679 p[4] = (unsigned char)((val >> 32) & 0xff);
680 p[3] = (unsigned char)((val >> 24) & 0xff);
681 p[2] = (unsigned char)((val >> 16) & 0xff);
682 p[1] = (unsigned char)((val >> 8) & 0xff);
683 p[0] = (unsigned char)((val ) & 0xff);
684 #endif
685 }
686 static inline unsigned short
load_16_le(const void * cvp)687 load_16_le (const void *cvp)
688 {
689 const unsigned char *p = (const unsigned char *) cvp;
690 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
691 return GET(16,p);
692 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)
693 return GETSWAPPED(16,p);
694 #else
695 return (p[0] | (p[1] << 8));
696 #endif
697 }
698 static inline unsigned int
load_32_le(const void * cvp)699 load_32_le (const void *cvp)
700 {
701 const unsigned char *p = (const unsigned char *) cvp;
702 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
703 return GET(32,p);
704 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)
705 return GETSWAPPED(32,p);
706 #else
707 return (p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));
708 #endif
709 }
710 static inline uint64_t
load_64_le(const void * cvp)711 load_64_le (const void *cvp)
712 {
713 const unsigned char *p = (const unsigned char *) cvp;
714 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
715 return GET(64,p);
716 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)
717 return GETSWAPPED(64,p);
718 #else
719 return ((uint64_t)load_32_le(p+4) << 32) | load_32_le(p);
720 #endif
721 }
722
723 #define UINT16_TYPE uint16_t
724 #define UINT32_TYPE uint32_t
725
726 static inline void
store_16_n(unsigned int val,void * vp)727 store_16_n (unsigned int val, void *vp)
728 {
729 UINT16_TYPE n = val;
730 memcpy(vp, &n, 2);
731 }
732 static inline void
store_32_n(unsigned int val,void * vp)733 store_32_n (unsigned int val, void *vp)
734 {
735 UINT32_TYPE n = val;
736 memcpy(vp, &n, 4);
737 }
738 static inline void
store_64_n(uint64_t val,void * vp)739 store_64_n (uint64_t val, void *vp)
740 {
741 uint64_t n = val;
742 memcpy(vp, &n, 8);
743 }
744 static inline unsigned short
load_16_n(const void * p)745 load_16_n (const void *p)
746 {
747 UINT16_TYPE n;
748 memcpy(&n, p, 2);
749 return n;
750 }
751 static inline unsigned int
load_32_n(const void * p)752 load_32_n (const void *p)
753 {
754 UINT32_TYPE n;
755 memcpy(&n, p, 4);
756 return n;
757 }
758 static inline uint64_t
load_64_n(const void * p)759 load_64_n (const void *p)
760 {
761 uint64_t n;
762 memcpy(&n, p, 8);
763 return n;
764 }
765 #undef UINT16_TYPE
766 #undef UINT32_TYPE
767
768 /* Assume for simplicity that these swaps are identical. */
769 static inline uint64_t
k5_htonll(uint64_t val)770 k5_htonll (uint64_t val)
771 {
772 #ifdef K5_BE
773 return val;
774 #elif defined K5_LE && defined SWAP64
775 return SWAP64 (val);
776 #else
777 return load_64_be ((unsigned char *)&val);
778 #endif
779 }
780 static inline uint64_t
k5_ntohll(uint64_t val)781 k5_ntohll (uint64_t val)
782 {
783 return k5_htonll (val);
784 }
785
786 /* Make the interfaces to getpwnam and getpwuid consistent.
787 Model the wrappers on the POSIX thread-safe versions, but
788 use the unsafe system versions if the safe ones don't exist
789 or we can't figure out their interfaces. */
790
791 /* int k5_getpwnam_r(const char *, blah blah) */
792 #ifdef HAVE_GETPWNAM_R
793 # ifndef GETPWNAM_R_4_ARGS
794 /* POSIX */
795 # define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \
796 (getpwnam_r(NAME,REC,BUF,BUFSIZE,OUT) == 0 \
797 ? (*(OUT) == NULL ? -1 : 0) : -1)
798 # else
799 /* POSIX drafts? */
800 # ifdef GETPWNAM_R_RETURNS_INT
801 # define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \
802 (getpwnam_r(NAME,REC,BUF,BUFSIZE) == 0 \
803 ? (*(OUT) = REC, 0) \
804 : (*(OUT) = NULL, -1))
805 # else
806 # define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \
807 (*(OUT) = getpwnam_r(NAME,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)
808 # endif
809 # endif
810 #else /* no getpwnam_r, or can't figure out #args or return type */
811 /* Will get warnings about unused variables. */
812 # define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \
813 (*(OUT) = getpwnam(NAME), *(OUT) == NULL ? -1 : 0)
814 #endif
815
816 /* int k5_getpwuid_r(uid_t, blah blah) */
817 #ifdef HAVE_GETPWUID_R
818 # ifndef GETPWUID_R_4_ARGS
819 /* POSIX */
820 # define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \
821 (getpwuid_r(UID,REC,BUF,BUFSIZE,OUT) == 0 \
822 ? (*(OUT) == NULL ? -1 : 0) : -1)
823 # else
824 /* POSIX drafts? Yes, I mean to test GETPWNAM... here. Less junk to
825 do at configure time. */
826 # ifdef GETPWNAM_R_RETURNS_INT
827 # define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \
828 (getpwuid_r(UID,REC,BUF,BUFSIZE) == 0 \
829 ? (*(OUT) = REC, 0) \
830 : (*(OUT) = NULL, -1))
831 # else
832 # define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \
833 (*(OUT) = getpwuid_r(UID,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)
834 # endif
835 # endif
836 #else /* no getpwuid_r, or can't figure out #args or return type */
837 /* Will get warnings about unused variables. */
838 # define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \
839 (*(OUT) = getpwuid(UID), *(OUT) == NULL ? -1 : 0)
840 #endif
841
842 /* Ensure, if possible, that the indicated file descriptor won't be
843 kept open if we exec another process (e.g., launching a ccapi
844 server). If we don't know how to do it... well, just go about our
845 business. Probably most callers won't check the return status
846 anyways. */
847
848 /* Macros make the Sun compiler happier, and all variants of this do a
849 single evaluation of the argument, and fcntl and fileno should
850 produce reasonable error messages on type mismatches, on any system
851 with F_SETFD. */
852 #ifdef F_SETFD
853 # ifdef FD_CLOEXEC
854 # define set_cloexec_fd(FD) ((void)fcntl((FD), F_SETFD, FD_CLOEXEC))
855 # else
856 # define set_cloexec_fd(FD) ((void)fcntl((FD), F_SETFD, 1))
857 # endif
858 #else
859 # define set_cloexec_fd(FD) ((void)(FD))
860 #endif
861 #define set_cloexec_file(F) set_cloexec_fd(fileno(F))
862
863 /* Since the original ANSI C spec left it undefined whether or
864 how you could copy around a va_list, C 99 added va_copy.
865 For old implementations, let's do our best to fake it.
866
867 XXX Doesn't yet handle implementations with __va_copy (early draft)
868 or GCC's __builtin_va_copy. */
869 #if defined(HAS_VA_COPY) || defined(va_copy)
870 /* Do nothing. */
871 #elif defined(CAN_COPY_VA_LIST)
872 #define va_copy(dest, src) ((dest) = (src))
873 #else
874 /* Assume array type, but still simply copyable.
875
876 There is, theoretically, the possibility that va_start will
877 allocate some storage pointed to by the va_list, and in that case
878 we'll just lose. If anyone cares, we could try to devise a test
879 for that case. */
880 #define va_copy(dest, src) memcpy(dest, src, sizeof(va_list))
881 #endif
882
883 /* Provide strlcpy/strlcat interfaces. */
884 #ifndef HAVE_STRLCPY
885 #define strlcpy krb5int_strlcpy
886 #define strlcat krb5int_strlcat
887 extern size_t krb5int_strlcpy(char *dst, const char *src, size_t siz);
888 extern size_t krb5int_strlcat(char *dst, const char *src, size_t siz);
889 #endif
890
891 /* Provide fnmatch interface. */
892 #ifndef HAVE_FNMATCH
893 #define fnmatch k5_fnmatch
894 int k5_fnmatch(const char *pattern, const char *string, int flags);
895 #define FNM_NOMATCH 1 /* Match failed. */
896 #define FNM_NOSYS 2 /* Function not implemented. */
897 #define FNM_NORES 3 /* Out of resources */
898 #define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */
899 #define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */
900 #define FNM_PERIOD 0x04 /* Period must be matched by period. */
901 #define FNM_CASEFOLD 0x08 /* Pattern is matched case-insensitive */
902 #define FNM_LEADING_DIR 0x10 /* Ignore /<tail> after Imatch. */
903 #endif
904
905 /* Provide [v]asprintf interfaces. */
906 #ifndef HAVE_VSNPRINTF
907 #ifdef _WIN32
908 static inline int
vsnprintf(char * str,size_t size,const char * format,va_list args)909 vsnprintf(char *str, size_t size, const char *format, va_list args)
910 {
911 va_list args_copy;
912 int length;
913
914 va_copy(args_copy, args);
915 length = _vscprintf(format, args_copy);
916 va_end(args_copy);
917 if (size > 0) {
918 _vsnprintf(str, size, format, args);
919 str[size - 1] = '\0';
920 }
921 return length;
922 }
923 static inline int
snprintf(char * str,size_t size,const char * format,...)924 snprintf(char *str, size_t size, const char *format, ...)
925 {
926 va_list args;
927 int n;
928
929 va_start(args, format);
930 n = vsnprintf(str, size, format, args);
931 va_end(args);
932 return n;
933 }
934 #else /* not win32 */
935 #error We need an implementation of vsnprintf.
936 #endif /* win32? */
937 #endif /* no vsnprintf */
938
939 #ifndef HAVE_VASPRINTF
940
941 extern int krb5int_vasprintf(char **, const char *, va_list)
942 #if !defined(__cplusplus) && (__GNUC__ > 2)
943 __attribute__((__format__(__printf__, 2, 0)))
944 #endif
945 ;
946 extern int krb5int_asprintf(char **, const char *, ...)
947 #if !defined(__cplusplus) && (__GNUC__ > 2)
948 __attribute__((__format__(__printf__, 2, 3)))
949 #endif
950 ;
951
952 #define vasprintf krb5int_vasprintf
953 /* Assume HAVE_ASPRINTF iff HAVE_VASPRINTF. */
954 #define asprintf krb5int_asprintf
955
956 #elif defined(NEED_VASPRINTF_PROTO)
957
958 extern int vasprintf(char **, const char *, va_list)
959 #if !defined(__cplusplus) && (__GNUC__ > 2)
960 __attribute__((__format__(__printf__, 2, 0)))
961 #endif
962 ;
963 extern int asprintf(char **, const char *, ...)
964 #if !defined(__cplusplus) && (__GNUC__ > 2)
965 __attribute__((__format__(__printf__, 2, 3)))
966 #endif
967 ;
968
969 #endif /* have vasprintf and prototype? */
970
971 /* Return true if the snprintf return value RESULT reflects a buffer
972 overflow for the buffer size SIZE.
973
974 We cast the result to unsigned int for two reasons. First, old
975 implementations of snprintf (such as the one in Solaris 9 and
976 prior) return -1 on a buffer overflow. Casting the result to -1
977 will convert that value to UINT_MAX, which should compare larger
978 than any reasonable buffer size. Second, comparing signed and
979 unsigned integers will generate warnings with some compilers, and
980 can have unpredictable results, particularly when the relative
981 widths of the types is not known (size_t may be the same width as
982 int or larger).
983 */
984 #define SNPRINTF_OVERFLOW(result, size) \
985 ((unsigned int)(result) >= (size_t)(size))
986
987 #if defined(_WIN32) || !defined(HAVE_STRERROR_R) || defined(STRERROR_R_CHAR_P)
988 #define strerror_r k5_strerror_r
989 #endif
990 extern int k5_strerror_r(int errnum, char *buf, size_t buflen);
991
992 #ifndef HAVE_MKSTEMP
993 extern int krb5int_mkstemp(char *);
994 #define mkstemp krb5int_mkstemp
995 #endif
996
997 #ifndef HAVE_GETTIMEOFDAY
998 extern int krb5int_gettimeofday(struct timeval *tp, void *ignore);
999 #define gettimeofday krb5int_gettimeofday
1000 #endif
1001
1002 /*
1003 * Attempt to zero memory in a way that compilers won't optimize out.
1004 *
1005 * This mechanism should work even for heap storage about to be freed,
1006 * or automatic storage right before we return from a function.
1007 *
1008 * Then, even if we leak uninitialized memory someplace, or UNIX
1009 * "core" files get created with world-read access, some of the most
1010 * sensitive data in the process memory will already be safely wiped.
1011 *
1012 * We're not going so far -- yet -- as to try to protect key data that
1013 * may have been written into swap space....
1014 */
1015 #ifdef _WIN32
1016 # define zap(ptr, len) SecureZeroMemory(ptr, len)
1017 #elif defined(__STDC_LIB_EXT1__)
1018 /*
1019 * Use memset_s() which cannot be optimized out. Avoid memset_s(NULL, 0, 0, 0)
1020 * which would cause a runtime constraint violation.
1021 */
zap(void * ptr,size_t len)1022 static inline void zap(void *ptr, size_t len)
1023 {
1024 if (len > 0)
1025 memset_s(ptr, len, 0, len);
1026 }
1027 #elif defined(HAVE_EXPLICIT_BZERO)
1028 # define zap(ptr, len) explicit_bzero(ptr, len)
1029 #elif defined(HAVE_EXPLICIT_MEMSET)
1030 # define zap(ptr, len) explicit_memset(ptr, 0, len)
1031 #elif defined(__GNUC__) || defined(__clang__)
1032 /*
1033 * Use an asm statement which declares a memory clobber to force the memset to
1034 * be carried out. Avoid memset(NULL, 0, 0) which has undefined behavior.
1035 */
zap(void * ptr,size_t len)1036 static inline void zap(void *ptr, size_t len)
1037 {
1038 if (len > 0)
1039 memset(ptr, 0, len);
1040 __asm__ __volatile__("" : : "g" (ptr) : "memory");
1041 }
1042 #else
1043 /*
1044 * Use a function from libkrb5support to defeat inlining unless link-time
1045 * optimization is used. The function uses a volatile pointer, which prevents
1046 * current compilers from optimizing out the memset.
1047 */
1048 # define zap(ptr, len) krb5int_zap(ptr, len)
1049 #endif
1050
1051 extern void krb5int_zap(void *ptr, size_t len);
1052
1053 /*
1054 * Return 0 if the n-byte memory regions p1 and p2 are equal, and nonzero if
1055 * they are not. The function is intended to take the same amount of time
1056 * regardless of how many bytes of p1 and p2 are equal.
1057 */
1058 int k5_bcmp(const void *p1, const void *p2, size_t n);
1059
1060 /*
1061 * Split a path into parent directory and basename. Either output parameter
1062 * may be NULL if the caller doesn't need it. parent_out will be empty if path
1063 * has no basename. basename_out will be empty if path ends with a path
1064 * separator. Returns 0 on success or ENOMEM on allocation failure.
1065 */
1066 long k5_path_split(const char *path, char **parent_out, char **basename_out);
1067
1068 /*
1069 * Compose two path components, inserting the platform-appropriate path
1070 * separator if needed. If path2 is an absolute path, path1 will be discarded
1071 * and path_out will be a copy of path2. Returns 0 on success or ENOMEM on
1072 * allocation failure.
1073 */
1074 long k5_path_join(const char *path1, const char *path2, char **path_out);
1075
1076 /* Return 1 if path is absolute, 0 if it is relative. */
1077 int k5_path_isabs(const char *path);
1078
1079 /*
1080 * Localization macros. If we have gettext, define _ appropriately for
1081 * translating a string. If we do not have gettext, define _ and
1082 * bindtextdomain as no-ops. N_ is always a no-op; it marks a string for
1083 * extraction to pot files but does not translate it.
1084 */
1085 #ifdef ENABLE_NLS
1086 #include <libintl.h>
1087 #define KRB5_TEXTDOMAIN "mit-krb5"
1088 #define _(s) dgettext(KRB5_TEXTDOMAIN, s)
1089 #else
1090 #define _(s) s
1091 #define dgettext(d, m) m
1092 #define ngettext(m1, m2, n) (((n) == 1) ? m1 : m2)
1093 #define bindtextdomain(p, d)
1094 #endif
1095 #define N_(s) s
1096
1097 #if !defined(HAVE_GETOPT) || !defined(HAVE_UNISTD_H)
1098 /* Data objects imported from DLLs must be declared as such on Windows. */
1099 #if defined(_WIN32) && !defined(K5_GETOPT_C)
1100 #define K5_GETOPT_DECL __declspec(dllimport)
1101 #else
1102 #define K5_GETOPT_DECL
1103 #endif
1104 K5_GETOPT_DECL extern int k5_opterr;
1105 K5_GETOPT_DECL extern int k5_optind;
1106 K5_GETOPT_DECL extern int k5_optopt;
1107 K5_GETOPT_DECL extern char *k5_optarg;
1108 #define opterr k5_opterr
1109 #define optind k5_optind
1110 #define optopt k5_optopt
1111 #define optarg k5_optarg
1112
1113 extern int k5_getopt(int nargc, char * const nargv[], const char *ostr);
1114 #define getopt k5_getopt
1115 #endif /* HAVE_GETOPT */
1116
1117 #ifdef HAVE_GETOPT_LONG
1118 #include <getopt.h>
1119 #else
1120
1121 struct option
1122 {
1123 const char *name;
1124 int has_arg;
1125 int *flag;
1126 int val;
1127 };
1128
1129 #define no_argument 0
1130 #define required_argument 1
1131 #define optional_argument 2
1132
1133 extern int k5_getopt_long(int nargc, char **nargv, char *options,
1134 struct option *long_options, int *index);
1135 #define getopt_long k5_getopt_long
1136 #endif /* HAVE_GETOPT_LONG */
1137
1138 #if defined(_WIN32)
1139 /* On Windows there is never a need to ignore the process environment. */
1140 #define secure_getenv getenv
1141 #elif !defined(HAVE_SECURE_GETENV)
1142 #define secure_getenv k5_secure_getenv
1143 extern char *k5_secure_getenv(const char *name);
1144 #endif
1145
1146 /* Set *fnames_out to a null-terminated list of filenames within dirname,
1147 * sorted according to strcmp(). Return 0 on success, or ENOENT/ENOMEM. */
1148 int k5_dir_filenames(const char *dirname, char ***fnames_out);
1149 void k5_free_filenames(char **fnames);
1150
1151 #endif /* K5_PLATFORM_H */
1152