xref: /titanic_50/usr/src/cmd/sendmail/libsm/snprintf.c (revision 3db86aab554edbb4244c8d1a1c90f152eee768af)
1 /*
2  * Copyright (c) 2000-2001 Sendmail, Inc. and its suppliers.
3  *      All rights reserved.
4  * Copyright (c) 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Chris Torek.
9  *
10  * By using this file, you agree to the terms and conditions set
11  * forth in the LICENSE file which can be found at the top level of
12  * the sendmail distribution.
13  */
14 
15 #pragma ident	"%Z%%M%	%I%	%E% SMI"
16 
17 #include <sm/gen.h>
18 SM_RCSID("@(#)$Id: snprintf.c,v 1.21 2001/03/02 23:53:41 ca Exp $")
19 #include <limits.h>
20 #include <sm/varargs.h>
21 #include <sm/io.h>
22 #include "local.h"
23 
24 /*
25 **  SM_SNPRINTF -- format a string to a memory location of restricted size
26 **
27 **	Parameters:
28 **		str -- memory location to place formatted string
29 **		n -- size of buffer pointed to by str, capped to
30 **			a maximum of INT_MAX
31 **		fmt -- the formatting directives
32 **		... -- the data to satisfy the formatting
33 **
34 **	Returns:
35 **		Failure: -1
36 **		Success: number of bytes that would have been written
37 **			to str, not including the trailing '\0',
38 **			up to a maximum of INT_MAX, as if there was
39 **			no buffer size limitation.  If the result >= n
40 **			then the output was truncated.
41 **
42 **	Side Effects:
43 **		If n > 0, then between 0 and n-1 bytes of formatted output
44 **		are written into 'str', followed by a '\0'.
45 */
46 
47 int
48 #if SM_VA_STD
49 sm_snprintf(char *str, size_t n, char const *fmt, ...)
50 #else /* SM_VA_STD */
51 sm_snprintf(str, n, fmt, va_alist)
52 	char *str;
53 	size_t n;
54 	char *fmt;
55 	va_dcl
56 #endif /* SM_VA_STD */
57 {
58 	int ret;
59 	SM_VA_LOCAL_DECL
60 	SM_FILE_T fake;
61 
62 	/* While snprintf(3) specifies size_t stdio uses an int internally */
63 	if (n > INT_MAX)
64 		n = INT_MAX;
65 	SM_VA_START(ap, fmt);
66 
67 	/* XXX put this into a static? */
68 	fake.sm_magic = SmFileMagic;
69 	fake.f_file = -1;
70 	fake.f_flags = SMWR | SMSTR;
71 	fake.f_cookie = &fake;
72 	fake.f_bf.smb_base = fake.f_p = (unsigned char *)str;
73 	fake.f_bf.smb_size = fake.f_w = n ? n - 1 : 0;
74 	fake.f_timeout = SM_TIME_FOREVER;
75 	fake.f_timeoutstate = SM_TIME_BLOCK;
76 	fake.f_close = NULL;
77 	fake.f_open = NULL;
78 	fake.f_read = NULL;
79 	fake.f_write = NULL;
80 	fake.f_seek = NULL;
81 	fake.f_setinfo = fake.f_getinfo = NULL;
82 	fake.f_type = "sm_snprintf:fake";
83 	ret = sm_io_vfprintf(&fake, SM_TIME_FOREVER, fmt, ap);
84 	if (n > 0)
85 		*fake.f_p = '\0';
86 	SM_VA_END(ap);
87 	return ret;
88 }
89