Imported Upstream version 1.17
[platform/upstream/krb5.git] / src / include / k5-platform.h
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  * + fetching filenames from a directory
49  */
50
51 #ifndef K5_PLATFORM_H
52 #define K5_PLATFORM_H
53
54 #include "autoconf.h"
55 #include <assert.h>
56 #include <string.h>
57 #include <stdarg.h>
58 #include <stdint.h>
59 #include <limits.h>
60 #include <stdlib.h>
61 #include <stdio.h>
62 #include <fcntl.h>
63 #include <errno.h>
64 #ifdef HAVE_FNMATCH_H
65 #include <fnmatch.h>
66 #endif
67
68 #ifdef HAVE_UNISTD_H
69 #include <unistd.h>
70 #endif
71
72 #ifdef _WIN32
73 #define CAN_COPY_VA_LIST
74 #endif
75
76 /* This attribute prevents unused function warnings in gcc and clang. */
77 #ifdef __GNUC__
78 #define UNUSED __attribute__((__unused__))
79 #else
80 #define UNUSED
81 #endif
82
83 #if defined(macintosh) || (defined(__MACH__) && defined(__APPLE__))
84 #include <TargetConditionals.h>
85 #endif
86
87 /* Initialization and finalization function support for libraries.
88
89    At top level, before the functions are defined or even declared:
90    MAKE_INIT_FUNCTION(init_fn);
91    MAKE_FINI_FUNCTION(fini_fn);
92    Then:
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);
97
98    To trigger or verify the initializer invocation from another file,
99    a helper function must be created.
100
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
108    already.)
109
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.
114
115
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.)
129
130
131    Implementation outline:
132
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.
140
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
148    pthread_once error).
149
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.)
154
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.
159
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.
164
165    UNIX, no library finalization support: The finalization function
166    never runs, and we leak memory.  Tough.
167
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.
172
173
174
175
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.)
182
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
191    function definition.
192
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.
197
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
201    same compiler.
202
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
208    linking to fail.
209
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
215    automatically.
216
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.  */
221
222 /* Helper macros.  */
223
224 # define JOIN__2_2(A,B) A ## _ ## _ ## B
225 # define JOIN__2(A,B) JOIN__2_2(A,B)
226
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.  */
230
231 #if defined(DELAY_INITIALIZER)
232
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) () { }
240 # else
241 #  define MAYBE_DUMMY_INIT(NAME)
242 # endif
243 # ifdef __GNUC__
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)                                      \
247         (__extension__ ({                                               \
248                 k5_init_t *k5int_i = (I);                               \
249                 int k5int_err = k5_once(&k5int_i->once, k5int_i->fn);   \
250                 (k5int_err                                              \
251                  ? k5int_err                                            \
252                  : (assert(k5int_i->did_run != 0), k5int_i->error));    \
253             }))
254 #  define MAYBE_DEFINE_CALLINIT_FUNCTION
255 # else
256 #  define MAYBE_DEFINE_CALLINIT_FUNCTION                        \
257         static inline int k5_call_init_function(k5_init_t *i)   \
258         {                                                       \
259             int err;                                            \
260             err = k5_once(&i->once, i->fn);                     \
261             if (err)                                            \
262                 return err;                                     \
263             assert (i->did_run != 0);                           \
264             return i->error;                                    \
265         }
266 # endif
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)                   \
276         {                                                       \
277             JOIN__2(NAME, once).did_run = 1;                    \
278             JOIN__2(NAME, once).error = NAME();                 \
279         }                                                       \
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.
287
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)
295
296 # define PROGRAM_EXITING()              (0)
297
298 #elif defined(__GNUC__) && !defined(_WIN32) && defined(CONSTRUCTOR_ATTR_WORKS)
299
300 /* Run initializer at load time, via GCC/C++ hook magic.  */
301
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) () { }
306 # else
307 #  define MAYBE_DUMMY_INIT(NAME)
308 # endif
309
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)     \
314                 = { 0, 2 };                     \
315         static void JOIN__2(NAME, aux)(void)    \
316             __attribute__((constructor));       \
317         static int NAME(void);                  \
318         static void JOIN__2(NAME, aux)(void)    \
319         {                                       \
320             JOIN__2(NAME, ran).error = NAME();  \
321             JOIN__2(NAME, ran).did_run = 3;     \
322         }                                       \
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             \
327          : (abort(),0))
328 # define INITIALIZER_RAN(NAME)  (JOIN__2(NAME,ran).did_run == 3 && JOIN__2(NAME, ran).error == 0)
329
330 # define PROGRAM_EXITING()              (0)
331
332 #elif defined(USE_LINKER_INIT_OPTION) || defined(_WIN32)
333
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)     \
339                 = { 0, 2 };                     \
340         static int NAME(void);                  \
341         void JOIN__2(NAME, auxinit)()           \
342         {                                       \
343             JOIN__2(NAME, ran).error = NAME();  \
344             JOIN__2(NAME, ran).did_run = 3;     \
345         }                                       \
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             \
350          : (abort(),0))
351 # define INITIALIZER_RAN(NAME)  \
352         (JOIN__2(NAME, ran).error == 0)
353
354 # define PROGRAM_EXITING()              (0)
355
356 #else
357
358 # error "Don't know how to do load-time initializers for this configuration."
359
360 # define PROGRAM_EXITING()              (0)
361
362 #endif
363
364
365
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
369    regardless.  */
370
371 # ifdef __hpux
372
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.
378
379         The "real" fini function doesn't need to be exported, so
380         declare it static.
381
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.  */
385
386 #  include <dl.h>
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)
392
393 # else /* not hpux */
394
395 #  define MAKE_FINI_FUNCTION(NAME)      \
396         void NAME(void)
397
398 # endif
399
400 #elif !defined(SHARED)
401
402 /*
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.
405  */
406 # define MAKE_FINI_FUNCTION(NAME)               \
407         static void NAME(void) UNUSED
408
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++.
414
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))
418
419 #else
420
421 # error "Don't know how to do unload-time finalization for this configuration."
422
423 #endif
424
425 #ifndef SIZE_MAX
426 # define SIZE_MAX ((size_t)((size_t)0 - 1))
427 #endif
428
429 #ifdef _WIN32
430 # define SSIZE_MAX ((ssize_t)(SIZE_MAX/2))
431 #endif
432
433 /* Read and write integer values as (unaligned) octet strings in
434    specific byte orders.  Add per-platform optimizations as
435    needed.  */
436
437 #if HAVE_ENDIAN_H
438 # include <endian.h>
439 #elif HAVE_MACHINE_ENDIAN_H
440 # include <machine/endian.h>
441 #endif
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
448 #  define K5_BE
449 # endif
450 # if BYTE_ORDER == LITTLE_ENDIAN
451 #  define K5_LE
452 # endif
453 #elif defined(BIG_ENDIAN)
454 # define K5_BE
455 #elif defined(LITTLE_ENDIAN)
456 # define K5_LE
457 #elif defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN)
458 # if _BYTE_ORDER == _BIG_ENDIAN
459 #  define K5_BE
460 # endif
461 # if _BYTE_ORDER == _LITTLE_ENDIAN
462 #  define K5_LE
463 # endif
464 #elif defined(_BIG_ENDIAN)
465 # define K5_BE
466 #elif defined(_LITTLE_ENDIAN)
467 # define K5_LE
468 #elif defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__)
469 # define K5_BE
470 #elif defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)
471 # define K5_LE
472 #endif
473 #if !defined(K5_BE) && !defined(K5_LE)
474 /* Look for some architectures we know about.
475
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
481    us there too).
482
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))
487 #  define K5_LE
488 # endif
489 # if defined(__hppa__) || defined(__rs6000__) || defined(__sparc__) || defined(_MIPSEB) || defined(__m68k__) || defined(__sparc64__) || defined(__ppc__) || defined(__ppc64__) || (defined(__hpux) && defined(__ia64__))
490 #  define K5_BE
491 # endif
492 #endif
493 #if defined(K5_BE) && defined(K5_LE)
494 # error "oops, check the byte order macros"
495 #endif
496
497 /* Optimize for GCC on platforms with known byte orders.
498
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.
502
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
505    GCC.  */
506 #ifdef __GNUC__
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))
511 #endif
512 /* To do: Define SWAP16, SWAP32, SWAP64 macros to byte-swap values
513    with the indicated numbers of bits.
514
515    Linux: byteswap.h, bswap_16 etc.
516    Solaris 10: none
517    macOS: machine/endian.h or byte_order.h, NXSwap{Short,Int,LongLong}
518    NetBSD: sys/bswap.h, bswap16 etc.  */
519
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
526 # endif
527 #elif TARGET_OS_MAC
528 # include <architecture/byte_order.h>
529 # define SWAP16                k5_swap16
530 static inline unsigned int k5_swap16 (unsigned int x) {
531     x &= 0xffff;
532     return (x >> 8) | ((x & 0xff) << 8);
533 }
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
548 # endif
549 #endif
550
551 /* Note that on Windows at least this file can be included from C++
552    source, so casts *from* void* are required.  */
553 static inline void
554 store_16_be (unsigned int val, void *vp)
555 {
556     unsigned char *p = (unsigned char *) vp;
557 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
558     PUT(16,p,val);
559 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)
560     PUTSWAPPED(16,p,val);
561 #else
562     p[0] = (val >>  8) & 0xff;
563     p[1] = (val      ) & 0xff;
564 #endif
565 }
566 static inline void
567 store_32_be (unsigned int val, void *vp)
568 {
569     unsigned char *p = (unsigned char *) vp;
570 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
571     PUT(32,p,val);
572 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)
573     PUTSWAPPED(32,p,val);
574 #else
575     p[0] = (val >> 24) & 0xff;
576     p[1] = (val >> 16) & 0xff;
577     p[2] = (val >>  8) & 0xff;
578     p[3] = (val      ) & 0xff;
579 #endif
580 }
581 static inline void
582 store_64_be (uint64_t val, void *vp)
583 {
584     unsigned char *p = (unsigned char *) vp;
585 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
586     PUT(64,p,val);
587 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)
588     PUTSWAPPED(64,p,val);
589 #else
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);
598 #endif
599 }
600 static inline unsigned short
601 load_16_be (const void *cvp)
602 {
603     const unsigned char *p = (const unsigned char *) cvp;
604 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
605     return GET(16,p);
606 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)
607     return GETSWAPPED(16,p);
608 #else
609     return (p[1] | (p[0] << 8));
610 #endif
611 }
612 static inline unsigned int
613 load_32_be (const void *cvp)
614 {
615     const unsigned char *p = (const unsigned char *) cvp;
616 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
617     return GET(32,p);
618 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)
619     return GETSWAPPED(32,p);
620 #else
621     return (p[3] | (p[2] << 8)
622             | ((uint32_t) p[1] << 16)
623             | ((uint32_t) p[0] << 24));
624 #endif
625 }
626 static inline uint64_t
627 load_64_be (const void *cvp)
628 {
629     const unsigned char *p = (const unsigned char *) cvp;
630 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
631     return GET(64,p);
632 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)
633     return GETSWAPPED(64,p);
634 #else
635     return ((uint64_t)load_32_be(p) << 32) | load_32_be(p+4);
636 #endif
637 }
638 static inline void
639 store_16_le (unsigned int val, void *vp)
640 {
641     unsigned char *p = (unsigned char *) vp;
642 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
643     PUT(16,p,val);
644 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)
645     PUTSWAPPED(16,p,val);
646 #else
647     p[1] = (val >>  8) & 0xff;
648     p[0] = (val      ) & 0xff;
649 #endif
650 }
651 static inline void
652 store_32_le (unsigned int val, void *vp)
653 {
654     unsigned char *p = (unsigned char *) vp;
655 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
656     PUT(32,p,val);
657 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)
658     PUTSWAPPED(32,p,val);
659 #else
660     p[3] = (val >> 24) & 0xff;
661     p[2] = (val >> 16) & 0xff;
662     p[1] = (val >>  8) & 0xff;
663     p[0] = (val      ) & 0xff;
664 #endif
665 }
666 static inline void
667 store_64_le (uint64_t val, void *vp)
668 {
669     unsigned char *p = (unsigned char *) vp;
670 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
671     PUT(64,p,val);
672 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)
673     PUTSWAPPED(64,p,val);
674 #else
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);
683 #endif
684 }
685 static inline unsigned short
686 load_16_le (const void *cvp)
687 {
688     const unsigned char *p = (const unsigned char *) cvp;
689 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
690     return GET(16,p);
691 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)
692     return GETSWAPPED(16,p);
693 #else
694     return (p[0] | (p[1] << 8));
695 #endif
696 }
697 static inline unsigned int
698 load_32_le (const void *cvp)
699 {
700     const unsigned char *p = (const unsigned char *) cvp;
701 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
702     return GET(32,p);
703 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)
704     return GETSWAPPED(32,p);
705 #else
706     return (p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));
707 #endif
708 }
709 static inline uint64_t
710 load_64_le (const void *cvp)
711 {
712     const unsigned char *p = (const unsigned char *) cvp;
713 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
714     return GET(64,p);
715 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)
716     return GETSWAPPED(64,p);
717 #else
718     return ((uint64_t)load_32_le(p+4) << 32) | load_32_le(p);
719 #endif
720 }
721
722 #define UINT16_TYPE uint16_t
723 #define UINT32_TYPE uint32_t
724
725 static inline void
726 store_16_n (unsigned int val, void *vp)
727 {
728     UINT16_TYPE n = val;
729     memcpy(vp, &n, 2);
730 }
731 static inline void
732 store_32_n (unsigned int val, void *vp)
733 {
734     UINT32_TYPE n = val;
735     memcpy(vp, &n, 4);
736 }
737 static inline void
738 store_64_n (uint64_t val, void *vp)
739 {
740     uint64_t n = val;
741     memcpy(vp, &n, 8);
742 }
743 static inline unsigned short
744 load_16_n (const void *p)
745 {
746     UINT16_TYPE n;
747     memcpy(&n, p, 2);
748     return n;
749 }
750 static inline unsigned int
751 load_32_n (const void *p)
752 {
753     UINT32_TYPE n;
754     memcpy(&n, p, 4);
755     return n;
756 }
757 static inline uint64_t
758 load_64_n (const void *p)
759 {
760     uint64_t n;
761     memcpy(&n, p, 8);
762     return n;
763 }
764 #undef UINT16_TYPE
765 #undef UINT32_TYPE
766
767 /* Assume for simplicity that these swaps are identical.  */
768 static inline uint64_t
769 k5_htonll (uint64_t val)
770 {
771 #ifdef K5_BE
772     return val;
773 #elif defined K5_LE && defined SWAP64
774     return SWAP64 (val);
775 #else
776     return load_64_be ((unsigned char *)&val);
777 #endif
778 }
779 static inline uint64_t
780 k5_ntohll (uint64_t val)
781 {
782     return k5_htonll (val);
783 }
784
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.  */
789
790 /* int k5_getpwnam_r(const char *, blah blah) */
791 #ifdef HAVE_GETPWNAM_R
792 # ifndef GETPWNAM_R_4_ARGS
793 /* POSIX */
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)
797 # else
798 /* POSIX drafts? */
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))
804 #  else
805 #   define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT)  \
806         (*(OUT) = getpwnam_r(NAME,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)
807 #  endif
808 # endif
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)
813 #endif
814
815 /* int k5_getpwuid_r(uid_t, blah blah) */
816 #ifdef HAVE_GETPWUID_R
817 # ifndef GETPWUID_R_4_ARGS
818 /* POSIX */
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)
822 # else
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))
830 #  else
831 #   define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT)  \
832         (*(OUT) = getpwuid_r(UID,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)
833 #  endif
834 # endif
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)
839 #endif
840
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
845    anyways.  */
846
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
850    with F_SETFD.  */
851 #ifdef F_SETFD
852 # ifdef FD_CLOEXEC
853 #  define set_cloexec_fd(FD)    ((void)fcntl((FD), F_SETFD, FD_CLOEXEC))
854 # else
855 #  define set_cloexec_fd(FD)    ((void)fcntl((FD), F_SETFD, 1))
856 # endif
857 #else
858 # define set_cloexec_fd(FD)     ((void)(FD))
859 #endif
860 #define set_cloexec_file(F)     set_cloexec_fd(fileno(F))
861
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.
865
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)
869 /* Do nothing.  */
870 #elif defined(CAN_COPY_VA_LIST)
871 #define va_copy(dest, src)      ((dest) = (src))
872 #else
873 /* Assume array type, but still simply copyable.
874
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
878    for that case.  */
879 #define va_copy(dest, src)      memcpy(dest, src, sizeof(va_list))
880 #endif
881
882 /* Provide strlcpy/strlcat interfaces. */
883 #ifndef HAVE_STRLCPY
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);
888 #endif
889
890 /* Provide fnmatch interface. */
891 #ifndef HAVE_FNMATCH
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. */
902 #endif
903
904 /* Provide [v]asprintf interfaces.  */
905 #ifndef HAVE_VSNPRINTF
906 #ifdef _WIN32
907 static inline int
908 vsnprintf(char *str, size_t size, const char *format, va_list args)
909 {
910     va_list args_copy;
911     int length;
912
913     va_copy(args_copy, args);
914     length = _vscprintf(format, args_copy);
915     va_end(args_copy);
916     if (size > 0) {
917         _vsnprintf(str, size, format, args);
918         str[size - 1] = '\0';
919     }
920     return length;
921 }
922 static inline int
923 snprintf(char *str, size_t size, const char *format, ...)
924 {
925     va_list args;
926     int n;
927
928     va_start(args, format);
929     n = vsnprintf(str, size, format, args);
930     va_end(args);
931     return n;
932 }
933 #else /* not win32 */
934 #error We need an implementation of vsnprintf.
935 #endif /* win32? */
936 #endif /* no vsnprintf */
937
938 #ifndef HAVE_VASPRINTF
939
940 extern int krb5int_vasprintf(char **, const char *, va_list)
941 #if !defined(__cplusplus) && (__GNUC__ > 2)
942     __attribute__((__format__(__printf__, 2, 0)))
943 #endif
944     ;
945 extern int krb5int_asprintf(char **, const char *, ...)
946 #if !defined(__cplusplus) && (__GNUC__ > 2)
947     __attribute__((__format__(__printf__, 2, 3)))
948 #endif
949     ;
950
951 #define vasprintf krb5int_vasprintf
952 /* Assume HAVE_ASPRINTF iff HAVE_VASPRINTF.  */
953 #define asprintf krb5int_asprintf
954
955 #elif defined(NEED_VASPRINTF_PROTO)
956
957 extern int vasprintf(char **, const char *, va_list)
958 #if !defined(__cplusplus) && (__GNUC__ > 2)
959     __attribute__((__format__(__printf__, 2, 0)))
960 #endif
961     ;
962 extern int asprintf(char **, const char *, ...)
963 #if !defined(__cplusplus) && (__GNUC__ > 2)
964     __attribute__((__format__(__printf__, 2, 3)))
965 #endif
966     ;
967
968 #endif /* have vasprintf and prototype? */
969
970 /* Return true if the snprintf return value RESULT reflects a buffer
971    overflow for the buffer size SIZE.
972
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
981    int or larger).
982 */
983 #define SNPRINTF_OVERFLOW(result, size) \
984     ((unsigned int)(result) >= (size_t)(size))
985
986 #if defined(_WIN32) || !defined(HAVE_STRERROR_R) || defined(STRERROR_R_CHAR_P)
987 #define strerror_r k5_strerror_r
988 #endif
989 extern int k5_strerror_r(int errnum, char *buf, size_t buflen);
990
991 #ifndef HAVE_MKSTEMP
992 extern int krb5int_mkstemp(char *);
993 #define mkstemp krb5int_mkstemp
994 #endif
995
996 #ifndef HAVE_GETTIMEOFDAY
997 extern int krb5int_gettimeofday(struct timeval *tp, void *ignore);
998 #define gettimeofday krb5int_gettimeofday
999 #endif
1000
1001 /*
1002  * Attempt to zero memory in a way that compilers won't optimize out.
1003  *
1004  * This mechanism should work even for heap storage about to be freed,
1005  * or automatic storage right before we return from a function.
1006  *
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.
1010  *
1011  * We're not going so far -- yet -- as to try to protect key data that
1012  * may have been written into swap space....
1013  */
1014 #ifdef _WIN32
1015 # define zap(ptr, len) SecureZeroMemory(ptr, len)
1016 #elif defined(__STDC_LIB_EXT1__)
1017 /*
1018  * Use memset_s() which cannot be optimized out.  Avoid memset_s(NULL, 0, 0, 0)
1019  * which would cause a runtime constraint violation.
1020  */
1021 static inline void zap(void *ptr, size_t len)
1022 {
1023     if (len > 0)
1024         memset_s(ptr, len, 0, len);
1025 }
1026 #elif defined(__GNUC__) || defined(__clang__)
1027 /*
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.
1030  */
1031 static inline void zap(void *ptr, size_t len)
1032 {
1033     if (len > 0)
1034         memset(ptr, 0, len);
1035     __asm__ __volatile__("" : : "r" (ptr) : "memory");
1036 }
1037 #else
1038 /*
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.
1042  */
1043 # define zap(ptr, len) krb5int_zap(ptr, len)
1044 #endif
1045
1046 extern void krb5int_zap(void *ptr, size_t len);
1047
1048 /*
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.
1052  */
1053 int k5_bcmp(const void *p1, const void *p2, size_t n);
1054
1055 /*
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.
1060  */
1061 long k5_path_split(const char *path, char **parent_out, char **basename_out);
1062
1063 /*
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.
1068  */
1069 long k5_path_join(const char *path1, const char *path2, char **path_out);
1070
1071 /* Return 1 if path is absolute, 0 if it is relative. */
1072 int k5_path_isabs(const char *path);
1073
1074 /*
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.
1079  */
1080 #ifdef ENABLE_NLS
1081 #include <libintl.h>
1082 #define KRB5_TEXTDOMAIN "mit-krb5"
1083 #define _(s) dgettext(KRB5_TEXTDOMAIN, s)
1084 #else
1085 #define _(s) s
1086 #define dgettext(d, m) m
1087 #define ngettext(m1, m2, n) (((n) == 1) ? m1 : m2)
1088 #define bindtextdomain(p, d)
1089 #endif
1090 #define N_(s) s
1091
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)
1096 #else
1097 #define K5_GETOPT_DECL
1098 #endif
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
1107
1108 extern int k5_getopt(int nargc, char * const nargv[], const char *ostr);
1109 #define getopt k5_getopt
1110 #endif /* HAVE_GETOPT */
1111
1112 #ifdef HAVE_GETOPT_LONG
1113 #include <getopt.h>
1114 #else
1115
1116 struct option
1117 {
1118   const char *name;
1119   int has_arg;
1120   int *flag;
1121   int val;
1122 };
1123
1124 #define no_argument       0
1125 #define required_argument 1
1126 #define optional_argument 2
1127
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 */
1132
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);
1137
1138 #endif /* K5_PLATFORM_H */