make mark-cstyle
[krb5.git] / src / include / k5-platform.h
1 /*
2  * 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  * Some platform-dependent definitions to sync up the C support level.
28  * Some to a C99-ish level, some related utility code.
29  *
30  * Currently:
31  * + [u]int{8,16,32}_t types
32  * + 64-bit types and load/store code
33  * + SIZE_MAX
34  * + shared library init/fini hooks
35  * + consistent getpwnam/getpwuid interfaces
36  * + va_copy fudged if not provided
37  * + [v]asprintf
38  */
39
40 #ifndef K5_PLATFORM_H
41 #define K5_PLATFORM_H
42
43 #include "autoconf.h"
44 #include <assert.h>
45 #include <string.h>
46 #include <stdarg.h>
47 #include <limits.h>
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <fcntl.h>
51 #include <errno.h>
52
53 #ifdef _WIN32
54 #define CAN_COPY_VA_LIST
55 #endif
56
57 #if defined(macintosh) || (defined(__MACH__) && defined(__APPLE__))
58 #include <TargetConditionals.h>
59 #endif
60
61 /* Initialization and finalization function support for libraries.
62
63    At top level, before the functions are defined or even declared:
64    MAKE_INIT_FUNCTION(init_fn);
65    MAKE_FINI_FUNCTION(fini_fn);
66    Then:
67    int init_fn(void) { ... }
68    void fini_fn(void) { if (INITIALIZER_RAN(init_fn)) ... }
69    In code, in the same file:
70    err = CALL_INIT_FUNCTION(init_fn);
71
72    To trigger or verify the initializer invocation from another file,
73    a helper function must be created.
74
75    This model handles both the load-time execution (Windows) and
76    delayed execution (pthread_once) approaches, and should be able to
77    guarantee in both cases that the init function is run once, in one
78    thread, before other stuff in the library is done; furthermore, the
79    finalization code should only run if the initialization code did.
80    (Maybe I could've made the "if INITIALIZER_RAN" test implicit, via
81    another function hidden in macros, but this is hairy enough
82    already.)
83
84    The init_fn and fini_fn names should be chosen such that any
85    exported names staring with those names, and optionally followed by
86    additional characters, fits in with any namespace constraints on
87    the library in question.
88
89
90    There's also PROGRAM_EXITING() currently always defined as zero.
91    If there's some trivial way to find out if the fini function is
92    being called because the program that the library is linked into is
93    exiting, we can just skip all the work because the resources are
94    about to be freed up anyways.  Generally this is likely to be the
95    same as distinguishing whether the library was loaded dynamically
96    while the program was running, or loaded as part of program
97    startup.  On most platforms, I don't think we can distinguish these
98    cases easily, and it's probably not worth expending any significant
99    effort.  (Note in particular that atexit() won't do, because if the
100    library is explicitly loaded and unloaded, it would have to be able
101    to deregister the atexit callback function.  Also, the system limit
102    on atexit callbacks may be small.)
103
104
105    Implementation outline:
106
107    Windows: MAKE_FINI_FUNCTION creates a symbol with a magic name that
108    is sought at library build time, and code is added to invoke the
109    function when the library is unloaded.  MAKE_INIT_FUNCTION does
110    likewise, but the function is invoked when the library is loaded,
111    and an extra variable is declared to hold an error code and a "yes
112    the initializer ran" flag.  CALL_INIT_FUNCTION blows up if the flag
113    isn't set, otherwise returns the error code.
114
115    UNIX: MAKE_INIT_FUNCTION creates and initializes a variable with a
116    name derived from the function name, containing a k5_once_t
117    (pthread_once_t or int), an error code, and a pointer to the
118    function.  The function itself is declared static, but the
119    associated variable has external linkage.  CALL_INIT_FUNCTION
120    ensures thath the function is called exactly once (pthread_once or
121    just check the flag) and returns the stored error code (or the
122    pthread_once error).
123
124    (That's the basic idea.  With some debugging assert() calls and
125    such, it's a bit more complicated.  And we also need to handle
126    doing the pthread test at run time on systems where that works, so
127    we use the k5_once_t stuff instead.)
128
129    UNIX, with compiler support: MAKE_FINI_FUNCTION declares the
130    function as a destructor, and the run time linker support or
131    whatever will cause it to be invoked when the library is unloaded,
132    the program ends, etc.
133
134    UNIX, with linker support: MAKE_FINI_FUNCTION creates a symbol with
135    a magic name that is sought at library build time, and linker
136    options are used to mark it as a finalization function for the
137    library.  The symbol must be exported.
138
139    UNIX, no library finalization support: The finalization function
140    never runs, and we leak memory.  Tough.
141
142    DELAY_INITIALIZER will be defined by the configure script if we
143    want to use k5_once instead of load-time initialization.  That'll
144    be the preferred method on most systems except Windows, where we
145    have to initialize some mutexes.
146
147
148
149
150    For maximum flexibility in defining the macros, the function name
151    parameter should be a simple name, not even a macro defined as
152    another name.  The function should have a unique name, and should
153    conform to whatever namespace is used by the library in question.
154    (We do have export lists, but (1) they're not used for all
155    platforms, and (2) they're not used for static libraries.)
156
157    If the macro expansion needs the function to have been declared, it
158    must include a declaration.  If it is not necessary for the symbol
159    name to be exported from the object file, the macro should declare
160    it as "static".  Hence the signature must exactly match "void
161    foo(void)".  (ANSI C allows a static declaration followed by a
162    non-static one; the result is internal linkage.)  The macro
163    expansion has to come before the function, because gcc apparently
164    won't act on "__attribute__((constructor))" if it comes after the
165    function definition.
166
167    This is going to be compiler- and environment-specific, and may
168    require some support at library build time, and/or "asm"
169    statements.  But through macro expansion and auxiliary functions,
170    we should be able to handle most things except #pragma.
171
172    It's okay for this code to require that the library be built
173    with the same compiler and compiler options throughout, but
174    we shouldn't require that the library and application use the
175    same compiler.
176
177    For static libraries, we don't really care about cleanup too much,
178    since it's all memory handling and mutex allocation which will all
179    be cleaned up when the program exits.  Thus, it's okay if gcc-built
180    static libraries don't play nicely with cc-built executables when
181    it comes to static constructors, just as long as it doesn't cause
182    linking to fail.
183
184    For dynamic libraries on UNIX, we'll use pthread_once-type support
185    to do delayed initialization, so if finalization can't be made to
186    work, we'll only have memory leaks in a load/use/unload cycle.  If
187    anyone (like, say, the OS vendor) complains about this, they can
188    tell us how to get a shared library finalization function invoked
189    automatically.
190
191    Currently there's --disable-delayed-initialization for preventing
192    the initialization from being delayed on UNIX, but that's mainly
193    just for testing the linker options for initialization, and will
194    probably be removed at some point.  */
195
196 /* Helper macros.  */
197
198 # define JOIN__2_2(A,B) A ## _ ## _ ## B
199 # define JOIN__2(A,B) JOIN__2_2(A,B)
200
201 /* XXX Should test USE_LINKER_INIT_OPTION early, and if it's set,
202    always provide a function by the expected name, even if we're
203    delaying initialization.  */
204
205 #if defined(DELAY_INITIALIZER)
206
207 /* Run the initialization code during program execution, at the latest
208    possible moment.  This means multiple threads may be active.  */
209 # include "k5-thread.h"
210 typedef struct { k5_once_t once; int error, did_run; void (*fn)(void); } k5_init_t;
211 # ifdef USE_LINKER_INIT_OPTION
212 #  define MAYBE_DUMMY_INIT(NAME)                \
213         void JOIN__2(NAME, auxinit) () { }
214 # else
215 #  define MAYBE_DUMMY_INIT(NAME)
216 # endif
217 # ifdef __GNUC__
218 /* Do it in macro form so we get the file/line of the invocation if
219    the assertion fails.  */
220 #  define k5_call_init_function(I)                                      \
221         (__extension__ ({                                               \
222                 k5_init_t *k5int_i = (I);                               \
223                 int k5int_err = k5_once(&k5int_i->once, k5int_i->fn);   \
224                 (k5int_err                                              \
225                  ? k5int_err                                            \
226                  : (assert(k5int_i->did_run != 0), k5int_i->error));    \
227             }))
228 #  define MAYBE_DEFINE_CALLINIT_FUNCTION
229 # else
230 #  define MAYBE_DEFINE_CALLINIT_FUNCTION                        \
231         static inline int k5_call_init_function(k5_init_t *i)   \
232         {                                                       \
233             int err;                                            \
234             err = k5_once(&i->once, i->fn);                     \
235             if (err)                                            \
236                 return err;                                     \
237             assert (i->did_run != 0);                           \
238             return i->error;                                    \
239         }
240 # endif
241 # define MAKE_INIT_FUNCTION(NAME)                               \
242         static int NAME(void);                                  \
243         MAYBE_DUMMY_INIT(NAME)                                  \
244         /* forward declaration for use in initializer */        \
245         static void JOIN__2(NAME, aux) (void);                  \
246         static k5_init_t JOIN__2(NAME, once) =                  \
247                 { K5_ONCE_INIT, 0, 0, JOIN__2(NAME, aux) };     \
248         MAYBE_DEFINE_CALLINIT_FUNCTION                          \
249         static void JOIN__2(NAME, aux) (void)                   \
250         {                                                       \
251             JOIN__2(NAME, once).did_run = 1;                    \
252             JOIN__2(NAME, once).error = NAME();                 \
253         }                                                       \
254         /* so ';' following macro use won't get error */        \
255         static int NAME(void)
256 # define CALL_INIT_FUNCTION(NAME)       \
257         k5_call_init_function(& JOIN__2(NAME, once))
258 /* This should be called in finalization only, so we shouldn't have
259    multiple active threads mucking around in our library at this
260    point.  So ignore the once_t object and just look at the flag.
261
262    XXX Could we have problems with memory coherence between processors
263    if we don't invoke mutex/once routines?  Probably not, the
264    application code should already be coordinating things such that
265    the library code is not in use by this point, and memory
266    synchronization will be needed there.  */
267 # define INITIALIZER_RAN(NAME)  \
268         (JOIN__2(NAME, once).did_run && JOIN__2(NAME, once).error == 0)
269
270 # define PROGRAM_EXITING()              (0)
271
272 #elif defined(__GNUC__) && !defined(_WIN32) && defined(CONSTRUCTOR_ATTR_WORKS)
273
274 /* Run initializer at load time, via GCC/C++ hook magic.  */
275
276 # ifdef USE_LINKER_INIT_OPTION
277      /* Both gcc and linker option??  Favor gcc.  */
278 #  define MAYBE_DUMMY_INIT(NAME)                \
279         void JOIN__2(NAME, auxinit) () { }
280 # else
281 #  define MAYBE_DUMMY_INIT(NAME)
282 # endif
283
284 typedef struct { int error; unsigned char did_run; } k5_init_t;
285 # define MAKE_INIT_FUNCTION(NAME)               \
286         MAYBE_DUMMY_INIT(NAME)                  \
287         static k5_init_t JOIN__2(NAME, ran)     \
288                 = { 0, 2 };                     \
289         static void JOIN__2(NAME, aux)(void)    \
290             __attribute__((constructor));       \
291         static int NAME(void);                  \
292         static void JOIN__2(NAME, aux)(void)    \
293         {                                       \
294             JOIN__2(NAME, ran).error = NAME();  \
295             JOIN__2(NAME, ran).did_run = 3;     \
296         }                                       \
297         static int NAME(void)
298 # define CALL_INIT_FUNCTION(NAME)               \
299         (JOIN__2(NAME, ran).did_run == 3        \
300          ? JOIN__2(NAME, ran).error             \
301          : (abort(),0))
302 # define INITIALIZER_RAN(NAME)  (JOIN__2(NAME,ran).did_run == 3 && JOIN__2(NAME, ran).error == 0)
303
304 # define PROGRAM_EXITING()              (0)
305
306 #elif defined(USE_LINKER_INIT_OPTION) || defined(_WIN32)
307
308 /* Run initializer at load time, via linker magic, or in the
309    case of WIN32, win_glue.c hard-coded knowledge.  */
310 typedef struct { int error; unsigned char did_run; } k5_init_t;
311 # define MAKE_INIT_FUNCTION(NAME)               \
312         static k5_init_t JOIN__2(NAME, ran)     \
313                 = { 0, 2 };                     \
314         static int NAME(void);                  \
315         void JOIN__2(NAME, auxinit)()           \
316         {                                       \
317             JOIN__2(NAME, ran).error = NAME();  \
318             JOIN__2(NAME, ran).did_run = 3;     \
319         }                                       \
320         static int NAME(void)
321 # define CALL_INIT_FUNCTION(NAME)               \
322         (JOIN__2(NAME, ran).did_run == 3        \
323          ? JOIN__2(NAME, ran).error             \
324          : (abort(),0))
325 # define INITIALIZER_RAN(NAME)  \
326         (JOIN__2(NAME, ran).error == 0)
327
328 # define PROGRAM_EXITING()              (0)
329
330 #else
331
332 # error "Don't know how to do load-time initializers for this configuration."
333
334 # define PROGRAM_EXITING()              (0)
335
336 #endif
337
338
339
340 #if defined(USE_LINKER_FINI_OPTION) || defined(_WIN32)
341 /* If we're told the linker option will be used, it doesn't really
342    matter what compiler we're using.  Do it the same way
343    regardless.  */
344
345 # ifdef __hpux
346
347      /* On HP-UX, we need this auxiliary function.  At dynamic load or
348         unload time (but *not* program startup and termination for
349         link-time specified libraries), the linker-indicated function
350         is called with a handle on the library and a flag indicating
351         whether it's being loaded or unloaded.
352
353         The "real" fini function doesn't need to be exported, so
354         declare it static.
355
356         As usual, the final declaration is just for syntactic
357         convenience, so the top-level invocation of this macro can be
358         followed by a semicolon.  */
359
360 #  include <dl.h>
361 #  define MAKE_FINI_FUNCTION(NAME)                                          \
362         static void NAME(void);                                             \
363         void JOIN__2(NAME, auxfini)(shl_t, int); /* silence gcc warnings */ \
364         void JOIN__2(NAME, auxfini)(shl_t h, int l) { if (!l) NAME(); }     \
365         static void NAME(void)
366
367 # else /* not hpux */
368
369 #  define MAKE_FINI_FUNCTION(NAME)      \
370         void NAME(void)
371
372 # endif
373
374 #elif defined(__GNUC__) && defined(DESTRUCTOR_ATTR_WORKS)
375 /* If we're using gcc, if the C++ support works, the compiler should
376    build executables and shared libraries that support the use of
377    static constructors and destructors.  The C compiler supports a
378    function attribute that makes use of the same facility as C++.
379
380    XXX How do we know if the C++ support actually works?  */
381 # define MAKE_FINI_FUNCTION(NAME)       \
382         static void NAME(void) __attribute__((destructor))
383
384 #elif !defined(SHARED)
385
386 /* In this case, we just don't care about finalization.
387
388    The code will still define the function, but we won't do anything
389    with it.  Annoying: This may generate unused-function warnings.  */
390
391 # define MAKE_FINI_FUNCTION(NAME)       \
392         static void NAME(void)
393
394 #else
395
396 # error "Don't know how to do unload-time finalization for this configuration."
397
398 #endif
399
400
401 /* 64-bit support: krb5_ui_8 and krb5_int64.
402
403    This should move to krb5.h eventually, but without the namespace
404    pollution from the autoconf macros.  */
405 #if defined(HAVE_STDINT_H) || defined(HAVE_INTTYPES_H)
406 # ifdef HAVE_STDINT_H
407 #  include <stdint.h>
408 # endif
409 # ifdef HAVE_INTTYPES_H
410 #  include <inttypes.h>
411 # endif
412 # define INT64_TYPE int64_t
413 # define UINT64_TYPE uint64_t
414 #elif defined(_WIN32)
415 # define INT64_TYPE signed __int64
416 # define UINT64_TYPE unsigned __int64
417 #else /* not Windows, and neither stdint.h nor inttypes.h */
418 # define INT64_TYPE signed long long
419 # define UINT64_TYPE unsigned long long
420 #endif
421
422 #ifndef SIZE_MAX
423 # define SIZE_MAX ((size_t)((size_t)0 - 1))
424 #endif
425
426 #ifndef UINT64_MAX
427 # define UINT64_MAX ((UINT64_TYPE)((UINT64_TYPE)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    Mac OS X: 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 #endif
529 #if TARGET_OS_MAC
530 # include <architecture/byte_order.h>
531 # if 0 /* This causes compiler warnings.  */
532 #  define SWAP16                OSSwapInt16
533 # else
534 #  define SWAP16                k5_swap16
535 static inline unsigned int k5_swap16 (unsigned int x) {
536     x &= 0xffff;
537     return (x >> 8) | ((x & 0xff) << 8);
538 }
539 # endif
540 # define SWAP32                 OSSwapInt32
541 # define SWAP64                 OSSwapInt64
542 #endif
543
544 /* Note that on Windows at least this file can be included from C++
545    source, so casts *from* void* are required.  */
546 static inline void
547 store_16_be (unsigned int val, void *vp)
548 {
549     unsigned char *p = (unsigned char *) vp;
550 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
551     PUT(16,p,val);
552 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)
553     PUTSWAPPED(16,p,val);
554 #else
555     p[0] = (val >>  8) & 0xff;
556     p[1] = (val      ) & 0xff;
557 #endif
558 }
559 static inline void
560 store_32_be (unsigned int val, void *vp)
561 {
562     unsigned char *p = (unsigned char *) vp;
563 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
564     PUT(32,p,val);
565 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)
566     PUTSWAPPED(32,p,val);
567 #else
568     p[0] = (val >> 24) & 0xff;
569     p[1] = (val >> 16) & 0xff;
570     p[2] = (val >>  8) & 0xff;
571     p[3] = (val      ) & 0xff;
572 #endif
573 }
574 static inline void
575 store_64_be (UINT64_TYPE val, void *vp)
576 {
577     unsigned char *p = (unsigned char *) vp;
578 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
579     PUT(64,p,val);
580 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)
581     PUTSWAPPED(64,p,val);
582 #else
583     p[0] = (unsigned char)((val >> 56) & 0xff);
584     p[1] = (unsigned char)((val >> 48) & 0xff);
585     p[2] = (unsigned char)((val >> 40) & 0xff);
586     p[3] = (unsigned char)((val >> 32) & 0xff);
587     p[4] = (unsigned char)((val >> 24) & 0xff);
588     p[5] = (unsigned char)((val >> 16) & 0xff);
589     p[6] = (unsigned char)((val >>  8) & 0xff);
590     p[7] = (unsigned char)((val      ) & 0xff);
591 #endif
592 }
593 static inline unsigned short
594 load_16_be (const void *cvp)
595 {
596     const unsigned char *p = (const unsigned char *) cvp;
597 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
598     return GET(16,p);
599 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)
600     return GETSWAPPED(16,p);
601 #else
602     return (p[1] | (p[0] << 8));
603 #endif
604 }
605 static inline unsigned int
606 load_32_be (const void *cvp)
607 {
608     const unsigned char *p = (const unsigned char *) cvp;
609 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
610     return GET(32,p);
611 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)
612     return GETSWAPPED(32,p);
613 #else
614     return (p[3] | (p[2] << 8)
615             | ((uint32_t) p[1] << 16)
616             | ((uint32_t) p[0] << 24));
617 #endif
618 }
619 static inline UINT64_TYPE
620 load_64_be (const void *cvp)
621 {
622     const unsigned char *p = (const unsigned char *) cvp;
623 #if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)
624     return GET(64,p);
625 #elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)
626     return GETSWAPPED(64,p);
627 #else
628     return ((UINT64_TYPE)load_32_be(p) << 32) | load_32_be(p+4);
629 #endif
630 }
631 static inline void
632 store_16_le (unsigned int val, void *vp)
633 {
634     unsigned char *p = (unsigned char *) vp;
635 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
636     PUT(16,p,val);
637 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)
638     PUTSWAPPED(16,p,val);
639 #else
640     p[1] = (val >>  8) & 0xff;
641     p[0] = (val      ) & 0xff;
642 #endif
643 }
644 static inline void
645 store_32_le (unsigned int val, void *vp)
646 {
647     unsigned char *p = (unsigned char *) vp;
648 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
649     PUT(32,p,val);
650 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)
651     PUTSWAPPED(32,p,val);
652 #else
653     p[3] = (val >> 24) & 0xff;
654     p[2] = (val >> 16) & 0xff;
655     p[1] = (val >>  8) & 0xff;
656     p[0] = (val      ) & 0xff;
657 #endif
658 }
659 static inline void
660 store_64_le (UINT64_TYPE val, void *vp)
661 {
662     unsigned char *p = (unsigned char *) vp;
663 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
664     PUT(64,p,val);
665 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)
666     PUTSWAPPED(64,p,val);
667 #else
668     p[7] = (unsigned char)((val >> 56) & 0xff);
669     p[6] = (unsigned char)((val >> 48) & 0xff);
670     p[5] = (unsigned char)((val >> 40) & 0xff);
671     p[4] = (unsigned char)((val >> 32) & 0xff);
672     p[3] = (unsigned char)((val >> 24) & 0xff);
673     p[2] = (unsigned char)((val >> 16) & 0xff);
674     p[1] = (unsigned char)((val >>  8) & 0xff);
675     p[0] = (unsigned char)((val      ) & 0xff);
676 #endif
677 }
678 static inline unsigned short
679 load_16_le (const void *cvp)
680 {
681     const unsigned char *p = (const unsigned char *) cvp;
682 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
683     return GET(16,p);
684 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)
685     return GETSWAPPED(16,p);
686 #else
687     return (p[0] | (p[1] << 8));
688 #endif
689 }
690 static inline unsigned int
691 load_32_le (const void *cvp)
692 {
693     const unsigned char *p = (const unsigned char *) cvp;
694 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
695     return GET(32,p);
696 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)
697     return GETSWAPPED(32,p);
698 #else
699     return (p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));
700 #endif
701 }
702 static inline UINT64_TYPE
703 load_64_le (const void *cvp)
704 {
705     const unsigned char *p = (const unsigned char *) cvp;
706 #if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)
707     return GET(64,p);
708 #elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)
709     return GETSWAPPED(64,p);
710 #else
711     return ((UINT64_TYPE)load_32_le(p+4) << 32) | load_32_le(p);
712 #endif
713 }
714
715 static inline unsigned short
716 load_16_n (const void *p)
717 {
718 #ifdef _WIN32
719     unsigned __int16 n;
720 #else
721     uint16_t n;
722 #endif
723     memcpy(&n, p, 2);
724     return n;
725 }
726 static inline unsigned int
727 load_32_n (const void *p)
728 {
729 #ifdef _WIN32
730     unsigned __int32 n;
731 #else
732     uint32_t n;
733 #endif
734     memcpy(&n, p, 4);
735     return n;
736 }
737 static inline UINT64_TYPE
738 load_64_n (const void *p)
739 {
740     UINT64_TYPE n;
741     memcpy(&n, p, 8);
742     return n;
743 }
744
745 /* Assume for simplicity that these swaps are identical.  */
746 static inline UINT64_TYPE
747 k5_htonll (UINT64_TYPE val)
748 {
749 #ifdef K5_BE
750     return val;
751 #elif defined K5_LE && defined SWAP64
752     return SWAP64 (val);
753 #else
754     return load_64_be ((unsigned char *)&val);
755 #endif
756 }
757 static inline UINT64_TYPE
758 k5_ntohll (UINT64_TYPE val)
759 {
760     return k5_htonll (val);
761 }
762
763 /* Make the interfaces to getpwnam and getpwuid consistent.
764    Model the wrappers on the POSIX thread-safe versions, but
765    use the unsafe system versions if the safe ones don't exist
766    or we can't figure out their interfaces.  */
767
768 /* int k5_getpwnam_r(const char *, blah blah) */
769 #ifdef HAVE_GETPWNAM_R
770 # ifndef GETPWNAM_R_4_ARGS
771 /* POSIX */
772 #  define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT)   \
773         (getpwnam_r(NAME,REC,BUF,BUFSIZE,OUT) == 0      \
774          ? (*(OUT) == NULL ? -1 : 0) : -1)
775 # else
776 /* POSIX drafts? */
777 #  ifdef GETPWNAM_R_RETURNS_INT
778 #   define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT)  \
779         (getpwnam_r(NAME,REC,BUF,BUFSIZE) == 0          \
780          ? (*(OUT) = REC, 0)                            \
781          : (*(OUT) = NULL, -1))
782 #  else
783 #   define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT)  \
784         (*(OUT) = getpwnam_r(NAME,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)
785 #  endif
786 # endif
787 #else /* no getpwnam_r, or can't figure out #args or return type */
788 /* Will get warnings about unused variables.  */
789 # define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \
790         (*(OUT) = getpwnam(NAME), *(OUT) == NULL ? -1 : 0)
791 #endif
792
793 /* int k5_getpwuid_r(uid_t, blah blah) */
794 #ifdef HAVE_GETPWUID_R
795 # ifndef GETPWUID_R_4_ARGS
796 /* POSIX */
797 #  define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT)    \
798         (getpwuid_r(UID,REC,BUF,BUFSIZE,OUT) == 0       \
799          ? (*(OUT) == NULL ? -1 : 0) : -1)
800 # else
801 /* POSIX drafts?  Yes, I mean to test GETPWNAM... here.  Less junk to
802    do at configure time.  */
803 #  ifdef GETPWNAM_R_RETURNS_INT
804 #   define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT)   \
805         (getpwuid_r(UID,REC,BUF,BUFSIZE) == 0           \
806          ? (*(OUT) = REC, 0)                            \
807          : (*(OUT) = NULL, -1))
808 #  else
809 #   define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT)  \
810         (*(OUT) = getpwuid_r(UID,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)
811 #  endif
812 # endif
813 #else /* no getpwuid_r, or can't figure out #args or return type */
814 /* Will get warnings about unused variables.  */
815 # define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \
816         (*(OUT) = getpwuid(UID), *(OUT) == NULL ? -1 : 0)
817 #endif
818
819 /* Ensure, if possible, that the indicated file descriptor won't be
820    kept open if we exec another process (e.g., launching a ccapi
821    server).  If we don't know how to do it... well, just go about our
822    business.  Probably most callers won't check the return status
823    anyways.  */
824
825 #if 0
826 static inline int
827 set_cloexec_fd(int fd)
828 {
829 #if defined(F_SETFD)
830 # ifdef FD_CLOEXEC
831     if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
832         return errno;
833 # else
834     if (fcntl(fd, F_SETFD, 1) != 0)
835         return errno;
836 # endif
837 #endif
838     return 0;
839 }
840
841 static inline int
842 set_cloexec_file(FILE *f)
843 {
844     return set_cloexec_fd(fileno(f));
845 }
846 #else
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)    (fcntl((FD), F_SETFD, FD_CLOEXEC) ? errno : 0)
854 # else
855 #  define set_cloexec_fd(FD)    (fcntl((FD), F_SETFD, 1) ? errno : 0)
856 # endif
857 #else
858 # define set_cloexec_fd(FD)     ((FD),0)
859 #endif
860 #define set_cloexec_file(F)     set_cloexec_fd(fileno(F))
861 #endif
862
863
864
865 /* Since the original ANSI C spec left it undefined whether or
866    how you could copy around a va_list, C 99 added va_copy.
867    For old implementations, let's do our best to fake it.
868
869    XXX Doesn't yet handle implementations with __va_copy (early draft)
870    or GCC's __builtin_va_copy.  */
871 #if defined(HAS_VA_COPY) || defined(va_copy)
872 /* Do nothing.  */
873 #elif defined(CAN_COPY_VA_LIST)
874 #define va_copy(dest, src)      ((dest) = (src))
875 #else
876 /* Assume array type, but still simply copyable.
877
878    There is, theoretically, the possibility that va_start will
879    allocate some storage pointed to by the va_list, and in that case
880    we'll just lose.  If anyone cares, we could try to devise a test
881    for that case.  */
882 #define va_copy(dest, src)      memcmp(dest, src, sizeof(va_list))
883 #endif
884
885 /* Provide strlcpy/strlcat interfaces. */
886 #ifndef HAVE_STRLCPY
887 #define strlcpy krb5int_strlcpy
888 #define strlcat krb5int_strlcat
889 extern size_t krb5int_strlcpy(char *dst, const char *src, size_t siz);
890 extern size_t krb5int_strlcat(char *dst, const char *src, size_t siz);
891 #endif
892
893 /* Provide [v]asprintf interfaces.  */
894 #ifndef HAVE_VSNPRINTF
895 #ifdef _WIN32
896 static inline int
897 vsnprintf(char *str, size_t size, const char *format, va_list args)
898 {
899     va_list args_copy;
900     int length;
901
902     va_copy(args_copy, args);
903     length = _vscprintf(format, args_copy);
904     va_end(args_copy);
905     if (size)
906         _vsnprintf(str, size, format, args);
907     return length;
908 }
909 static inline int
910 snprintf(char *str, size_t size, const char *format, ...)
911 {
912     va_list args;
913     int n;
914
915     va_start(args, format);
916     n = vsnprintf(str, size, format, args);
917     va_end(args);
918     return n;
919 }
920 #else /* not win32 */
921 #error We need an implementation of vsnprintf.
922 #endif /* win32? */
923 #endif /* no vsnprintf */
924
925 #ifndef HAVE_VASPRINTF
926
927 extern int krb5int_vasprintf(char **, const char *, va_list)
928 #if !defined(__cplusplus) && (__GNUC__ > 2)
929     __attribute__((__format__(__printf__, 2, 0)))
930 #endif
931     ;
932 extern int krb5int_asprintf(char **, const char *, ...)
933 #if !defined(__cplusplus) && (__GNUC__ > 2)
934     __attribute__((__format__(__printf__, 2, 3)))
935 #endif
936     ;
937
938 #define vasprintf krb5int_vasprintf
939 /* Assume HAVE_ASPRINTF iff HAVE_VASPRINTF.  */
940 #define asprintf krb5int_asprintf
941
942 #elif defined(NEED_VASPRINTF_PROTO)
943
944 extern int vasprintf(char **, const char *, va_list)
945 #if !defined(__cplusplus) && (__GNUC__ > 2)
946     __attribute__((__format__(__printf__, 2, 0)))
947 #endif
948     ;
949 extern int asprintf(char **, const char *, ...)
950 #if !defined(__cplusplus) && (__GNUC__ > 2)
951     __attribute__((__format__(__printf__, 2, 3)))
952 #endif
953     ;
954
955 #endif /* have vasprintf and prototype? */
956
957 /* Return true if the snprintf return value RESULT reflects a buffer
958    overflow for the buffer size SIZE.
959
960    We cast the result to unsigned int for two reasons.  First, old
961    implementations of snprintf (such as the one in Solaris 9 and
962    prior) return -1 on a buffer overflow.  Casting the result to -1
963    will convert that value to UINT_MAX, which should compare larger
964    than any reasonable buffer size.  Second, comparing signed and
965    unsigned integers will generate warnings with some compilers, and
966    can have unpredictable results, particularly when the relative
967    widths of the types is not known (size_t may be the same width as
968    int or larger).
969 */
970 #define SNPRINTF_OVERFLOW(result, size) \
971     ((unsigned int)(result) >= (size_t)(size))
972
973 #ifndef HAVE_MKSTEMP
974 extern int krb5int_mkstemp(char *);
975 #define mkstemp krb5int_mkstemp
976 #endif
977
978 /* Fudge for future adoption of gettext or the like.  */
979 #ifndef _
980 #define _(X) (X)
981 #endif
982
983 #endif /* K5_PLATFORM_H */