1 const char miscutil_rcs[] = "$Id: miscutil.c,v 2.0 2002/06/04 14:34:21 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/src/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 2.0 2002/06/04 14:34:21 jongfoster
40 * Moving source files to src/
42 * Revision 1.37 2002/04/26 18:29:43 jongfoster
43 * Fixing this Visual C++ warning:
44 * miscutil.c(710) : warning C4090: '=' : different 'const' qualifiers
46 * Revision 1.36 2002/04/26 12:55:38 oes
47 * New function string_toupper
49 * Revision 1.35 2002/03/26 22:29:55 swa
50 * we have a new homepage!
52 * Revision 1.34 2002/03/24 13:25:43 swa
53 * name change related issues
55 * Revision 1.33 2002/03/07 03:46:53 oes
56 * Fixed compiler warnings etc
58 * Revision 1.32 2002/03/06 23:02:57 jongfoster
61 * Revision 1.31 2002/03/05 04:52:42 oes
62 * Deleted non-errlog debugging code
64 * Revision 1.30 2002/03/04 18:27:42 oes
65 * - Deleted deletePidFile
66 * - Made write_pid_file use the --pidfile option value
67 * (or no PID file, if the option was absent)
68 * - Played styleguide police
70 * Revision 1.29 2002/03/04 02:08:02 david__schmidt
71 * Enable web editing of actions file on OS/2 (it had been broken all this time!)
73 * Revision 1.28 2002/03/03 09:18:03 joergs
74 * Made jumbjuster work on AmigaOS again.
76 * Revision 1.27 2002/01/21 00:52:32 jongfoster
77 * Adding string_join()
79 * Revision 1.26 2001/12/30 14:07:32 steudten
80 * - Add signal handling (unix)
81 * - Add SIGHUP handler (unix)
82 * - Add creation of pidfile (unix)
83 * - Add action 'top' in rc file (RH)
84 * - Add entry 'SIGNALS' to manpage
85 * - Add exit message to logfile (unix)
87 * Revision 1.25 2001/11/13 00:16:38 jongfoster
88 * Replacing references to malloc.h with the standard stdlib.h
89 * (See ANSI or K&R 2nd Ed)
91 * Revision 1.24 2001/11/05 21:41:43 steudten
92 * Add changes to be a real daemon just for unix os.
93 * (change cwd to /, detach from controlling tty, set
94 * process group and session leader to the own process.
96 * Add some fatal-error log message for failed malloc().
97 * Add '-d' if compiled with 'configure --with-debug' to
98 * enable debug output.
100 * Revision 1.23 2001/10/29 03:48:10 david__schmidt
101 * OS/2 native needed a snprintf() routine. Added one to miscutil, brackedted
102 * by and __OS2__ ifdef.
104 * Revision 1.22 2001/10/26 17:39:38 oes
105 * Moved ijb_isspace and ijb_tolower to project.h
107 * Revision 1.21 2001/10/23 21:27:50 jongfoster
108 * Standardising error codes in string_append
109 * make_path() no longer adds '\\' if the dir already ends in '\\' (this
110 * is just copying a UNIX-specific fix to the Windows-specific part)
112 * Revision 1.20 2001/10/22 15:33:56 david__schmidt
113 * Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
114 * filters.c. Added a FIXME in front of the offending code. I'll gladly
115 * put in a better/more robust fix for all parties if one is presented...
116 * It seems that just returning 200 instead of 404 would pretty much fix
117 * it for everyone, but I don't know all the history of the problem.
119 * Revision 1.19 2001/10/14 22:02:57 jongfoster
120 * New function string_append() which is like strsav(), but running
121 * out of memory isn't automatically FATAL.
123 * Revision 1.18 2001/09/20 13:33:43 steudten
125 * change long to int as return value in hash_string(). Remember the wraparound
126 * for int = long = sizeof(4) - thats maybe not what we want.
128 * Revision 1.17 2001/09/13 20:51:29 jongfoster
129 * Fixing potential problems with characters >=128 in simplematch()
130 * This was also a compiler warning.
132 * Revision 1.16 2001/09/10 10:56:59 oes
133 * Silenced compiler warnings
135 * Revision 1.15 2001/07/13 14:02:24 oes
136 * Removed vim-settings
138 * Revision 1.14 2001/06/29 21:45:41 oes
139 * Indentation, CRLF->LF, Tab-> Space
141 * Revision 1.13 2001/06/29 13:32:14 oes
142 * Removed logentry from cancelled commit
144 * Revision 1.12 2001/06/09 10:55:28 jongfoster
145 * Changing BUFSIZ ==> BUFFER_SIZE
147 * Revision 1.11 2001/06/07 23:09:19 jongfoster
148 * Cosmetic indentation changes.
150 * Revision 1.10 2001/06/07 14:51:38 joergs
151 * make_path() no longer adds '/' if the dir already ends in '/'.
153 * Revision 1.9 2001/06/07 14:43:17 swa
154 * slight mistake in make_path, unix path style is /.
156 * Revision 1.8 2001/06/05 22:32:01 jongfoster
157 * New function make_path() to splice directory and file names together.
159 * Revision 1.7 2001/06/03 19:12:30 oes
160 * introduced bindup()
162 * Revision 1.6 2001/06/01 18:14:49 jongfoster
163 * Changing the calls to strerr() to check HAVE_STRERR (which is defined
164 * in config.h if appropriate) rather than the NO_STRERR macro.
166 * Revision 1.5 2001/06/01 10:31:51 oes
167 * Added character class matching to trivimatch; renamed to simplematch
169 * Revision 1.4 2001/05/31 17:32:31 oes
171 * - Enhanced domain part globbing with infix and prefix asterisk
172 * matching and optional unanchored operation
174 * Revision 1.3 2001/05/29 23:10:09 oes
177 * - Introduced chomp()
178 * - Moved strsav() from showargs to miscutil
180 * Revision 1.2 2001/05/29 09:50:24 jongfoster
181 * Unified blocklist/imagelist/permissionslist.
182 * File format is still under discussion, but the internal changes
185 * Also modified interceptor behaviour:
186 * - We now intercept all URLs beginning with one of the following
187 * prefixes (and *only* these prefixes):
189 * * http://ijbswa.sf.net/config/
190 * * http://ijbswa.sourceforge.net/config/
191 * - New interceptors "home page" - go to http://i.j.b/ to see it.
192 * - Internal changes so that intercepted and fast redirect pages
193 * are not replaced with an image.
194 * - Interceptors now have the option to send a binary page direct
195 * to the client. (i.e. ijb-send-banner uses this)
196 * - Implemented show-url-info interceptor. (Which is why I needed
197 * the above interceptors changes - a typical URL is
198 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
199 * The previous mechanism would not have intercepted that, and
200 * if it had been intercepted then it then it would have replaced
203 * Revision 1.1.1.1 2001/05/15 13:59:00 oes
204 * Initial import of version 2.9.3 source tree
207 *********************************************************************/
213 #include <sys/types.h>
215 #if !defined(_WIN32) && !defined(__OS2__)
217 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
223 #include "miscutil.h"
227 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
229 /*********************************************************************
233 * Description : Malloc some memory and set it to '\0'.
234 * The way calloc() ought to be -acjc
237 * 1 : size = Size of memory chunk to return.
239 * Returns : Pointer to newly malloc'd memory chunk.
241 *********************************************************************/
242 void *zalloc(size_t size)
246 if ((ret = (void *)malloc(size)) != NULL)
248 memset(ret, 0, size);
257 /*********************************************************************
259 * Function : write_pid_file
261 * Description : Writes a pid file with the pid of the main process
267 *********************************************************************/
268 void write_pid_file(void)
273 * If no --pidfile option was given,
274 * we can live without one.
276 if (pidfile == NULL) return;
278 if ((fp = fopen(pidfile, "w")) == NULL)
280 log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
284 fprintf(fp, "%u\n", (unsigned int) getpid());
290 #endif /* def unix */
293 /*********************************************************************
295 * Function : hash_string
297 * Description : Take a string and compute a (hopefuly) unique numeric
298 * integer value. This has several uses, but being able
299 * to "switch" a string the one of my favorites.
302 * 1 : s = string to be hashed.
304 * Returns : an unsigned long variable with the hashed value.
306 *********************************************************************/
307 unsigned int hash_string( const char* s )
322 /*********************************************************************
326 * Description : For some reason (which is beyond me), gcc and WIN32
327 * don't like strdup. When a "free" is executed on a
328 * strdup'd ptr, it can at times freez up! So I just
329 * replaced it and problem was solved.
332 * 1 : s = string to duplicate
334 * Returns : Pointer to newly malloc'ed copy of the string.
336 *********************************************************************/
337 char *strdup( const char *s )
339 char * result = (char *)malloc( strlen(s)+1 );
349 #endif /* def __MINGW32__ */
353 /*********************************************************************
355 * Function : safe_strerror
357 * Description : Variant of the library routine strerror() which will
358 * work on systems without the library routine, and
359 * which should never return NULL.
362 * 1 : err = the `errno' of the last operation.
364 * Returns : An "English" string of the last `errno'. Allocated
365 * with strdup(), so caller frees. May be NULL if the
366 * system is out of memory.
368 *********************************************************************/
369 char *safe_strerror(int err)
372 char buf[BUFFER_SIZE];
377 #endif /* HAVE_STRERROR */
381 sprintf(buf, "(errno = %d)", err);
390 /*********************************************************************
392 * Function : strcmpic
394 * Description : Case insensitive string comparison
397 * 1 : s1 = string 1 to compare
398 * 2 : s2 = string 2 to compare
400 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
402 *********************************************************************/
403 int strcmpic(const char *s1, const char *s2)
407 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
413 return(ijb_tolower(*s1) - ijb_tolower(*s2));
418 /*********************************************************************
420 * Function : strncmpic
422 * Description : Case insensitive string comparison (upto n characters)
425 * 1 : s1 = string 1 to compare
426 * 2 : s2 = string 2 to compare
427 * 3 : n = maximum characters to compare
429 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
431 *********************************************************************/
432 int strncmpic(const char *s1, const char *s2, size_t n)
434 if (n <= 0) return(0);
438 if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
447 return(ijb_tolower(*s1) - ijb_tolower(*s2));
452 /*********************************************************************
456 * Description : In-situ-eliminate all leading and trailing whitespace
460 * 1 : string = string to be chomped.
462 * Returns : chomped string
464 *********************************************************************/
465 char *chomp(char *string)
470 * strip trailing whitespace
472 p = string + strlen(string);
473 while (p > string && ijb_isspace(*(p-1)))
480 * find end of leading whitespace
483 while (*q && ijb_isspace(*q))
489 * if there was any, move the rest forwards
504 /*********************************************************************
508 * Description : Reallocate "old" and append text to it. This makes
509 * it easier to append to malloc'd strings.
510 * Running out of memory is a FATAL error.
513 * 1 : old = Old text that is to be extended. Will be
514 * free()d by this routine. May be NULL.
515 * 2 : text_to_append = Text to be appended to old.
518 * Returns : Pointer to newly malloc'ed appended string.
519 * If there is no text to append, return old. Caller
522 *********************************************************************/
523 char *strsav(char *old, const char *text_to_append)
525 size_t old_len, new_len = 0;
528 if ((text_to_append == NULL) || (*text_to_append == '\0'))
535 if ((p = strdup(text_to_append)) == NULL)
537 log_error(LOG_LEVEL_FATAL, "strdup() failed!");
538 /* Never get here - LOG_LEVEL_FATAL causes program exit */
543 old_len = strlen(old);
544 new_len = old_len + strlen(text_to_append) + 1;
546 if ((p = realloc(old, new_len)) == NULL)
548 log_error(LOG_LEVEL_FATAL, "realloc(%d) bytes failed!", new_len);
549 /* Never get here - LOG_LEVEL_FATAL causes program exit */
552 strcpy(p + old_len, text_to_append);
557 /*********************************************************************
559 * Function : string_append
561 * Description : Reallocate target_string and append text to it.
562 * This makes it easier to append to malloc'd strings.
563 * This is similar to the (removed) strsav(), but
564 * running out of memory isn't catastrophic.
568 * The following style provides sufficient error
569 * checking for this routine, with minimal clutter
570 * in the source code. It is recommended if you
571 * have many calls to this function:
573 * char * s = strdup(...); // don't check for error
574 * string_append(&s, ...); // don't check for error
575 * string_append(&s, ...); // don't check for error
576 * string_append(&s, ...); // don't check for error
577 * if (NULL == s) { ... handle error ... }
581 * char * s = strdup(...); // don't check for error
582 * string_append(&s, ...); // don't check for error
583 * string_append(&s, ...); // don't check for error
584 * if (string_append(&s, ...)) {... handle error ...}
587 * 1 : target_string = Pointer to old text that is to be
588 * extended. *target_string will be free()d by this
589 * routine. target_string must be non-NULL.
590 * If *target_string is NULL, this routine will
591 * do nothing and return with an error - this allows
592 * you to make many calls to this routine and only
593 * check for errors after the last one.
594 * 2 : text_to_append = Text to be appended to old.
597 * Returns : JB_ERR_OK on success, and sets *target_string
598 * to newly malloc'ed appended string. Caller
599 * must free(*target_string).
600 * JB_ERR_MEMORY on out-of-memory. (And free()s
601 * *target_string and sets it to NULL).
602 * JB_ERR_MEMORY if *target_string is NULL.
604 *********************************************************************/
605 jb_err string_append(char **target_string, const char *text_to_append)
610 assert(target_string);
611 assert(text_to_append);
613 if (*target_string == NULL)
615 return JB_ERR_MEMORY;
618 if (*text_to_append == '\0')
623 old_len = strlen(*target_string);
625 if (NULL == (new_string = realloc(*target_string,
626 strlen(text_to_append) + old_len + 1)))
628 free(*target_string);
630 *target_string = NULL;
631 return JB_ERR_MEMORY;
634 strcpy(new_string + old_len, text_to_append);
636 *target_string = new_string;
641 /*********************************************************************
643 * Function : string_join
645 * Description : Join two strings together. Frees BOTH the original
646 * strings. If either or both input strings are NULL,
647 * fails as if it had run out of memory.
649 * For comparison, string_append requires that the
650 * second string is non-NULL, and doesn't free it.
652 * Rationale: Too often, we want to do
653 * string_append(s, html_encode(s2)). That assert()s
654 * if s2 is NULL or if html_encode() runs out of memory.
655 * It also leaks memory. Proper checking is cumbersome.
656 * The solution: string_join(s, html_encode(s2)) is safe,
657 * and will free the memory allocated by html_encode().
660 * 1 : target_string = Pointer to old text that is to be
661 * extended. *target_string will be free()d by this
662 * routine. target_string must be non-NULL.
663 * 2 : text_to_append = Text to be appended to old.
665 * Returns : JB_ERR_OK on success, and sets *target_string
666 * to newly malloc'ed appended string. Caller
667 * must free(*target_string).
668 * JB_ERR_MEMORY on out-of-memory, or if
669 * *target_string or text_to_append is NULL. (In
670 * this case, frees *target_string and text_to_append,
671 * sets *target_string to NULL).
673 *********************************************************************/
674 jb_err string_join(char **target_string, char *text_to_append)
678 assert(target_string);
680 if (text_to_append == NULL)
682 freez(*target_string);
683 return JB_ERR_MEMORY;
686 err = string_append(target_string, text_to_append);
688 free(text_to_append);
694 /*********************************************************************
696 * Function : string_toupper
698 * Description : Produce a copy of string with all convertible
699 * characters converted to uppercase.
702 * 1 : string = string to convert
704 * Returns : Uppercase copy of string if possible,
705 * NULL on out-of-memory or if string was NULL.
707 *********************************************************************/
708 char *string_toupper(const char *string)
713 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
723 *p++ = toupper(*q++);
731 /*********************************************************************
733 * Function : simplematch
735 * Description : String matching, with a (greedy) '*' wildcard that
736 * stands for zero or more arbitrary characters and
737 * character classes in [], which take both enumerations
741 * 1 : pattern = pattern for matching
742 * 2 : text = text to be matched
744 * Returns : 0 if match, else nonzero
746 *********************************************************************/
747 int simplematch(char *pattern, char *text)
749 unsigned char *pat = (unsigned char *) pattern;
750 unsigned char *txt = (unsigned char *) text;
751 unsigned char *fallback = pat;
754 unsigned char lastchar = 'a';
756 unsigned char charmap[32];
762 /* EOF pattern but !EOF text? */
768 /* '*' in the pattern? */
772 /* The pattern ends afterwards? Speed up the return. */
778 /* Else, set wildcard mode and remember position after '*' */
783 /* Character range specification? */
786 memset(charmap, '\0', sizeof(charmap));
788 while (*++pat != ']')
794 else if (*pat == '-')
796 if ((*++pat == ']') || *pat == '\0')
800 for(i = lastchar; i <= *pat; i++)
802 charmap[i / 8] |= (1 << (i % 8));
807 charmap[*pat / 8] |= (1 << (*pat % 8));
811 } /* -END- if Character range specification */
814 /* Compare: Char match, or char range match*/
816 || ((*pat == ']') && (charmap[*txt / 8] & (1 << (*txt % 8)))) )
818 /* Sucess, go ahead */
823 /* In wildcard mode, just try again after failiure */
838 /* Cut off extra '*'s */
839 if(*pat == '*') pat++;
841 /* If this is the pattern's end, fine! */
847 /*********************************************************************
851 * Description : Duplicate the first n characters of a string that may
852 * contain '\0' characters.
855 * 1 : string = string to be duplicated
856 * 2 : len = number of bytes to duplicate
858 * Returns : pointer to copy, or NULL if failiure
860 *********************************************************************/
861 char *bindup(const char *string, size_t len)
865 if (NULL == (duplicate = (char *)malloc(len)))
871 memcpy(duplicate, string, len);
879 /*********************************************************************
881 * Function : make_path
883 * Description : Takes a directory name and a file name, returns
884 * the complete path. Handles windows/unix differences.
885 * If the file name is already an absolute path, or if
886 * the directory name is NULL or empty, it returns
890 * 1 : dir = Name of directory or NULL for none.
891 * 2 : file = Name of file. Should not be NULL or empty.
893 * Returns : "dir/file" (Or on windows, "dir\file").
894 * It allocates the string on the heap. Caller frees.
895 * Returns NULL in error (i.e. NULL file or out of
898 *********************************************************************/
899 char * make_path(const char * dir, const char * file)
910 strncpy(path,dir+2,512);
914 strncpy(path,dir+1,512);
919 strncpy(path,dir,512);
925 if(AddPart(path,file,512))
931 #else /* ndef AMIGA */
933 if ((file == NULL) || (*file == '\0'))
935 return NULL; /* Error */
938 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
939 #if defined(_WIN32) || defined(__OS2__)
940 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
941 #else /* ifndef _WIN32 || __OS2__ */
942 || (*file == '/') /* Absolute path (U*ix) */
943 #endif /* ifndef _WIN32 || __OS2__ */
953 if ( *dir != '/' && basedir && *basedir )
955 path = malloc( strlen( basedir ) + strlen(dir) + strlen(file) + 3);
956 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
957 strcpy(path, basedir);
963 path = malloc(strlen(dir) + strlen(file) + 2);
964 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
969 path = malloc(strlen(dir) + strlen(file) + 2);
970 if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
973 #endif /* defined unix */
975 #if defined(_WIN32) || defined(__OS2__)
976 if(path[strlen(path)-1] != '\\')
980 #else /* ifndef _WIN32 || __OS2__ */
981 if(path[strlen(path)-1] != '/')
985 #endif /* ifndef _WIN32 || __OS2__ */
990 #endif /* ndef AMIGA */
995 * What follows is a portable snprintf routine, written by Mark Martinec.
996 * See: http://www.ijs.si/software/snprintf/
997 * Anyone who needs it can add a define for themselves... so far, only
998 * OS/2 (native) lacks snprintf.
1001 - a portable implementation of snprintf,
1002 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
1004 snprintf is a routine to convert numeric and string arguments to
1005 formatted strings. It is similar to sprintf(3) provided in a system's
1006 C library, yet it requires an additional argument - the buffer size -
1007 and it guarantees never to store anything beyond the given buffer,
1008 regardless of the format or arguments to be formatted. Some newer
1009 operating systems do provide snprintf in their C library, but many do
1010 not or do provide an inadequate (slow or idiosyncratic) version, which
1011 calls for a portable implementation of this routine.
1015 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
1016 Copyright © 1999, Mark Martinec
1022 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
1023 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
1025 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
1026 # if defined(NEED_SNPRINTF_ONLY)
1027 # undef NEED_SNPRINTF_ONLY
1029 # if !defined(PREFER_PORTABLE_SNPRINTF)
1030 # define PREFER_PORTABLE_SNPRINTF
1034 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1035 #define SOLARIS_COMPATIBLE
1038 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1039 #define HPUX_COMPATIBLE
1042 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1043 #define DIGITAL_UNIX_COMPATIBLE
1046 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1047 #define PERL_COMPATIBLE
1050 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1051 #define LINUX_COMPATIBLE
1054 #include <sys/types.h>
1065 #define isdigit(c) ((c) >= '0' && (c) <= '9')
1067 /* For copying strings longer or equal to 'breakeven_point'
1068 * it is more efficient to call memcpy() than to do it inline.
1069 * The value depends mostly on the processor architecture,
1070 * but also on the compiler and its optimization capabilities.
1071 * The value is not critical, some small value greater than zero
1072 * will be just fine if you don't care to squeeze every drop
1073 * of performance out of the code.
1075 * Small values favor memcpy, large values favor inline code.
1077 #if defined(__alpha__) || defined(__alpha)
1078 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
1080 #if defined(__i386__) || defined(__i386)
1081 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
1084 # define breakeven_point 10 /* HP-PA - gcc */
1086 #if defined(__sparc__) || defined(__sparc)
1087 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
1090 /* some other values of possible interest: */
1091 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
1092 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
1094 #ifndef breakeven_point
1095 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
1098 #define fast_memcpy(d,s,n) \
1099 { register size_t nn = (size_t)(n); \
1100 if (nn >= breakeven_point) memcpy((d), (s), nn); \
1101 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1102 register char *dd; register const char *ss; \
1103 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
1105 #define fast_memset(d,c,n) \
1106 { register size_t nn = (size_t)(n); \
1107 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
1108 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1109 register char *dd; register const int cc=(int)(c); \
1110 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1114 #if defined(NEED_ASPRINTF)
1115 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
1117 #if defined(NEED_VASPRINTF)
1118 int vasprintf (char **ptr, const char *fmt, va_list ap);
1120 #if defined(NEED_ASNPRINTF)
1121 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1123 #if defined(NEED_VASNPRINTF)
1124 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1127 #if defined(HAVE_SNPRINTF)
1128 /* declare our portable snprintf routine under name portable_snprintf */
1129 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1131 /* declare our portable routines under names snprintf and vsnprintf */
1132 #define portable_snprintf snprintf
1133 #if !defined(NEED_SNPRINTF_ONLY)
1134 #define portable_vsnprintf vsnprintf
1138 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1139 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1140 #if !defined(NEED_SNPRINTF_ONLY)
1141 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1147 static char credits[] = "\n\
1148 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1149 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1150 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1152 #if defined(NEED_ASPRINTF)
1153 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1159 va_start(ap, fmt); /* measure the required size */
1160 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1162 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1163 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1164 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1168 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1170 assert(str_l2 == str_l);
1176 #if defined(NEED_VASPRINTF)
1177 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1183 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1184 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1187 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1188 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1189 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1191 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1192 assert(str_l2 == str_l);
1198 #if defined(NEED_ASNPRINTF)
1199 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1204 va_start(ap, fmt); /* measure the required size */
1205 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1207 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1208 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1209 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1210 if (str_m == 0) { /* not interested in resulting string, just return size */
1212 *ptr = (char *) malloc(str_m);
1213 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1217 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1219 assert(str_l2 == str_l);
1226 #if defined(NEED_VASNPRINTF)
1227 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1232 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1233 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1236 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1237 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1238 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1239 if (str_m == 0) { /* not interested in resulting string, just return size */
1241 *ptr = (char *) malloc(str_m);
1242 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1244 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1245 assert(str_l2 == str_l);
1253 * If the system does have snprintf and the portable routine is not
1254 * specifically required, this module produces no code for snprintf/vsnprintf.
1256 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1258 #if !defined(NEED_SNPRINTF_ONLY)
1259 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1264 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1270 #if defined(NEED_SNPRINTF_ONLY)
1271 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1273 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1276 #if defined(NEED_SNPRINTF_ONLY)
1280 const char *p = fmt;
1282 /* In contrast with POSIX, the ISO C99 now says
1283 * that str can be NULL and str_m can be 0.
1284 * This is more useful than the old: if (str_m < 1) return -1; */
1286 #if defined(NEED_SNPRINTF_ONLY)
1292 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1293 /* but the following code achieves better performance for cases
1294 * where format string is long and contains few conversions */
1295 const char *q = strchr(p+1,'%');
1296 size_t n = !q ? strlen(p) : (q-p);
1297 if (str_l < str_m) {
1298 size_t avail = str_m-str_l;
1299 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1303 const char *starting_p;
1304 size_t min_field_width = 0, precision = 0;
1305 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1306 int alternate_form = 0, force_sign = 0;
1307 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1308 the ' ' flag should be ignored. */
1309 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1310 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1312 const char *str_arg; /* string address in case of string argument */
1313 size_t str_arg_l; /* natural field width of arg without padding
1315 unsigned char uchar_arg;
1316 /* unsigned char argument value - only defined for c conversion.
1317 N.B. standard explicitly states the char argument for
1318 the c conversion is unsigned */
1320 size_t number_of_zeros_to_pad = 0;
1321 /* number of zeros to be inserted for numeric conversions
1322 as required by the precision or minimal field width */
1324 size_t zero_padding_insertion_ind = 0;
1325 /* index into tmp where zero padding is to be inserted */
1327 char fmt_spec = '\0';
1328 /* current conversion specifier character */
1330 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1332 starting_p = p; p++; /* skip '%' */
1334 while (*p == '0' || *p == '-' || *p == '+' ||
1335 *p == ' ' || *p == '#' || *p == '\'') {
1337 case '0': zero_padding = 1; break;
1338 case '-': justify_left = 1; break;
1339 case '+': force_sign = 1; space_for_positive = 0; break;
1340 case ' ': force_sign = 1;
1341 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1342 #ifdef PERL_COMPATIBLE
1343 /* ... but in Perl the last of ' ' and '+' applies */
1344 space_for_positive = 1;
1347 case '#': alternate_form = 1; break;
1352 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1354 /* parse field width */
1357 p++; j = va_arg(ap, int);
1358 if (j >= 0) min_field_width = j;
1359 else { min_field_width = -j; justify_left = 1; }
1360 } else if (isdigit((int)(*p))) {
1361 /* size_t could be wider than unsigned int;
1362 make sure we treat argument like common implementations do */
1363 unsigned int uj = *p++ - '0';
1364 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1365 min_field_width = uj;
1367 /* parse precision */
1369 p++; precision_specified = 1;
1371 int j = va_arg(ap, int);
1373 if (j >= 0) precision = j;
1375 precision_specified = 0; precision = 0;
1377 * Solaris 2.6 man page claims that in this case the precision
1378 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1379 * claim that this case should be treated as unspecified precision,
1380 * which is what we do here.
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');
1391 /* parse 'h', 'l' and 'll' length modifiers */
1392 if (*p == 'h' || *p == 'l') {
1393 length_modifier = *p; p++;
1394 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1395 #ifdef SNPRINTF_LONGLONG_SUPPORT
1396 length_modifier = '2'; /* double l encoded as '2' */
1398 length_modifier = 'l'; /* treat it as a single 'l' */
1404 /* common synonyms: */
1406 case 'i': fmt_spec = 'd'; break;
1407 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1408 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1409 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1412 /* get parameter value, do initial processing */
1414 case '%': /* % behaves similar to 's' regarding flags and field widths */
1415 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1417 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1418 /* the result of zero padding flag with non-numeric conversion specifier*/
1419 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1420 /* Digital Unix and Linux does not. */
1421 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1422 zero_padding = 0; /* turn zero padding off for string conversions */
1429 int j = va_arg(ap, int);
1430 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1431 str_arg = (const char *) &uchar_arg;
1435 str_arg = va_arg(ap, const char *);
1436 if (!str_arg) str_arg_l = 0;
1437 /* make sure not to address string beyond the specified precision !!! */
1438 else if (!precision_specified) str_arg_l = strlen(str_arg);
1439 /* truncate string if necessary as requested by precision */
1440 else if (precision == 0) str_arg_l = 0;
1442 /* memchr on HP does not like n > 2^31 !!! */
1443 const char *q = memchr(str_arg, '\0',
1444 precision <= 0x7fffffff ? precision : 0x7fffffff);
1445 str_arg_l = !q ? precision : (q-str_arg);
1451 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1452 /* NOTE: the u, o, x, X and p conversion specifiers imply
1453 the value is unsigned; d implies a signed value */
1456 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1457 +1 if greater than zero (or nonzero for unsigned arguments),
1458 -1 if negative (unsigned argument is never negative) */
1460 int int_arg = 0; unsigned int uint_arg = 0;
1461 /* only defined for length modifier h, or for no length modifiers */
1463 long int long_arg = 0; unsigned long int ulong_arg = 0;
1464 /* only defined for length modifier l */
1466 void *ptr_arg = NULL;
1467 /* pointer argument value -only defined for p conversion */
1469 #ifdef SNPRINTF_LONGLONG_SUPPORT
1470 long long int long_long_arg = 0;
1471 unsigned long long int ulong_long_arg = 0;
1472 /* only defined for length modifier ll */
1474 if (fmt_spec == 'p') {
1475 /* HPUX 10: An l, h, ll or L before any other conversion character
1476 * (other than d, i, u, o, x, or X) is ignored.
1478 * not specified, but seems to behave as HPUX does.
1479 * Solaris: If an h, l, or L appears before any other conversion
1480 * specifier (other than d, i, u, o, x, or X), the behavior
1481 * is undefined. (Actually %hp converts only 16-bits of address
1482 * and %llp treats address as 64-bit data which is incompatible
1483 * with (void *) argument on a 32-bit system).
1485 #ifdef SOLARIS_COMPATIBLE
1486 # ifdef SOLARIS_BUG_COMPATIBLE
1487 /* keep length modifiers even if it represents 'll' */
1489 if (length_modifier == '2') length_modifier = '\0';
1492 length_modifier = '\0';
1494 ptr_arg = va_arg(ap, void *);
1495 if (ptr_arg != NULL) arg_sign = 1;
1496 } else if (fmt_spec == 'd') { /* signed */
1497 switch (length_modifier) {
1500 /* It is non-portable to specify a second argument of char or short
1501 * to va_arg, because arguments seen by the called function
1502 * are not char or short. C converts char and short arguments
1503 * to int before passing them to a function.
1505 int_arg = va_arg(ap, int);
1506 if (int_arg > 0) arg_sign = 1;
1507 else if (int_arg < 0) arg_sign = -1;
1510 long_arg = va_arg(ap, long int);
1511 if (long_arg > 0) arg_sign = 1;
1512 else if (long_arg < 0) arg_sign = -1;
1514 #ifdef SNPRINTF_LONGLONG_SUPPORT
1516 long_long_arg = va_arg(ap, long long int);
1517 if (long_long_arg > 0) arg_sign = 1;
1518 else if (long_long_arg < 0) arg_sign = -1;
1522 } else { /* unsigned */
1523 switch (length_modifier) {
1526 uint_arg = va_arg(ap, unsigned int);
1527 if (uint_arg) arg_sign = 1;
1530 ulong_arg = va_arg(ap, unsigned long int);
1531 if (ulong_arg) arg_sign = 1;
1533 #ifdef SNPRINTF_LONGLONG_SUPPORT
1535 ulong_long_arg = va_arg(ap, unsigned long long int);
1536 if (ulong_long_arg) arg_sign = 1;
1541 str_arg = tmp; str_arg_l = 0;
1543 * For d, i, u, o, x, and X conversions, if precision is specified,
1544 * the '0' flag should be ignored. This is so with Solaris 2.6,
1545 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1547 #ifndef PERL_COMPATIBLE
1548 if (precision_specified) zero_padding = 0;
1550 if (fmt_spec == 'd') {
1551 if (force_sign && arg_sign >= 0)
1552 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1553 /* leave negative numbers for sprintf to handle,
1554 to avoid handling tricky cases like (short int)(-32768) */
1555 #ifdef LINUX_COMPATIBLE
1556 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1557 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1559 } else if (alternate_form) {
1560 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1561 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1562 /* alternate form should have no effect for p conversion, but ... */
1563 #ifdef HPUX_COMPATIBLE
1564 else if (fmt_spec == 'p'
1565 /* HPUX 10: for an alternate form of p conversion,
1566 * a nonzero result is prefixed by 0x. */
1567 #ifndef HPUX_BUG_COMPATIBLE
1568 /* Actually it uses 0x prefix even for a zero value. */
1571 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1574 zero_padding_insertion_ind = str_arg_l;
1575 if (!precision_specified) precision = 1; /* default precision is 1 */
1576 if (precision == 0 && arg_sign == 0
1577 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1579 /* HPUX 10 man page claims: With conversion character p the result of
1580 * converting a zero value with a precision of zero is a null string.
1581 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1584 /* converted to null string */
1585 /* When zero value is formatted with an explicit precision 0,
1586 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1588 char f[5]; int f_l = 0;
1589 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1590 if (!length_modifier) { }
1591 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1592 else f[f_l++] = length_modifier;
1593 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1594 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1595 else if (fmt_spec == 'd') { /* signed */
1596 switch (length_modifier) {
1598 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1599 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1600 #ifdef SNPRINTF_LONGLONG_SUPPORT
1601 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1604 } else { /* unsigned */
1605 switch (length_modifier) {
1607 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1608 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1609 #ifdef SNPRINTF_LONGLONG_SUPPORT
1610 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1614 /* include the optional minus sign and possible "0x"
1615 in the region before the zero padding insertion point */
1616 if (zero_padding_insertion_ind < str_arg_l &&
1617 tmp[zero_padding_insertion_ind] == '-') {
1618 zero_padding_insertion_ind++;
1620 if (zero_padding_insertion_ind+1 < str_arg_l &&
1621 tmp[zero_padding_insertion_ind] == '0' &&
1622 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1623 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1624 zero_padding_insertion_ind += 2;
1627 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1628 if (alternate_form && fmt_spec == 'o'
1629 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1632 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1634 /* unless zero is already the first character */
1635 && !(zero_padding_insertion_ind < str_arg_l
1636 && tmp[zero_padding_insertion_ind] == '0')
1638 ) { /* assure leading zero for alternate-form octal numbers */
1639 if (!precision_specified || precision < num_of_digits+1) {
1640 /* precision is increased to force the first character to be zero,
1641 except if a zero value is formatted with an explicit precision
1643 precision = num_of_digits+1; precision_specified = 1;
1646 /* zero padding to specified precision? */
1647 if (num_of_digits < precision)
1648 number_of_zeros_to_pad = precision - num_of_digits;
1650 /* zero padding to specified minimal field width? */
1651 if (!justify_left && zero_padding) {
1652 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1653 if (n > 0) number_of_zeros_to_pad += n;
1657 default: /* unrecognized conversion specifier, keep format string as-is*/
1658 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1659 #ifndef DIGITAL_UNIX_COMPATIBLE
1660 justify_left = 1; min_field_width = 0; /* reset flags */
1662 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1663 /* keep the entire format string unchanged */
1664 str_arg = starting_p; str_arg_l = p - starting_p;
1665 /* well, not exactly so for Linux, which does something inbetween,
1666 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1668 /* discard the unrecognized conversion, just keep *
1669 * the unrecognized conversion character */
1670 str_arg = p; str_arg_l = 0;
1672 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1673 if not at end-of-string */
1676 if (*p) p++; /* step over the just processed conversion specifier */
1677 /* insert padding to the left as requested by min_field_width;
1678 this does not include the zero padding in case of numerical conversions*/
1679 if (!justify_left) { /* left padding with blank or zero */
1680 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1682 if (str_l < str_m) {
1683 size_t avail = str_m-str_l;
1684 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1689 /* zero padding as requested by the precision or by the minimal field width
1690 * for numeric conversions required? */
1691 if (number_of_zeros_to_pad <= 0) {
1692 /* will not copy first part of numeric right now, *
1693 * force it to be copied later in its entirety */
1694 zero_padding_insertion_ind = 0;
1696 /* insert first part of numerics (sign or '0x') before zero padding */
1697 int n = zero_padding_insertion_ind;
1699 if (str_l < str_m) {
1700 size_t avail = str_m-str_l;
1701 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1705 /* insert zero padding as requested by the precision or min field width */
1706 n = number_of_zeros_to_pad;
1708 if (str_l < str_m) {
1709 size_t avail = str_m-str_l;
1710 fast_memset(str+str_l, '0', (n>avail?avail:n));
1715 /* insert formatted string
1716 * (or as-is conversion specifier for unknown conversions) */
1717 { int n = str_arg_l - zero_padding_insertion_ind;
1719 if (str_l < str_m) {
1720 size_t avail = str_m-str_l;
1721 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1727 /* insert right padding */
1728 if (justify_left) { /* right blank padding to the field width */
1729 int n = min_field_width - (str_arg_l+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, ' ', (n>avail?avail:n));
1740 #if defined(NEED_SNPRINTF_ONLY)
1743 if (str_m > 0) { /* make sure the string is null-terminated
1744 even at the expense of overwriting the last character
1745 (shouldn't happen, but just in case) */
1746 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1748 /* Return the number of characters formatted (excluding trailing null
1749 * character), that is, the number of characters that would have been
1750 * written to the buffer if it were large enough.
1752 * The value of str_l should be returned, but str_l is of unsigned type
1753 * size_t, and snprintf is int, possibly leading to an undetected
1754 * integer overflow, resulting in a negative return value, which is illegal.
1755 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1756 * Should errno be set to EOVERFLOW and EOF returned in this case???
1761 #endif /* __OS2__ */