1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.37.2.3 2003/11/20 11:39:24 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/Attic/miscutil.c,v $
6 * Purpose : zalloc, hash_string, safe_strerror, strcmpic,
7 * strncmpic, chomp, and MinGW32 strdup
9 * These are each too small to deserve their own file
10 * but don't really fit in any other file.
12 * Copyright : Written by and Copyright (C) 2001 the SourceForge
13 * Privoxy team. http://www.privoxy.org/
15 * Based on the Internet Junkbuster originally written
16 * by and Copyright (C) 1997 Anonymous Coders and
17 * Junkbusters Corporation. http://www.junkbusters.com
19 * This program is free software; you can redistribute it
20 * and/or modify it under the terms of the GNU General
21 * Public License as published by the Free Software
22 * Foundation; either version 2 of the License, or (at
23 * your option) any later version.
25 * This program is distributed in the hope that it will
26 * be useful, but WITHOUT ANY WARRANTY; without even the
27 * implied warranty of MERCHANTABILITY or FITNESS FOR A
28 * PARTICULAR PURPOSE. See the GNU General Public
29 * License for more details.
31 * The GNU General Public License should be included with
32 * this file. If not, you can view it at
33 * http://www.gnu.org/copyleft/gpl.html
34 * or write to the Free Software Foundation, Inc., 59
35 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
38 * $Log: miscutil.c,v $
39 * Revision 1.37.2.3 2003/11/20 11:39:24 oes
40 * Bugfix: The "?" wildcard for domain names had never been implemented. Ooops\!
42 * Revision 1.37.2.2 2002/11/12 14:28:18 oes
43 * Proper backtracking in simplematch; fixes bug #632888
45 * Revision 1.37.2.1 2002/09/25 12:58:51 oes
46 * Made strcmpic and strncmpic safe against NULL arguments
47 * (which are now treated as empty strings).
49 * Revision 1.37 2002/04/26 18:29:43 jongfoster
50 * Fixing this Visual C++ warning:
51 * miscutil.c(710) : warning C4090: '=' : different 'const' qualifiers
53 * Revision 1.36 2002/04/26 12:55:38 oes
54 * New function string_toupper
56 * Revision 1.35 2002/03/26 22:29:55 swa
57 * we have a new homepage!
59 * Revision 1.34 2002/03/24 13:25:43 swa
60 * name change related issues
62 * Revision 1.33 2002/03/07 03:46:53 oes
63 * Fixed compiler warnings etc
65 * Revision 1.32 2002/03/06 23:02:57 jongfoster
68 * Revision 1.31 2002/03/05 04:52:42 oes
69 * Deleted non-errlog debugging code
71 * Revision 1.30 2002/03/04 18:27:42 oes
72 * - Deleted deletePidFile
73 * - Made write_pid_file use the --pidfile option value
74 * (or no PID file, if the option was absent)
75 * - Played styleguide police
77 * Revision 1.29 2002/03/04 02:08:02 david__schmidt
78 * Enable web editing of actions file on OS/2 (it had been broken all this time!)
80 * Revision 1.28 2002/03/03 09:18:03 joergs
81 * Made jumbjuster work on AmigaOS again.
83 * Revision 1.27 2002/01/21 00:52:32 jongfoster
84 * Adding string_join()
86 * Revision 1.26 2001/12/30 14:07:32 steudten
87 * - Add signal handling (unix)
88 * - Add SIGHUP handler (unix)
89 * - Add creation of pidfile (unix)
90 * - Add action 'top' in rc file (RH)
91 * - Add entry 'SIGNALS' to manpage
92 * - Add exit message to logfile (unix)
94 * Revision 1.25 2001/11/13 00:16:38 jongfoster
95 * Replacing references to malloc.h with the standard stdlib.h
96 * (See ANSI or K&R 2nd Ed)
98 * Revision 1.24 2001/11/05 21:41:43 steudten
99 * Add changes to be a real daemon just for unix os.
100 * (change cwd to /, detach from controlling tty, set
101 * process group and session leader to the own process.
103 * Add some fatal-error log message for failed malloc().
104 * Add '-d' if compiled with 'configure --with-debug' to
105 * enable debug output.
107 * Revision 1.23 2001/10/29 03:48:10 david__schmidt
108 * OS/2 native needed a snprintf() routine. Added one to miscutil, brackedted
109 * by and __OS2__ ifdef.
111 * Revision 1.22 2001/10/26 17:39:38 oes
112 * Moved ijb_isspace and ijb_tolower to project.h
114 * Revision 1.21 2001/10/23 21:27:50 jongfoster
115 * Standardising error codes in string_append
116 * make_path() no longer adds '\\' if the dir already ends in '\\' (this
117 * is just copying a UNIX-specific fix to the Windows-specific part)
119 * Revision 1.20 2001/10/22 15:33:56 david__schmidt
120 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
121 * filters.c. Added a FIXME in front of the offending code. I'll gladly
122 * put in a better/more robust fix for all parties if one is presented...
123 * It seems that just returning 200 instead of 404 would pretty much fix
124 * it for everyone, but I don't know all the history of the problem.
126 * Revision 1.19 2001/10/14 22:02:57 jongfoster
127 * New function string_append() which is like strsav(), but running
128 * out of memory isn't automatically FATAL.
130 * Revision 1.18 2001/09/20 13:33:43 steudten
132 * change long to int as return value in hash_string(). Remember the wraparound
133 * for int = long = sizeof(4) - thats maybe not what we want.
135 * Revision 1.17 2001/09/13 20:51:29 jongfoster
136 * Fixing potential problems with characters >=128 in simplematch()
137 * This was also a compiler warning.
139 * Revision 1.16 2001/09/10 10:56:59 oes
140 * Silenced compiler warnings
142 * Revision 1.15 2001/07/13 14:02:24 oes
143 * Removed vim-settings
145 * Revision 1.14 2001/06/29 21:45:41 oes
146 * Indentation, CRLF->LF, Tab-> Space
148 * Revision 1.13 2001/06/29 13:32:14 oes
149 * Removed logentry from cancelled commit
151 * Revision 1.12 2001/06/09 10:55:28 jongfoster
152 * Changing BUFSIZ ==> BUFFER_SIZE
154 * Revision 1.11 2001/06/07 23:09:19 jongfoster
155 * Cosmetic indentation changes.
157 * Revision 1.10 2001/06/07 14:51:38 joergs
158 * make_path() no longer adds '/' if the dir already ends in '/'.
160 * Revision 1.9 2001/06/07 14:43:17 swa
161 * slight mistake in make_path, unix path style is /.
163 * Revision 1.8 2001/06/05 22:32:01 jongfoster
164 * New function make_path() to splice directory and file names together.
166 * Revision 1.7 2001/06/03 19:12:30 oes
167 * introduced bindup()
169 * Revision 1.6 2001/06/01 18:14:49 jongfoster
170 * Changing the calls to strerr() to check HAVE_STRERR (which is defined
171 * in config.h if appropriate) rather than the NO_STRERR macro.
173 * Revision 1.5 2001/06/01 10:31:51 oes
174 * Added character class matching to trivimatch; renamed to simplematch
176 * Revision 1.4 2001/05/31 17:32:31 oes
178 * - Enhanced domain part globbing with infix and prefix asterisk
179 * matching and optional unanchored operation
181 * Revision 1.3 2001/05/29 23:10:09 oes
184 * - Introduced chomp()
185 * - Moved strsav() from showargs to miscutil
187 * Revision 1.2 2001/05/29 09:50:24 jongfoster
188 * Unified blocklist/imagelist/permissionslist.
189 * File format is still under discussion, but the internal changes
192 * Also modified interceptor behaviour:
193 * - We now intercept all URLs beginning with one of the following
194 * prefixes (and *only* these prefixes):
196 * * http://ijbswa.sf.net/config/
197 * * http://ijbswa.sourceforge.net/config/
198 * - New interceptors "home page" - go to http://i.j.b/ to see it.
199 * - Internal changes so that intercepted and fast redirect pages
200 * are not replaced with an image.
201 * - Interceptors now have the option to send a binary page direct
202 * to the client. (i.e. ijb-send-banner uses this)
203 * - Implemented show-url-info interceptor. (Which is why I needed
204 * the above interceptors changes - a typical URL is
205 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
206 * The previous mechanism would not have intercepted that, and
207 * if it had been intercepted then it then it would have replaced
210 * Revision 1.1.1.1 2001/05/15 13:59:00 oes
211 * Initial import of version 2.9.3 source tree
214 *********************************************************************/
220 #include <sys/types.h>
222 #if !defined(_WIN32) && !defined(__OS2__)
224 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
230 #include "miscutil.h"
234 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
236 /*********************************************************************
240 * Description : Malloc some memory and set it to '\0'.
241 * The way calloc() ought to be -acjc
244 * 1 : size = Size of memory chunk to return.
246 * Returns : Pointer to newly malloc'd memory chunk.
248 *********************************************************************/
249 void *zalloc(size_t size)
253 if ((ret = (void *)malloc(size)) != NULL)
255 memset(ret, 0, size);
264 /*********************************************************************
266 * Function : write_pid_file
268 * Description : Writes a pid file with the pid of the main process
274 *********************************************************************/
275 void write_pid_file(void)
280 * If no --pidfile option was given,
281 * we can live without one.
283 if (pidfile == NULL) return;
285 if ((fp = fopen(pidfile, "w")) == NULL)
287 log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
291 fprintf(fp, "%u\n", (unsigned int) getpid());
297 #endif /* def unix */
300 /*********************************************************************
302 * Function : hash_string
304 * Description : Take a string and compute a (hopefuly) unique numeric
305 * integer value. This has several uses, but being able
306 * to "switch" a string the one of my favorites.
309 * 1 : s : string to be hashed.
311 * Returns : an unsigned long variable with the hashed value.
313 *********************************************************************/
314 unsigned int hash_string( const char* s )
329 /*********************************************************************
333 * Description : For some reason (which is beyond me), gcc and WIN32
334 * don't like strdup. When a "free" is executed on a
335 * strdup'd ptr, it can at times freez up! So I just
336 * replaced it and problem was solved.
339 * 1 : s = string to duplicate
341 * Returns : Pointer to newly malloc'ed copy of the string.
343 *********************************************************************/
344 char *strdup( const char *s )
346 char * result = (char *)malloc( strlen(s)+1 );
356 #endif /* def __MINGW32__ */
360 /*********************************************************************
362 * Function : safe_strerror
364 * Description : Variant of the library routine strerror() which will
365 * work on systems without the library routine, and
366 * which should never return NULL.
369 * 1 : err = the `errno' of the last operation.
371 * Returns : An "English" string of the last `errno'. Allocated
372 * with strdup(), so caller frees. May be NULL if the
373 * system is out of memory.
375 *********************************************************************/
376 char *safe_strerror(int err)
379 char buf[BUFFER_SIZE];
384 #endif /* HAVE_STRERROR */
388 sprintf(buf, "(errno = %d)", err);
397 /*********************************************************************
399 * Function : strcmpic
401 * Description : Case insensitive string comparison
404 * 1 : s1 = string 1 to compare
405 * 2 : s2 = string 2 to compare
407 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
409 *********************************************************************/
410 int strcmpic(const char *s1, const char *s2)
417 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
423 return(ijb_tolower(*s1) - ijb_tolower(*s2));
428 /*********************************************************************
430 * Function : strncmpic
432 * Description : Case insensitive string comparison (upto n characters)
435 * 1 : s1 = string 1 to compare
436 * 2 : s2 = string 2 to compare
437 * 3 : n = maximum characters to compare
439 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
441 *********************************************************************/
442 int strncmpic(const char *s1, const char *s2, size_t n)
444 if (n <= 0) return(0);
450 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
459 return(ijb_tolower(*s1) - ijb_tolower(*s2));
464 /*********************************************************************
468 * Description : In-situ-eliminate all leading and trailing whitespace
472 * 1 : s : string to be chomped.
474 * Returns : chomped string
476 *********************************************************************/
477 char *chomp(char *string)
482 * strip trailing whitespace
484 p = string + strlen(string);
485 while (p > string && ijb_isspace(*(p-1)))
492 * find end of leading whitespace
495 while (*q && ijb_isspace(*q))
501 * if there was any, move the rest forwards
516 /*********************************************************************
520 * Description : Reallocate "old" and append text to it. This makes
521 * it easier to append to malloc'd strings.
522 * Running out of memory is a FATAL error.
525 * 1 : old = Old text that is to be extended. Will be
526 * free()d by this routine. May be NULL.
527 * 2 : text_to_append = Text to be appended to old.
530 * Returns : Pointer to newly malloc'ed appended string.
531 * If there is no text to append, return old. Caller
534 *********************************************************************/
535 char *strsav(char *old, const char *text_to_append)
537 size_t old_len, new_len = 0;
540 if ((text_to_append == NULL) || (*text_to_append == '\0'))
547 if ((p = strdup(text_to_append)) == NULL)
549 log_error(LOG_LEVEL_FATAL, "strdup() failed!");
550 /* Never get here - LOG_LEVEL_FATAL causes program exit */
555 old_len = strlen(old);
556 new_len = old_len + strlen(text_to_append) + 1;
558 if ((p = realloc(old, new_len)) == NULL)
560 log_error(LOG_LEVEL_FATAL, "realloc(%d) bytes failed!", new_len);
561 /* Never get here - LOG_LEVEL_FATAL causes program exit */
564 strcpy(p + old_len, text_to_append);
569 /*********************************************************************
571 * Function : string_append
573 * Description : Reallocate target_string and append text to it.
574 * This makes it easier to append to malloc'd strings.
575 * This is similar to the (removed) strsav(), but
576 * running out of memory isn't catastrophic.
580 * The following style provides sufficient error
581 * checking for this routine, with minimal clutter
582 * in the source code. It is recommended if you
583 * have many calls to this function:
585 * char * s = strdup(...); // don't check for error
586 * string_append(&s, ...); // don't check for error
587 * string_append(&s, ...); // don't check for error
588 * string_append(&s, ...); // don't check for error
589 * if (NULL == s) { ... handle error ... }
593 * char * s = strdup(...); // don't check for error
594 * string_append(&s, ...); // don't check for error
595 * string_append(&s, ...); // don't check for error
596 * if (string_append(&s, ...)) {... handle error ...}
599 * 1 : target_string = Pointer to old text that is to be
600 * extended. *target_string will be free()d by this
601 * routine. target_string must be non-NULL.
602 * If *target_string is NULL, this routine will
603 * do nothing and return with an error - this allows
604 * you to make many calls to this routine and only
605 * check for errors after the last one.
606 * 2 : text_to_append = Text to be appended to old.
609 * Returns : JB_ERR_OK on success, and sets *target_string
610 * to newly malloc'ed appended string. Caller
611 * must free(*target_string).
612 * JB_ERR_MEMORY on out-of-memory. (And free()s
613 * *target_string and sets it to NULL).
614 * JB_ERR_MEMORY if *target_string is NULL.
616 *********************************************************************/
617 jb_err string_append(char **target_string, const char *text_to_append)
622 assert(target_string);
623 assert(text_to_append);
625 if (*target_string == NULL)
627 return JB_ERR_MEMORY;
630 if (*text_to_append == '\0')
635 old_len = strlen(*target_string);
637 if (NULL == (new_string = realloc(*target_string,
638 strlen(text_to_append) + old_len + 1)))
640 free(*target_string);
642 *target_string = NULL;
643 return JB_ERR_MEMORY;
646 strcpy(new_string + old_len, text_to_append);
648 *target_string = new_string;
653 /*********************************************************************
655 * Function : string_join
657 * Description : Join two strings together. Frees BOTH the original
658 * strings. If either or both input strings are NULL,
659 * fails as if it had run out of memory.
661 * For comparison, string_append requires that the
662 * second string is non-NULL, and doesn't free it.
664 * Rationale: Too often, we want to do
665 * string_append(s, html_encode(s2)). That assert()s
666 * if s2 is NULL or if html_encode() runs out of memory.
667 * It also leaks memory. Proper checking is cumbersome.
668 * The solution: string_join(s, html_encode(s2)) is safe,
669 * and will free the memory allocated by html_encode().
672 * 1 : target_string = Pointer to old text that is to be
673 * extended. *target_string will be free()d by this
674 * routine. target_string must be non-NULL.
675 * 2 : text_to_append = Text to be appended to old.
677 * Returns : JB_ERR_OK on success, and sets *target_string
678 * to newly malloc'ed appended string. Caller
679 * must free(*target_string).
680 * JB_ERR_MEMORY on out-of-memory, or if
681 * *target_string or text_to_append is NULL. (In
682 * this case, frees *target_string and text_to_append,
683 * sets *target_string to NULL).
685 *********************************************************************/
686 jb_err string_join(char **target_string, char *text_to_append)
690 assert(target_string);
692 if (text_to_append == NULL)
694 freez(*target_string);
695 return JB_ERR_MEMORY;
698 err = string_append(target_string, text_to_append);
700 free(text_to_append);
706 /*********************************************************************
708 * Function : string_toupper
710 * Description : Produce a copy of string with all convertible
711 * characters converted to uppercase.
714 * 1 : string = string to convert
716 * Returns : Uppercase copy of string if possible,
717 * NULL on out-of-memory or if string was NULL.
719 *********************************************************************/
720 char *string_toupper(const char *string)
725 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
735 *p++ = toupper(*q++);
743 /*********************************************************************
745 * Function : simplematch
747 * Description : String matching, with a (greedy) '*' wildcard that
748 * stands for zero or more arbitrary characters and
749 * character classes in [], which take both enumerations
753 * 1 : pattern = pattern for matching
754 * 2 : text = text to be matched
756 * Returns : 0 if match, else nonzero
758 *********************************************************************/
759 int simplematch(char *pattern, char *text)
761 unsigned char *pat = (unsigned char *) pattern;
762 unsigned char *txt = (unsigned char *) text;
763 unsigned char *fallback = pat;
766 unsigned char lastchar = 'a';
768 unsigned char charmap[32];
773 /* EOF pattern but !EOF text? */
786 /* '*' in the pattern? */
790 /* The pattern ends afterwards? Speed up the return. */
796 /* Else, set wildcard mode and remember position after '*' */
801 /* Character range specification? */
804 memset(charmap, '\0', sizeof(charmap));
806 while (*++pat != ']')
812 else if (*pat == '-')
814 if ((*++pat == ']') || *pat == '\0')
818 for(i = lastchar; i <= *pat; i++)
820 charmap[i / 8] |= (1 << (i % 8));
825 charmap[*pat / 8] |= (1 << (*pat % 8));
829 } /* -END- if Character range specification */
833 * Char match, or char range match?
837 || ((*pat == ']') && (charmap[*txt / 8] & (1 << (*txt % 8)))) )
847 * No match && no wildcard: No luck
851 else if (pat != fallback)
854 * Wildcard mode && nonmatch beyond fallback: Rewind pattern
861 /* Cut off extra '*'s */
862 if(*pat == '*') pat++;
864 /* If this is the pattern's end, fine! */
870 /*********************************************************************
874 * Description : Duplicate the first n characters of a string that may
875 * contain '\0' characters.
878 * 1 : string = string to be duplicated
879 * 2 : len = number of bytes to duplicate
881 * Returns : pointer to copy, or NULL if failiure
883 *********************************************************************/
884 char *bindup(const char *string, size_t len)
888 if (NULL == (duplicate = (char *)malloc(len)))
894 memcpy(duplicate, string, len);
902 /*********************************************************************
904 * Function : make_path
906 * Description : Takes a directory name and a file name, returns
907 * the complete path. Handles windows/unix differences.
908 * If the file name is already an absolute path, or if
909 * the directory name is NULL or empty, it returns
913 * 1 : dir: Name of directory or NULL for none.
914 * 2 : file: Name of file. Should not be NULL or empty.
916 * Returns : "dir/file" (Or on windows, "dir\file").
917 * It allocates the string on the heap. Caller frees.
918 * Returns NULL in error (i.e. NULL file or out of
921 *********************************************************************/
922 char * make_path(const char * dir, const char * file)
933 strncpy(path,dir+2,512);
937 strncpy(path,dir+1,512);
942 strncpy(path,dir,512);
948 if(AddPart(path,file,512))
954 #else /* ndef AMIGA */
956 if ((file == NULL) || (*file == '\0'))
958 return NULL; /* Error */
961 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
962 #if defined(_WIN32) || defined(__OS2__)
963 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
964 #else /* ifndef _WIN32 || __OS2__ */
965 || (*file == '/') /* Absolute path (U*ix) */
966 #endif /* ifndef _WIN32 || __OS2__ */
976 if ( *dir != '/' && basedir && *basedir )
978 path = malloc( strlen( basedir ) + strlen(dir) + strlen(file) + 3);
979 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
980 strcpy(path, basedir);
986 path = malloc(strlen(dir) + strlen(file) + 2);
987 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
992 path = malloc(strlen(dir) + strlen(file) + 2);
993 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
996 #endif /* defined unix */
998 #if defined(_WIN32) || defined(__OS2__)
999 if(path[strlen(path)-1] != '\\')
1003 #else /* ifndef _WIN32 || __OS2__ */
1004 if(path[strlen(path)-1] != '/')
1008 #endif /* ifndef _WIN32 || __OS2__ */
1013 #endif /* ndef AMIGA */
1018 * What follows is a portable snprintf routine, written by Mark Martinec.
1019 * See: http://www.ijs.si/software/snprintf/
1020 * Anyone who needs it can add a define for themselves... so far, only
1021 * OS/2 (native) lacks snprintf.
1024 - a portable implementation of snprintf,
1025 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
1027 snprintf is a routine to convert numeric and string arguments to
1028 formatted strings. It is similar to sprintf(3) provided in a system's
1029 C library, yet it requires an additional argument - the buffer size -
1030 and it guarantees never to store anything beyond the given buffer,
1031 regardless of the format or arguments to be formatted. Some newer
1032 operating systems do provide snprintf in their C library, but many do
1033 not or do provide an inadequate (slow or idiosyncratic) version, which
1034 calls for a portable implementation of this routine.
1038 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
1039 Copyright © 1999, Mark Martinec
1045 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
1046 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
1048 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
1049 # if defined(NEED_SNPRINTF_ONLY)
1050 # undef NEED_SNPRINTF_ONLY
1052 # if !defined(PREFER_PORTABLE_SNPRINTF)
1053 # define PREFER_PORTABLE_SNPRINTF
1057 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1058 #define SOLARIS_COMPATIBLE
1061 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1062 #define HPUX_COMPATIBLE
1065 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1066 #define DIGITAL_UNIX_COMPATIBLE
1069 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1070 #define PERL_COMPATIBLE
1073 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1074 #define LINUX_COMPATIBLE
1077 #include <sys/types.h>
1088 #define isdigit(c) ((c) >= '0' && (c) <= '9')
1090 /* For copying strings longer or equal to 'breakeven_point'
1091 * it is more efficient to call memcpy() than to do it inline.
1092 * The value depends mostly on the processor architecture,
1093 * but also on the compiler and its optimization capabilities.
1094 * The value is not critical, some small value greater than zero
1095 * will be just fine if you don't care to squeeze every drop
1096 * of performance out of the code.
1098 * Small values favor memcpy, large values favor inline code.
1100 #if defined(__alpha__) || defined(__alpha)
1101 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
1103 #if defined(__i386__) || defined(__i386)
1104 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
1107 # define breakeven_point 10 /* HP-PA - gcc */
1109 #if defined(__sparc__) || defined(__sparc)
1110 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
1113 /* some other values of possible interest: */
1114 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
1115 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
1117 #ifndef breakeven_point
1118 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
1121 #define fast_memcpy(d,s,n) \
1122 { register size_t nn = (size_t)(n); \
1123 if (nn >= breakeven_point) memcpy((d), (s), nn); \
1124 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1125 register char *dd; register const char *ss; \
1126 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
1128 #define fast_memset(d,c,n) \
1129 { register size_t nn = (size_t)(n); \
1130 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
1131 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1132 register char *dd; register const int cc=(int)(c); \
1133 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1137 #if defined(NEED_ASPRINTF)
1138 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
1140 #if defined(NEED_VASPRINTF)
1141 int vasprintf (char **ptr, const char *fmt, va_list ap);
1143 #if defined(NEED_ASNPRINTF)
1144 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1146 #if defined(NEED_VASNPRINTF)
1147 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1150 #if defined(HAVE_SNPRINTF)
1151 /* declare our portable snprintf routine under name portable_snprintf */
1152 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1154 /* declare our portable routines under names snprintf and vsnprintf */
1155 #define portable_snprintf snprintf
1156 #if !defined(NEED_SNPRINTF_ONLY)
1157 #define portable_vsnprintf vsnprintf
1161 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1162 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1163 #if !defined(NEED_SNPRINTF_ONLY)
1164 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1170 static char credits[] = "\n\
1171 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1172 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1173 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1175 #if defined(NEED_ASPRINTF)
1176 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1182 va_start(ap, fmt); /* measure the required size */
1183 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1185 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1186 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1187 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1191 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1193 assert(str_l2 == str_l);
1199 #if defined(NEED_VASPRINTF)
1200 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1206 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1207 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1210 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1211 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1212 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1214 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1215 assert(str_l2 == str_l);
1221 #if defined(NEED_ASNPRINTF)
1222 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1227 va_start(ap, fmt); /* measure the required size */
1228 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1230 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1231 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1232 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1233 if (str_m == 0) { /* not interested in resulting string, just return size */
1235 *ptr = (char *) malloc(str_m);
1236 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1240 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1242 assert(str_l2 == str_l);
1249 #if defined(NEED_VASNPRINTF)
1250 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1255 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1256 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1259 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1260 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1261 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1262 if (str_m == 0) { /* not interested in resulting string, just return size */
1264 *ptr = (char *) malloc(str_m);
1265 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1267 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1268 assert(str_l2 == str_l);
1276 * If the system does have snprintf and the portable routine is not
1277 * specifically required, this module produces no code for snprintf/vsnprintf.
1279 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1281 #if !defined(NEED_SNPRINTF_ONLY)
1282 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1287 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1293 #if defined(NEED_SNPRINTF_ONLY)
1294 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1296 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1299 #if defined(NEED_SNPRINTF_ONLY)
1303 const char *p = fmt;
1305 /* In contrast with POSIX, the ISO C99 now says
1306 * that str can be NULL and str_m can be 0.
1307 * This is more useful than the old: if (str_m < 1) return -1; */
1309 #if defined(NEED_SNPRINTF_ONLY)
1315 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1316 /* but the following code achieves better performance for cases
1317 * where format string is long and contains few conversions */
1318 const char *q = strchr(p+1,'%');
1319 size_t n = !q ? strlen(p) : (q-p);
1320 if (str_l < str_m) {
1321 size_t avail = str_m-str_l;
1322 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1326 const char *starting_p;
1327 size_t min_field_width = 0, precision = 0;
1328 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1329 int alternate_form = 0, force_sign = 0;
1330 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1331 the ' ' flag should be ignored. */
1332 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1333 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1335 const char *str_arg; /* string address in case of string argument */
1336 size_t str_arg_l; /* natural field width of arg without padding
1338 unsigned char uchar_arg;
1339 /* unsigned char argument value - only defined for c conversion.
1340 N.B. standard explicitly states the char argument for
1341 the c conversion is unsigned */
1343 size_t number_of_zeros_to_pad = 0;
1344 /* number of zeros to be inserted for numeric conversions
1345 as required by the precision or minimal field width */
1347 size_t zero_padding_insertion_ind = 0;
1348 /* index into tmp where zero padding is to be inserted */
1350 char fmt_spec = '\0';
1351 /* current conversion specifier character */
1353 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1355 starting_p = p; p++; /* skip '%' */
1357 while (*p == '0' || *p == '-' || *p == '+' ||
1358 *p == ' ' || *p == '#' || *p == '\'') {
1360 case '0': zero_padding = 1; break;
1361 case '-': justify_left = 1; break;
1362 case '+': force_sign = 1; space_for_positive = 0; break;
1363 case ' ': force_sign = 1;
1364 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1365 #ifdef PERL_COMPATIBLE
1366 /* ... but in Perl the last of ' ' and '+' applies */
1367 space_for_positive = 1;
1370 case '#': alternate_form = 1; break;
1375 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1377 /* parse field width */
1380 p++; j = va_arg(ap, int);
1381 if (j >= 0) min_field_width = j;
1382 else { min_field_width = -j; justify_left = 1; }
1383 } else if (isdigit((int)(*p))) {
1384 /* size_t could be wider than unsigned int;
1385 make sure we treat argument like common implementations do */
1386 unsigned int uj = *p++ - '0';
1387 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1388 min_field_width = uj;
1390 /* parse precision */
1392 p++; precision_specified = 1;
1394 int j = va_arg(ap, int);
1396 if (j >= 0) precision = j;
1398 precision_specified = 0; precision = 0;
1400 * Solaris 2.6 man page claims that in this case the precision
1401 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1402 * claim that this case should be treated as unspecified precision,
1403 * which is what we do here.
1406 } else if (isdigit((int)(*p))) {
1407 /* size_t could be wider than unsigned int;
1408 make sure we treat argument like common implementations do */
1409 unsigned int uj = *p++ - '0';
1410 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1414 /* parse 'h', 'l' and 'll' length modifiers */
1415 if (*p == 'h' || *p == 'l') {
1416 length_modifier = *p; p++;
1417 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1418 #ifdef SNPRINTF_LONGLONG_SUPPORT
1419 length_modifier = '2'; /* double l encoded as '2' */
1421 length_modifier = 'l'; /* treat it as a single 'l' */
1427 /* common synonyms: */
1429 case 'i': fmt_spec = 'd'; break;
1430 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1431 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1432 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1435 /* get parameter value, do initial processing */
1437 case '%': /* % behaves similar to 's' regarding flags and field widths */
1438 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1440 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1441 /* the result of zero padding flag with non-numeric conversion specifier*/
1442 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1443 /* Digital Unix and Linux does not. */
1444 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1445 zero_padding = 0; /* turn zero padding off for string conversions */
1452 int j = va_arg(ap, int);
1453 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1454 str_arg = (const char *) &uchar_arg;
1458 str_arg = va_arg(ap, const char *);
1459 if (!str_arg) str_arg_l = 0;
1460 /* make sure not to address string beyond the specified precision !!! */
1461 else if (!precision_specified) str_arg_l = strlen(str_arg);
1462 /* truncate string if necessary as requested by precision */
1463 else if (precision == 0) str_arg_l = 0;
1465 /* memchr on HP does not like n > 2^31 !!! */
1466 const char *q = memchr(str_arg, '\0',
1467 precision <= 0x7fffffff ? precision : 0x7fffffff);
1468 str_arg_l = !q ? precision : (q-str_arg);
1474 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1475 /* NOTE: the u, o, x, X and p conversion specifiers imply
1476 the value is unsigned; d implies a signed value */
1479 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1480 +1 if greater than zero (or nonzero for unsigned arguments),
1481 -1 if negative (unsigned argument is never negative) */
1483 int int_arg = 0; unsigned int uint_arg = 0;
1484 /* only defined for length modifier h, or for no length modifiers */
1486 long int long_arg = 0; unsigned long int ulong_arg = 0;
1487 /* only defined for length modifier l */
1489 void *ptr_arg = NULL;
1490 /* pointer argument value -only defined for p conversion */
1492 #ifdef SNPRINTF_LONGLONG_SUPPORT
1493 long long int long_long_arg = 0;
1494 unsigned long long int ulong_long_arg = 0;
1495 /* only defined for length modifier ll */
1497 if (fmt_spec == 'p') {
1498 /* HPUX 10: An l, h, ll or L before any other conversion character
1499 * (other than d, i, u, o, x, or X) is ignored.
1501 * not specified, but seems to behave as HPUX does.
1502 * Solaris: If an h, l, or L appears before any other conversion
1503 * specifier (other than d, i, u, o, x, or X), the behavior
1504 * is undefined. (Actually %hp converts only 16-bits of address
1505 * and %llp treats address as 64-bit data which is incompatible
1506 * with (void *) argument on a 32-bit system).
1508 #ifdef SOLARIS_COMPATIBLE
1509 # ifdef SOLARIS_BUG_COMPATIBLE
1510 /* keep length modifiers even if it represents 'll' */
1512 if (length_modifier == '2') length_modifier = '\0';
1515 length_modifier = '\0';
1517 ptr_arg = va_arg(ap, void *);
1518 if (ptr_arg != NULL) arg_sign = 1;
1519 } else if (fmt_spec == 'd') { /* signed */
1520 switch (length_modifier) {
1523 /* It is non-portable to specify a second argument of char or short
1524 * to va_arg, because arguments seen by the called function
1525 * are not char or short. C converts char and short arguments
1526 * to int before passing them to a function.
1528 int_arg = va_arg(ap, int);
1529 if (int_arg > 0) arg_sign = 1;
1530 else if (int_arg < 0) arg_sign = -1;
1533 long_arg = va_arg(ap, long int);
1534 if (long_arg > 0) arg_sign = 1;
1535 else if (long_arg < 0) arg_sign = -1;
1537 #ifdef SNPRINTF_LONGLONG_SUPPORT
1539 long_long_arg = va_arg(ap, long long int);
1540 if (long_long_arg > 0) arg_sign = 1;
1541 else if (long_long_arg < 0) arg_sign = -1;
1545 } else { /* unsigned */
1546 switch (length_modifier) {
1549 uint_arg = va_arg(ap, unsigned int);
1550 if (uint_arg) arg_sign = 1;
1553 ulong_arg = va_arg(ap, unsigned long int);
1554 if (ulong_arg) arg_sign = 1;
1556 #ifdef SNPRINTF_LONGLONG_SUPPORT
1558 ulong_long_arg = va_arg(ap, unsigned long long int);
1559 if (ulong_long_arg) arg_sign = 1;
1564 str_arg = tmp; str_arg_l = 0;
1566 * For d, i, u, o, x, and X conversions, if precision is specified,
1567 * the '0' flag should be ignored. This is so with Solaris 2.6,
1568 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1570 #ifndef PERL_COMPATIBLE
1571 if (precision_specified) zero_padding = 0;
1573 if (fmt_spec == 'd') {
1574 if (force_sign && arg_sign >= 0)
1575 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1576 /* leave negative numbers for sprintf to handle,
1577 to avoid handling tricky cases like (short int)(-32768) */
1578 #ifdef LINUX_COMPATIBLE
1579 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1580 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1582 } else if (alternate_form) {
1583 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1584 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1585 /* alternate form should have no effect for p conversion, but ... */
1586 #ifdef HPUX_COMPATIBLE
1587 else if (fmt_spec == 'p'
1588 /* HPUX 10: for an alternate form of p conversion,
1589 * a nonzero result is prefixed by 0x. */
1590 #ifndef HPUX_BUG_COMPATIBLE
1591 /* Actually it uses 0x prefix even for a zero value. */
1594 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1597 zero_padding_insertion_ind = str_arg_l;
1598 if (!precision_specified) precision = 1; /* default precision is 1 */
1599 if (precision == 0 && arg_sign == 0
1600 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1602 /* HPUX 10 man page claims: With conversion character p the result of
1603 * converting a zero value with a precision of zero is a null string.
1604 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1607 /* converted to null string */
1608 /* When zero value is formatted with an explicit precision 0,
1609 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1611 char f[5]; int f_l = 0;
1612 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1613 if (!length_modifier) { }
1614 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1615 else f[f_l++] = length_modifier;
1616 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1617 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1618 else if (fmt_spec == 'd') { /* signed */
1619 switch (length_modifier) {
1621 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1622 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1623 #ifdef SNPRINTF_LONGLONG_SUPPORT
1624 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1627 } else { /* unsigned */
1628 switch (length_modifier) {
1630 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1631 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1632 #ifdef SNPRINTF_LONGLONG_SUPPORT
1633 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1637 /* include the optional minus sign and possible "0x"
1638 in the region before the zero padding insertion point */
1639 if (zero_padding_insertion_ind < str_arg_l &&
1640 tmp[zero_padding_insertion_ind] == '-') {
1641 zero_padding_insertion_ind++;
1643 if (zero_padding_insertion_ind+1 < str_arg_l &&
1644 tmp[zero_padding_insertion_ind] == '0' &&
1645 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1646 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1647 zero_padding_insertion_ind += 2;
1650 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1651 if (alternate_form && fmt_spec == 'o'
1652 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1655 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1657 /* unless zero is already the first character */
1658 && !(zero_padding_insertion_ind < str_arg_l
1659 && tmp[zero_padding_insertion_ind] == '0')
1661 ) { /* assure leading zero for alternate-form octal numbers */
1662 if (!precision_specified || precision < num_of_digits+1) {
1663 /* precision is increased to force the first character to be zero,
1664 except if a zero value is formatted with an explicit precision
1666 precision = num_of_digits+1; precision_specified = 1;
1669 /* zero padding to specified precision? */
1670 if (num_of_digits < precision)
1671 number_of_zeros_to_pad = precision - num_of_digits;
1673 /* zero padding to specified minimal field width? */
1674 if (!justify_left && zero_padding) {
1675 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1676 if (n > 0) number_of_zeros_to_pad += n;
1680 default: /* unrecognized conversion specifier, keep format string as-is*/
1681 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1682 #ifndef DIGITAL_UNIX_COMPATIBLE
1683 justify_left = 1; min_field_width = 0; /* reset flags */
1685 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1686 /* keep the entire format string unchanged */
1687 str_arg = starting_p; str_arg_l = p - starting_p;
1688 /* well, not exactly so for Linux, which does something inbetween,
1689 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1691 /* discard the unrecognized conversion, just keep *
1692 * the unrecognized conversion character */
1693 str_arg = p; str_arg_l = 0;
1695 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1696 if not at end-of-string */
1699 if (*p) p++; /* step over the just processed conversion specifier */
1700 /* insert padding to the left as requested by min_field_width;
1701 this does not include the zero padding in case of numerical conversions*/
1702 if (!justify_left) { /* left padding with blank or zero */
1703 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1705 if (str_l < str_m) {
1706 size_t avail = str_m-str_l;
1707 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1712 /* zero padding as requested by the precision or by the minimal field width
1713 * for numeric conversions required? */
1714 if (number_of_zeros_to_pad <= 0) {
1715 /* will not copy first part of numeric right now, *
1716 * force it to be copied later in its entirety */
1717 zero_padding_insertion_ind = 0;
1719 /* insert first part of numerics (sign or '0x') before zero padding */
1720 int n = zero_padding_insertion_ind;
1722 if (str_l < str_m) {
1723 size_t avail = str_m-str_l;
1724 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1728 /* insert zero padding as requested by the precision or min field width */
1729 n = number_of_zeros_to_pad;
1731 if (str_l < str_m) {
1732 size_t avail = str_m-str_l;
1733 fast_memset(str+str_l, '0', (n>avail?avail:n));
1738 /* insert formatted string
1739 * (or as-is conversion specifier for unknown conversions) */
1740 { int n = str_arg_l - zero_padding_insertion_ind;
1742 if (str_l < str_m) {
1743 size_t avail = str_m-str_l;
1744 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1750 /* insert right padding */
1751 if (justify_left) { /* right blank padding to the field width */
1752 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1754 if (str_l < str_m) {
1755 size_t avail = str_m-str_l;
1756 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1763 #if defined(NEED_SNPRINTF_ONLY)
1766 if (str_m > 0) { /* make sure the string is null-terminated
1767 even at the expense of overwriting the last character
1768 (shouldn't happen, but just in case) */
1769 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1771 /* Return the number of characters formatted (excluding trailing null
1772 * character), that is, the number of characters that would have been
1773 * written to the buffer if it were large enough.
1775 * The value of str_l should be returned, but str_l is of unsigned type
1776 * size_t, and snprintf is int, possibly leading to an undetected
1777 * integer overflow, resulting in a negative return value, which is illegal.
1778 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1779 * Should errno be set to EOVERFLOW and EOF returned in this case???
1784 #endif /* __OS2__ */