Renaming Makefile.in to GNUmakefile.in so that non-GNU versions of
[privoxy.git] / miscutil.c
1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.24 2001/11/05 21:41:43 steudten Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/miscutil.c,v $
5  *
6  * Purpose     :  zalloc, hash_string, safe_strerror, strcmpic,
7  *                strncmpic, strsav, chomp, and MinGW32 strdup
8  *                functions. 
9  *                These are each too small to deserve their own file
10  *                but don't really fit in any other file.
11  *
12  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
13  *                IJBSWA team.  http://ijbswa.sourceforge.net
14  *
15  *                Based on the Internet Junkbuster originally written
16  *                by and Copyright (C) 1997 Anonymous Coders and 
17  *                Junkbusters Corporation.  http://www.junkbusters.com
18  *
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.
24  *
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.
30  *
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.
36  *
37  * Revisions   :
38  *    $Log: miscutil.c,v $
39  *    Revision 1.24  2001/11/05 21:41:43  steudten
40  *    Add changes to be a real daemon just for unix os.
41  *    (change cwd to /, detach from controlling tty, set
42  *    process group and session leader to the own process.
43  *    Add DBG() Macro.
44  *    Add some fatal-error log message for failed malloc().
45  *    Add '-d' if compiled with 'configure --with-debug' to
46  *    enable debug output.
47  *
48  *    Revision 1.23  2001/10/29 03:48:10  david__schmidt
49  *    OS/2 native needed a snprintf() routine.  Added one to miscutil, brackedted
50  *    by and __OS2__ ifdef.
51  *
52  *    Revision 1.22  2001/10/26 17:39:38  oes
53  *    Moved ijb_isspace and ijb_tolower to project.h
54  *
55  *    Revision 1.21  2001/10/23 21:27:50  jongfoster
56  *    Standardising error codes in string_append
57  *    make_path() no longer adds '\\' if the dir already ends in '\\' (this
58  *    is just copying a UNIX-specific fix to the Windows-specific part)
59  *
60  *    Revision 1.20  2001/10/22 15:33:56  david__schmidt
61  *    Special-cased OS/2 out of the Netscape-abort-on-404-in-js problem in
62  *    filters.c.  Added a FIXME in front of the offending code.  I'll gladly
63  *    put in a better/more robust fix for all parties if one is presented...
64  *    It seems that just returning 200 instead of 404 would pretty much fix
65  *    it for everyone, but I don't know all the history of the problem.
66  *
67  *    Revision 1.19  2001/10/14 22:02:57  jongfoster
68  *    New function string_append() which is like strsav(), but running
69  *    out of memory isn't automatically FATAL.
70  *
71  *    Revision 1.18  2001/09/20 13:33:43  steudten
72  *
73  *    change long to int as return value in hash_string(). Remember the wraparound
74  *    for int = long = sizeof(4) - thats maybe not what we want.
75  *
76  *    Revision 1.17  2001/09/13 20:51:29  jongfoster
77  *    Fixing potential problems with characters >=128 in simplematch()
78  *    This was also a compiler warning.
79  *
80  *    Revision 1.16  2001/09/10 10:56:59  oes
81  *    Silenced compiler warnings
82  *
83  *    Revision 1.15  2001/07/13 14:02:24  oes
84  *    Removed vim-settings
85  *
86  *    Revision 1.14  2001/06/29 21:45:41  oes
87  *    Indentation, CRLF->LF, Tab-> Space
88  *
89  *    Revision 1.13  2001/06/29 13:32:14  oes
90  *    Removed logentry from cancelled commit
91  *
92  *    Revision 1.12  2001/06/09 10:55:28  jongfoster
93  *    Changing BUFSIZ ==> BUFFER_SIZE
94  *
95  *    Revision 1.11  2001/06/07 23:09:19  jongfoster
96  *    Cosmetic indentation changes.
97  *
98  *    Revision 1.10  2001/06/07 14:51:38  joergs
99  *    make_path() no longer adds '/' if the dir already ends in '/'.
100  *
101  *    Revision 1.9  2001/06/07 14:43:17  swa
102  *    slight mistake in make_path, unix path style is /.
103  *
104  *    Revision 1.8  2001/06/05 22:32:01  jongfoster
105  *    New function make_path() to splice directory and file names together.
106  *
107  *    Revision 1.7  2001/06/03 19:12:30  oes
108  *    introduced bindup()
109  *
110  *    Revision 1.6  2001/06/01 18:14:49  jongfoster
111  *    Changing the calls to strerr() to check HAVE_STRERR (which is defined
112  *    in config.h if appropriate) rather than the NO_STRERR macro.
113  *
114  *    Revision 1.5  2001/06/01 10:31:51  oes
115  *    Added character class matching to trivimatch; renamed to simplematch
116  *
117  *    Revision 1.4  2001/05/31 17:32:31  oes
118  *
119  *     - Enhanced domain part globbing with infix and prefix asterisk
120  *       matching and optional unanchored operation
121  *
122  *    Revision 1.3  2001/05/29 23:10:09  oes
123  *
124  *
125  *     - Introduced chomp()
126  *     - Moved strsav() from showargs to miscutil
127  *
128  *    Revision 1.2  2001/05/29 09:50:24  jongfoster
129  *    Unified blocklist/imagelist/permissionslist.
130  *    File format is still under discussion, but the internal changes
131  *    are (mostly) done.
132  *
133  *    Also modified interceptor behaviour:
134  *    - We now intercept all URLs beginning with one of the following
135  *      prefixes (and *only* these prefixes):
136  *        * http://i.j.b/
137  *        * http://ijbswa.sf.net/config/
138  *        * http://ijbswa.sourceforge.net/config/
139  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
140  *    - Internal changes so that intercepted and fast redirect pages
141  *      are not replaced with an image.
142  *    - Interceptors now have the option to send a binary page direct
143  *      to the client. (i.e. ijb-send-banner uses this)
144  *    - Implemented show-url-info interceptor.  (Which is why I needed
145  *      the above interceptors changes - a typical URL is
146  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
147  *      The previous mechanism would not have intercepted that, and
148  *      if it had been intercepted then it then it would have replaced
149  *      it with an image.)
150  *
151  *    Revision 1.1.1.1  2001/05/15 13:59:00  oes
152  *    Initial import of version 2.9.3 source tree
153  *
154  *
155  *********************************************************************/
156 \f
157
158 #include "config.h"
159
160 #include <stdio.h>
161 #include <stdlib.h>
162 #include <string.h>
163 #include <ctype.h>
164 #include <assert.h>
165
166 #include "project.h"
167 #include "miscutil.h"
168 #include "errlog.h"
169
170 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
171
172 /*********************************************************************
173  *
174  * Function    :  zalloc
175  *
176  * Description :  Malloc some memory and set it to '\0'.
177  *                The way calloc() ought to be -acjc
178  *
179  * Parameters  :
180  *          1  :  size = Size of memory chunk to return.
181  *
182  * Returns     :  Pointer to newly malloc'd memory chunk.
183  *
184  *********************************************************************/
185 void *zalloc(int size)
186 {
187    void * ret;
188
189    if ((ret = (void *)malloc(size)) != NULL)
190    {
191       memset(ret, 0, size);
192    }
193
194    return(ret);
195 }
196
197
198 /*********************************************************************
199  *
200  * Function    :  hash_string
201  *
202  * Description :  Take a string and compute a (hopefuly) unique numeric
203  *                integer value.  This has several uses, but being able
204  *                to "switch" a string the one of my favorites.
205  *
206  * Parameters  :
207  *          1  :  s : string to be hashed.
208  *
209  * Returns     :  an unsigned long variable with the hashed value.
210  *
211  *********************************************************************/
212 unsigned int hash_string( const char* s )
213 {
214    unsigned int h = 0; 
215
216    for ( ; *s; ++s )
217    {
218       h = 5 * h + *s;
219    }
220
221    return (h);
222
223 }
224
225
226 #ifdef __MINGW32__
227 /*********************************************************************
228  *
229  * Function    :  strdup
230  *
231  * Description :  For some reason (which is beyond me), gcc and WIN32
232  *                don't like strdup.  When a "free" is executed on a
233  *                strdup'd ptr, it can at times freez up!  So I just
234  *                replaced it and problem was solved.
235  *
236  * Parameters  :
237  *          1  :  s = string to duplicate
238  *
239  * Returns     :  Pointer to newly malloc'ed copy of the string.
240  *
241  *********************************************************************/
242 char *strdup( const char *s )
243 {
244    char * result = (char *)malloc( strlen(s)+1 );
245
246    if (result != NULL)
247    {
248       strcpy( result, s );
249    }
250
251    return( result );
252 }
253
254 #endif /* def __MINGW32__ */
255
256
257
258 /*********************************************************************
259  *
260  * Function    :  safe_strerror
261  *
262  * Description :  Variant of the library routine strerror() which will
263  *                work on systems without the library routine, and
264  *                which should never return NULL.
265  *
266  * Parameters  :
267  *          1  :  err = the `errno' of the last operation.
268  *
269  * Returns     :  An "English" string of the last `errno'.  Allocated
270  *                with strdup(), so caller frees.  May be NULL if the
271  *                system is out of memory.
272  *
273  *********************************************************************/
274 char *safe_strerror(int err)
275 {
276    char *s = NULL;
277    char buf[BUFFER_SIZE];
278
279
280 #ifdef HAVE_STRERROR
281    s = strerror(err);
282 #endif /* HAVE_STRERROR */
283
284    if (s == NULL)
285    {
286       sprintf(buf, "(errno = %d)", err);
287       s = buf;
288    }
289
290    return(strdup(s));
291
292 }
293
294
295 /*********************************************************************
296  *
297  * Function    :  strcmpic
298  *
299  * Description :  Case insensitive string comparison
300  *
301  * Parameters  :
302  *          1  :  s1 = string 1 to compare
303  *          2  :  s2 = string 2 to compare
304  *
305  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
306  *
307  *********************************************************************/
308 int strcmpic(const char *s1, const char *s2)
309 {
310    while (*s1 && *s2)
311    {
312       if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
313       {
314          break;
315       }
316       s1++, s2++;
317    }
318    return(ijb_tolower(*s1) - ijb_tolower(*s2));
319
320 }
321
322
323 /*********************************************************************
324  *
325  * Function    :  strncmpic
326  *
327  * Description :  Case insensitive string comparison (upto n characters)
328  *
329  * Parameters  :
330  *          1  :  s1 = string 1 to compare
331  *          2  :  s2 = string 2 to compare
332  *          3  :  n = maximum characters to compare
333  *
334  * Returns     :  0 if s1==s2, Negative if s1<s2, Positive if s1>s2
335  *
336  *********************************************************************/
337 int strncmpic(const char *s1, const char *s2, size_t n)
338 {
339    if (n <= 0) return(0);
340
341    while (*s1 && *s2)
342    {
343       if ( ( *s1 != *s2 ) && ( ijb_tolower(*s1) != ijb_tolower(*s2) ) )
344       {
345          break;
346       }
347
348       if (--n <= 0) break;
349
350       s1++, s2++;
351    }
352    return(ijb_tolower(*s1) - ijb_tolower(*s2));
353
354 }
355
356
357 /*********************************************************************
358  *
359  * Function    :  chomp
360  *
361  * Description :  In-situ-eliminate all leading and trailing whitespace
362  *                from a string.
363  *
364  * Parameters  :
365  *          1  :  s : string to be chomped.
366  *
367  * Returns     :  chomped string
368  *
369  *********************************************************************/
370 char *chomp(char *string)
371 {
372    char *p, *q, *r;
373
374    /* 
375     * strip trailing whitespace
376     */
377    p = string + strlen(string);
378    while (p > string && ijb_isspace(*(p-1)))
379    {
380       p--;
381    }
382    *p = '\0';
383
384    /* 
385     * find end of leading whitespace 
386     */
387    q = r = string;
388    while (*q && ijb_isspace(*q))
389    {
390       q++;
391    }
392
393    /*
394     * if there was any, move the rest forwards
395     */
396    if (q != string)
397    {
398       while (q <= p)
399       {
400          *r++ = *q++;
401       }
402    }
403
404    return(string);
405
406 }
407
408
409 /*********************************************************************
410  *
411  * Function    :  strsav
412  *
413  * Description :  Reallocate "old" and append text to it.  This makes
414  *                it easier to append to malloc'd strings.
415  *                Running out of memory is a FATAL error.
416  *
417  * Parameters  :
418  *          1  :  old = Old text that is to be extended.  Will be
419  *                free()d by this routine.  May be NULL.
420  *          2  :  text_to_append = Text to be appended to old.
421  *                May be NULL.
422  *
423  * Returns     :  Pointer to newly malloc'ed appended string.
424  *                If there is no text to append, return old.  Caller
425  *                must free().
426  *
427  *********************************************************************/
428 char *strsav(char *old, const char *text_to_append)
429 {
430    int old_len, new_len = 0;
431    char *p;
432
433    if (( text_to_append == NULL) || (*text_to_append == '\0'))
434    {
435       return(old);
436    }
437
438    if (NULL == old)
439    {
440       if ((p = strdup(text_to_append)) == NULL)
441       {
442          log_error(LOG_LEVEL_FATAL, "strdup() failed!", new_len);
443          /* Never get here - LOG_LEVEL_FATAL causes program exit */
444       }
445       return p;
446    }
447
448    old_len = strlen(old);
449    new_len = old_len + strlen(text_to_append) + 1;
450
451    if ((p = realloc(old, new_len)) == NULL)
452    {
453       log_error(LOG_LEVEL_FATAL, "realloc(%d) bytes failed!", new_len);
454       /* Never get here - LOG_LEVEL_FATAL causes program exit */
455    }
456
457    strcpy(p + old_len, text_to_append);
458    return(p);
459 }
460
461
462 /*********************************************************************
463  *
464  * Function    :  string_append
465  *
466  * Description :  Reallocate target_string and append text to it.  
467  *                This makes it easier to append to malloc'd strings.
468  *                This is similar to strsav(), but running out of
469  *                memory isn't catastrophic.
470  *
471  *                Programming style:
472  *
473  *                The following style provides sufficient error
474  *                checking for this routine, with minimal clutter
475  *                in the source code.  It is recommended if you
476  *                have many calls to this function:
477  *
478  *                char * s = strdup(...); // don't check for error
479  *                string_append(&s, ...);  // don't check for error
480  *                string_append(&s, ...);  // don't check for error
481  *                string_append(&s, ...);  // don't check for error
482  *                if (NULL == s) { ... handle error ... }
483  *
484  *                OR, equivalently:
485  *
486  *                char * s = strdup(...); // don't check for error
487  *                string_append(&s, ...);  // don't check for error
488  *                string_append(&s, ...);  // don't check for error
489  *                if (string_append(&s, ...)) {... handle error ...}
490  *
491  * Parameters  :
492  *          1  :  target_string = Pointer to old text that is to be
493  *                extended.  *target_string will be free()d by this
494  *                routine.  target_string must be non-NULL.
495  *                If *target_string is NULL, this routine will
496  *                do nothing and return with an error - this allows
497  *                you to make many calls to this routine and only
498  *                check for errors after the last one.
499  *          2  :  text_to_append = Text to be appended to old.
500  *                Must not be NULL.
501  *
502  * Returns     :  JB_ERR_OK on success, and sets *target_string
503  *                   to newly malloc'ed appended string.  Caller
504  *                   must free(*target_string).
505  *                JB_ERR_MEMORY on out-of-memory.  (And free()s
506  *                   *target_string and sets it to NULL).
507  *                JB_ERR_MEMORY if *target_string is NULL.
508  *
509  *********************************************************************/
510 jb_err string_append(char **target_string, const char *text_to_append)
511 {
512    size_t old_len;
513    char *new_string;
514
515    assert(target_string);
516    assert(text_to_append);
517
518    if (*target_string == NULL)
519    {
520       return JB_ERR_MEMORY;
521    }
522
523    if (*text_to_append == '\0')
524    {
525       return JB_ERR_OK;
526    }
527
528    old_len = strlen(*target_string);
529
530    if (NULL == (new_string = realloc(*target_string,
531           strlen(text_to_append) + old_len + 1)))
532    {
533       free(*target_string);
534
535       *target_string = NULL;
536       return JB_ERR_MEMORY;
537    }
538
539    strcpy(new_string + old_len, text_to_append);
540
541    *target_string = new_string;
542    return JB_ERR_OK;
543 }
544
545
546 /*********************************************************************
547  *
548  * Function    :  simplematch
549  *
550  * Description :  String matching, with a (greedy) '*' wildcard that
551  *                stands for zero or more arbitrary characters and
552  *                character classes in [], which take both enumerations
553  *                and ranges.
554  *
555  * Parameters  :
556  *          1  :  pattern = pattern for matching
557  *          2  :  text    = text to be matched
558  *
559  * Returns     :  0 if match, else nonzero
560  *
561  *********************************************************************/
562 int simplematch(char *pattern, char *text)
563 {
564    unsigned char *pat = (unsigned char *) pattern;
565    unsigned char *txt = (unsigned char *) text;
566    unsigned char *fallback = pat; 
567    int wildcard = 0;
568   
569    unsigned char lastchar = 'a';
570    unsigned i;
571    unsigned char charmap[32];
572   
573   
574    while (*txt)
575    {
576
577       /* EOF pattern but !EOF text? */
578       if (*pat == '\0')
579       {
580          return 1;
581       }
582
583       /* '*' in the pattern?  */
584       if (*pat == '*') 
585       {
586      
587          /* The pattern ends afterwards? Speed up the return. */
588          if (*++pat == '\0')
589          {
590             return 0;
591          }
592      
593          /* Else, set wildcard mode and remember position after '*' */
594          wildcard = 1;
595          fallback = pat;
596       }
597
598       /* Character range specification? */
599       if (*pat == '[')
600       {
601          memset(charmap, '\0', sizeof(charmap));
602
603          while (*++pat != ']')
604          {
605             if (!*pat)
606             { 
607                return 1;
608             }
609             else if (*pat == '-')
610             {
611                if ((*++pat == ']') || *pat == '\0')
612                {
613                   return(1);
614                }
615                for(i = lastchar; i <= *pat; i++)
616                {
617                   charmap[i / 8] |= (1 << (i % 8));
618                } 
619             }
620             else
621             {
622                charmap[*pat / 8] |= (1 << (*pat % 8));
623                lastchar = *pat;
624             }
625          }
626       } /* -END- if Character range specification */
627
628
629       /* Compare: Char match, or char range match*/
630       if ((*pat == *txt)  
631       || ((*pat == ']') && (charmap[*txt / 8] & (1 << (*txt % 8)))) )
632       {
633          /* Sucess, go ahead */
634          pat++;
635       }
636       else
637       {
638          /* In wildcard mode, just try again after failiure */
639          if(wildcard)
640          {
641             pat = fallback;
642          }
643
644          /* Else, bad luck */
645          else
646          {
647             return 1;
648          }
649       }
650       txt++;
651    }
652
653    /* Cut off extra '*'s */
654    if(*pat == '*')  pat++;
655
656    /* If this is the pattern's end, fine! */
657    return(*pat);
658
659 }
660
661
662 /*********************************************************************
663  *
664  * Function    :  bindup
665  *
666  * Description :  Duplicate the first n characters of a string that may
667  *                contain '\0' characters.
668  *
669  * Parameters  :
670  *          1  :  string = string to be duplicated
671  *          2  :  n = number of bytes to duplicate
672  *
673  * Returns     :  pointer to copy, or NULL if failiure
674  *
675  *********************************************************************/
676 char *bindup(const char *string, int n)
677 {
678    char *dup;
679
680    if (NULL == (dup = (char *)malloc(n)))
681    {
682       return NULL;
683    }
684    else
685    {
686      memcpy(dup, string, n);
687    }
688
689    return dup;
690
691 }
692
693
694 /*********************************************************************
695  *
696  * Function    :  make_path
697  *
698  * Description :  Takes a directory name and a file name, returns 
699  *                the complete path.  Handles windows/unix differences.
700  *                If the file name is already an absolute path, or if
701  *                the directory name is NULL or empty, it returns 
702  *                the filename. 
703  *
704  * Parameters  :
705  *          1  :  dir: Name of directory or NULL for none.
706  *          2  :  file: Name of file.  Should not be NULL or empty.
707  *
708  * Returns     :  "dir/file" (Or on windows, "dir\file").
709  *                It allocates the string on the heap.  Caller frees.
710  *                Returns NULL in error (i.e. NULL file or out of
711  *                memory) 
712  *
713  *********************************************************************/
714 char * make_path(const char * dir, const char * file)
715 {
716 #ifdef AMIGA
717    char path[512];
718
719    if(dir)
720    {
721       strncpy(path,dir,512);
722       path[511]=0;
723    } else {
724       path[0]=0;
725    }
726    if(AddPart(path,file,512))
727    {
728       return strdup(path);
729    } else {
730       return NULL;
731    }
732 #else /* ndef AMIGA */
733
734    if ((file == NULL) || (*file == '\0'))
735    {
736       return NULL; /* Error */
737    }
738
739    if ((dir == NULL) || (*dir == '\0') /* No directory specified */
740 #ifdef _WIN32
741       || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
742 #else /* ifndef _WIN32 */
743       || (*file == '/') /* Absolute path (U*ix) */
744 #endif /* ifndef _WIN32 */
745       )
746    {
747       return strdup(file);
748    }
749    else
750    {
751       char * path;
752
753 #if defined(unix)
754       if ( *dir != '/' && basedir && *basedir )
755       {
756               path = malloc( strlen( basedir ) + strlen(dir) + strlen(file) + 3);
757               if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
758               strcpy(path, basedir);
759               strcat(path, "/");
760               strcat(path, dir);
761               DBG(1, ("make_path: path: %s\n",path) );
762       }
763       else
764       {
765               path = malloc(strlen(dir) + strlen(file) + 2);
766               if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
767               strcpy(path, dir);
768       }
769 #else
770
771       path = malloc(strlen(dir) + strlen(file) + 2);
772       if (!path ) log_error(LOG_LEVEL_FATAL, "malloc failed!");
773       strcpy(path, dir);
774
775 #endif /* defined unix */
776
777 #ifdef _WIN32
778       if(path[strlen(path)-1] != '\\')
779       {
780          strcat(path, "\\");
781       }
782 #else /* ifndef _WIN32 */
783       if(path[strlen(path)-1] != '/')
784       {
785          strcat(path, "/");
786       }
787 #endif /* ifndef _WIN32 */
788       strcat(path, file);
789
790       return path;
791    }
792 #endif /* ndef AMIGA */
793 }
794
795
796 /*
797  * What follows is a portable snprintf routine, written by Mark Martinec.
798  * See: http://www.ijs.si/software/snprintf/
799  * Anyone who needs it can add a define for themselves... so far, only 
800  * OS/2 (native) lacks snprintf.
801
802                                   snprintf.c
803                    - a portable implementation of snprintf,
804        including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
805                                        
806    snprintf is a routine to convert numeric and string arguments to
807    formatted strings. It is similar to sprintf(3) provided in a system's
808    C library, yet it requires an additional argument - the buffer size -
809    and it guarantees never to store anything beyond the given buffer,
810    regardless of the format or arguments to be formatted. Some newer
811    operating systems do provide snprintf in their C library, but many do
812    not or do provide an inadequate (slow or idiosyncratic) version, which
813    calls for a portable implementation of this routine.
814
815 Author
816
817    Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
818    Copyright Â© 1999, Mark Martinec
819
820  */
821
822 #ifdef __OS2__
823
824 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
825 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
826
827 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
828 # if defined(NEED_SNPRINTF_ONLY)
829 # undef NEED_SNPRINTF_ONLY
830 # endif
831 # if !defined(PREFER_PORTABLE_SNPRINTF)
832 # define PREFER_PORTABLE_SNPRINTF
833 # endif
834 #endif
835
836 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
837 #define SOLARIS_COMPATIBLE
838 #endif
839
840 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
841 #define HPUX_COMPATIBLE
842 #endif
843
844 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
845 #define DIGITAL_UNIX_COMPATIBLE
846 #endif
847
848 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
849 #define PERL_COMPATIBLE
850 #endif
851
852 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
853 #define LINUX_COMPATIBLE
854 #endif
855
856 #include <sys/types.h>
857 #include <string.h>
858 #include <stdlib.h>
859 #include <stdio.h>
860 #include <stdarg.h>
861 #include <assert.h>
862 #include <errno.h>
863
864 #ifdef isdigit
865 #undef isdigit
866 #endif
867 #define isdigit(c) ((c) >= '0' && (c) <= '9')
868
869 /* For copying strings longer or equal to 'breakeven_point'
870  * it is more efficient to call memcpy() than to do it inline.
871  * The value depends mostly on the processor architecture,
872  * but also on the compiler and its optimization capabilities.
873  * The value is not critical, some small value greater than zero
874  * will be just fine if you don't care to squeeze every drop
875  * of performance out of the code.
876  *
877  * Small values favor memcpy, large values favor inline code.
878  */
879 #if defined(__alpha__) || defined(__alpha)
880 #  define breakeven_point   2   /* AXP (DEC Alpha)     - gcc or cc or egcs */
881 #endif
882 #if defined(__i386__)  || defined(__i386)
883 #  define breakeven_point  12   /* Intel Pentium/Linux - gcc 2.96 */
884 #endif
885 #if defined(__hppa)
886 #  define breakeven_point  10   /* HP-PA               - gcc */
887 #endif
888 #if defined(__sparc__) || defined(__sparc)
889 #  define breakeven_point  33   /* Sun Sparc 5         - gcc 2.8.1 */
890 #endif
891
892 /* some other values of possible interest: */
893 /* #define breakeven_point  8 */  /* VAX 4000          - vaxc */
894 /* #define breakeven_point 19 */  /* VAX 4000          - gcc 2.7.0 */
895
896 #ifndef breakeven_point
897 #  define breakeven_point   6   /* some reasonable one-size-fits-all value */
898 #endif
899
900 #define fast_memcpy(d,s,n) \
901   { register size_t nn = (size_t)(n); \
902     if (nn >= breakeven_point) memcpy((d), (s), nn); \
903     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
904       register char *dd; register const char *ss; \
905       for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
906
907 #define fast_memset(d,c,n) \
908   { register size_t nn = (size_t)(n); \
909     if (nn >= breakeven_point) memset((d), (int)(c), nn); \
910     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
911       register char *dd; register const int cc=(int)(c); \
912       for (dd=(d); nn>0; nn--) *dd++ = cc; } }
913
914 /* prototypes */
915
916 #if defined(NEED_ASPRINTF)
917 int asprintf   (char **ptr, const char *fmt, /*args*/ ...);
918 #endif
919 #if defined(NEED_VASPRINTF)
920 int vasprintf  (char **ptr, const char *fmt, va_list ap);
921 #endif
922 #if defined(NEED_ASNPRINTF)
923 int asnprintf  (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
924 #endif
925 #if defined(NEED_VASNPRINTF)
926 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
927 #endif
928
929 #if defined(HAVE_SNPRINTF)
930 /* declare our portable snprintf  routine under name portable_snprintf  */
931 /* declare our portable vsnprintf routine under name portable_vsnprintf */
932 #else
933 /* declare our portable routines under names snprintf and vsnprintf */
934 #define portable_snprintf snprintf
935 #if !defined(NEED_SNPRINTF_ONLY)
936 #define portable_vsnprintf vsnprintf
937 #endif
938 #endif
939
940 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
941 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
942 #if !defined(NEED_SNPRINTF_ONLY)
943 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
944 #endif
945 #endif
946
947 /* declarations */
948
949 static char credits[] = "\n\
950 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
951 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
952 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
953
954 #if defined(NEED_ASPRINTF)
955 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
956   va_list ap;
957   size_t str_m;
958   int str_l;
959
960   *ptr = NULL;
961   va_start(ap, fmt);                            /* measure the required size */
962   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
963   va_end(ap);
964   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
965   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
966   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
967   else {
968     int str_l2;
969     va_start(ap, fmt);
970     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
971     va_end(ap);
972     assert(str_l2 == str_l);
973   }
974   return str_l;
975 }
976 #endif
977
978 #if defined(NEED_VASPRINTF)
979 int vasprintf(char **ptr, const char *fmt, va_list ap) {
980   size_t str_m;
981   int str_l;
982
983   *ptr = NULL;
984   { va_list ap2;
985     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
986     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
987     va_end(ap2);
988   }
989   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
990   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
991   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
992   else {
993     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
994     assert(str_l2 == str_l);
995   }
996   return str_l;
997 }
998 #endif
999
1000 #if defined(NEED_ASNPRINTF)
1001 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1002   va_list ap;
1003   int str_l;
1004
1005   *ptr = NULL;
1006   va_start(ap, fmt);                            /* measure the required size */
1007   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1008   va_end(ap);
1009   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1010   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1011   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1012   if (str_m == 0) {  /* not interested in resulting string, just return size */
1013   } else {
1014     *ptr = (char *) malloc(str_m);
1015     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1016     else {
1017       int str_l2;
1018       va_start(ap, fmt);
1019       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1020       va_end(ap);
1021       assert(str_l2 == str_l);
1022     }
1023   }
1024   return str_l;
1025 }
1026 #endif
1027
1028 #if defined(NEED_VASNPRINTF)
1029 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1030   int str_l;
1031
1032   *ptr = NULL;
1033   { va_list ap2;
1034     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
1035     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1036     va_end(ap2);
1037   }
1038   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
1039   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
1040   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1041   if (str_m == 0) {  /* not interested in resulting string, just return size */
1042   } else {
1043     *ptr = (char *) malloc(str_m);
1044     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1045     else {
1046       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1047       assert(str_l2 == str_l);
1048     }
1049   }
1050   return str_l;
1051 }
1052 #endif
1053
1054 /*
1055  * If the system does have snprintf and the portable routine is not
1056  * specifically required, this module produces no code for snprintf/vsnprintf.
1057  */
1058 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1059
1060 #if !defined(NEED_SNPRINTF_ONLY)
1061 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1062   va_list ap;
1063   int str_l;
1064
1065   va_start(ap, fmt);
1066   str_l = portable_vsnprintf(str, str_m, fmt, ap);
1067   va_end(ap);
1068   return str_l;
1069 }
1070 #endif
1071
1072 #if defined(NEED_SNPRINTF_ONLY)
1073 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1074 #else
1075 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1076 #endif
1077
1078 #if defined(NEED_SNPRINTF_ONLY)
1079   va_list ap;
1080 #endif
1081   size_t str_l = 0;
1082   const char *p = fmt;
1083
1084 /* In contrast with POSIX, the ISO C99 now says
1085  * that str can be NULL and str_m can be 0.
1086  * This is more useful than the old:  if (str_m < 1) return -1; */
1087
1088 #if defined(NEED_SNPRINTF_ONLY)
1089   va_start(ap, fmt);
1090 #endif
1091   if (!p) p = "";
1092   while (*p) {
1093     if (*p != '%') {
1094    /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
1095    /* but the following code achieves better performance for cases
1096     * where format string is long and contains few conversions */
1097       const char *q = strchr(p+1,'%');
1098       size_t n = !q ? strlen(p) : (q-p);
1099       if (str_l < str_m) {
1100         size_t avail = str_m-str_l;
1101         fast_memcpy(str+str_l, p, (n>avail?avail:n));
1102       }
1103       p += n; str_l += n;
1104     } else {
1105       const char *starting_p;
1106       size_t min_field_width = 0, precision = 0;
1107       int zero_padding = 0, precision_specified = 0, justify_left = 0;
1108       int alternate_form = 0, force_sign = 0;
1109       int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1110                                      the ' ' flag should be ignored. */
1111       char length_modifier = '\0';            /* allowed values: \0, h, l, L */
1112       char tmp[32];/* temporary buffer for simple numeric->string conversion */
1113
1114       const char *str_arg;      /* string address in case of string argument */
1115       size_t str_arg_l;         /* natural field width of arg without padding
1116                                    and sign */
1117       unsigned char uchar_arg;
1118         /* unsigned char argument value - only defined for c conversion.
1119            N.B. standard explicitly states the char argument for
1120            the c conversion is unsigned */
1121
1122       size_t number_of_zeros_to_pad = 0;
1123         /* number of zeros to be inserted for numeric conversions
1124            as required by the precision or minimal field width */
1125
1126       size_t zero_padding_insertion_ind = 0;
1127         /* index into tmp where zero padding is to be inserted */
1128
1129       char fmt_spec = '\0';
1130         /* current conversion specifier character */
1131
1132       str_arg = credits;/* just to make compiler happy (defined but not used)*/
1133       str_arg = NULL;
1134       starting_p = p; p++;  /* skip '%' */
1135    /* parse flags */
1136       while (*p == '0' || *p == '-' || *p == '+' ||
1137              *p == ' ' || *p == '#' || *p == '\'') {
1138         switch (*p) {
1139         case '0': zero_padding = 1; break;
1140         case '-': justify_left = 1; break;
1141         case '+': force_sign = 1; space_for_positive = 0; break;
1142         case ' ': force_sign = 1;
1143      /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1144 #ifdef PERL_COMPATIBLE
1145      /* ... but in Perl the last of ' ' and '+' applies */
1146                   space_for_positive = 1;
1147 #endif
1148                   break;
1149         case '#': alternate_form = 1; break;
1150         case '\'': break;
1151         }
1152         p++;
1153       }
1154    /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1155
1156    /* parse field width */
1157       if (*p == '*') {
1158         int j;
1159         p++; j = va_arg(ap, int);
1160         if (j >= 0) min_field_width = j;
1161         else { min_field_width = -j; justify_left = 1; }
1162       } else if (isdigit((int)(*p))) {
1163         /* size_t could be wider than unsigned int;
1164            make sure we treat argument like common implementations do */
1165         unsigned int uj = *p++ - '0';
1166         while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1167         min_field_width = uj;
1168       }
1169    /* parse precision */
1170       if (*p == '.') {
1171         p++; precision_specified = 1;
1172         if (*p == '*') {
1173           int j = va_arg(ap, int);
1174           p++;
1175           if (j >= 0) precision = j;
1176           else {
1177             precision_specified = 0; precision = 0;
1178          /* NOTE:
1179           *   Solaris 2.6 man page claims that in this case the precision
1180           *   should be set to 0.  Digital Unix 4.0, HPUX 10 and BSD man page
1181           *   claim that this case should be treated as unspecified precision,
1182           *   which is what we do here.
1183           */
1184           }
1185         } else if (isdigit((int)(*p))) {
1186           /* size_t could be wider than unsigned int;
1187              make sure we treat argument like common implementations do */
1188           unsigned int uj = *p++ - '0';
1189           while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1190           precision = uj;
1191         }
1192       }
1193    /* parse 'h', 'l' and 'll' length modifiers */
1194       if (*p == 'h' || *p == 'l') {
1195         length_modifier = *p; p++;
1196         if (length_modifier == 'l' && *p == 'l') {   /* double l = long long */
1197 #ifdef SNPRINTF_LONGLONG_SUPPORT
1198           length_modifier = '2';                  /* double l encoded as '2' */
1199 #else
1200           length_modifier = 'l';                 /* treat it as a single 'l' */
1201 #endif
1202           p++;
1203         }
1204       }
1205       fmt_spec = *p;
1206    /* common synonyms: */
1207       switch (fmt_spec) {
1208       case 'i': fmt_spec = 'd'; break;
1209       case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1210       case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1211       case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1212       default: break;
1213       }
1214    /* get parameter value, do initial processing */
1215       switch (fmt_spec) {
1216       case '%': /* % behaves similar to 's' regarding flags and field widths */
1217       case 'c': /* c behaves similar to 's' regarding flags and field widths */
1218       case 's':
1219         length_modifier = '\0';          /* wint_t and wchar_t not supported */
1220      /* the result of zero padding flag with non-numeric conversion specifier*/
1221      /* is undefined. Solaris and HPUX 10 does zero padding in this case,    */
1222      /* Digital Unix and Linux does not. */
1223 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1224         zero_padding = 0;    /* turn zero padding off for string conversions */
1225 #endif
1226         str_arg_l = 1;
1227         switch (fmt_spec) {
1228         case '%':
1229           str_arg = p; break;
1230         case 'c': {
1231           int j = va_arg(ap, int);
1232           uchar_arg = (unsigned char) j;   /* standard demands unsigned char */
1233           str_arg = (const char *) &uchar_arg;
1234           break;
1235         }
1236         case 's':
1237           str_arg = va_arg(ap, const char *);
1238           if (!str_arg) str_arg_l = 0;
1239        /* make sure not to address string beyond the specified precision !!! */
1240           else if (!precision_specified) str_arg_l = strlen(str_arg);
1241        /* truncate string if necessary as requested by precision */
1242           else if (precision == 0) str_arg_l = 0;
1243           else {
1244        /* memchr on HP does not like n > 2^31  !!! */
1245             const char *q = memchr(str_arg, '\0',
1246                              precision <= 0x7fffffff ? precision : 0x7fffffff);
1247             str_arg_l = !q ? precision : (q-str_arg);
1248           }
1249           break;
1250         default: break;
1251         }
1252         break;
1253       case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1254         /* NOTE: the u, o, x, X and p conversion specifiers imply
1255                  the value is unsigned;  d implies a signed value */
1256
1257         int arg_sign = 0;
1258           /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1259             +1 if greater than zero (or nonzero for unsigned arguments),
1260             -1 if negative (unsigned argument is never negative) */
1261
1262         int int_arg = 0;  unsigned int uint_arg = 0;
1263           /* only defined for length modifier h, or for no length modifiers */
1264
1265         long int long_arg = 0;  unsigned long int ulong_arg = 0;
1266           /* only defined for length modifier l */
1267
1268         void *ptr_arg = NULL;
1269           /* pointer argument value -only defined for p conversion */
1270
1271 #ifdef SNPRINTF_LONGLONG_SUPPORT
1272         long long int long_long_arg = 0;
1273         unsigned long long int ulong_long_arg = 0;
1274           /* only defined for length modifier ll */
1275 #endif
1276         if (fmt_spec == 'p') {
1277         /* HPUX 10: An l, h, ll or L before any other conversion character
1278          *   (other than d, i, u, o, x, or X) is ignored.
1279          * Digital Unix:
1280          *   not specified, but seems to behave as HPUX does.
1281          * Solaris: If an h, l, or L appears before any other conversion
1282          *   specifier (other than d, i, u, o, x, or X), the behavior
1283          *   is undefined. (Actually %hp converts only 16-bits of address
1284          *   and %llp treats address as 64-bit data which is incompatible
1285          *   with (void *) argument on a 32-bit system).
1286          */
1287 #ifdef SOLARIS_COMPATIBLE
1288 #  ifdef SOLARIS_BUG_COMPATIBLE
1289           /* keep length modifiers even if it represents 'll' */
1290 #  else
1291           if (length_modifier == '2') length_modifier = '\0';
1292 #  endif
1293 #else
1294           length_modifier = '\0';
1295 #endif
1296           ptr_arg = va_arg(ap, void *);
1297           if (ptr_arg != NULL) arg_sign = 1;
1298         } else if (fmt_spec == 'd') {  /* signed */
1299           switch (length_modifier) {
1300           case '\0':
1301           case 'h':
1302          /* It is non-portable to specify a second argument of char or short
1303           * to va_arg, because arguments seen by the called function
1304           * are not char or short.  C converts char and short arguments
1305           * to int before passing them to a function.
1306           */
1307             int_arg = va_arg(ap, int);
1308             if      (int_arg > 0) arg_sign =  1;
1309             else if (int_arg < 0) arg_sign = -1;
1310             break;
1311           case 'l':
1312             long_arg = va_arg(ap, long int);
1313             if      (long_arg > 0) arg_sign =  1;
1314             else if (long_arg < 0) arg_sign = -1;
1315             break;
1316 #ifdef SNPRINTF_LONGLONG_SUPPORT
1317           case '2':
1318             long_long_arg = va_arg(ap, long long int);
1319             if      (long_long_arg > 0) arg_sign =  1;
1320             else if (long_long_arg < 0) arg_sign = -1;
1321             break;
1322 #endif
1323           }
1324         } else {  /* unsigned */
1325           switch (length_modifier) {
1326           case '\0':
1327           case 'h':
1328             uint_arg = va_arg(ap, unsigned int);
1329             if (uint_arg) arg_sign = 1;
1330             break;
1331           case 'l':
1332             ulong_arg = va_arg(ap, unsigned long int);
1333             if (ulong_arg) arg_sign = 1;
1334             break;
1335 #ifdef SNPRINTF_LONGLONG_SUPPORT
1336           case '2':
1337             ulong_long_arg = va_arg(ap, unsigned long long int);
1338             if (ulong_long_arg) arg_sign = 1;
1339             break;
1340 #endif
1341           }
1342         }
1343         str_arg = tmp; str_arg_l = 0;
1344      /* NOTE:
1345       *   For d, i, u, o, x, and X conversions, if precision is specified,
1346       *   the '0' flag should be ignored. This is so with Solaris 2.6,
1347       *   Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1348       */
1349 #ifndef PERL_COMPATIBLE
1350         if (precision_specified) zero_padding = 0;
1351 #endif
1352         if (fmt_spec == 'd') {
1353           if (force_sign && arg_sign >= 0)
1354             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1355          /* leave negative numbers for sprintf to handle,
1356             to avoid handling tricky cases like (short int)(-32768) */
1357 #ifdef LINUX_COMPATIBLE
1358         } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1359           tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1360 #endif
1361         } else if (alternate_form) {
1362           if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1363             { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1364          /* alternate form should have no effect for p conversion, but ... */
1365 #ifdef HPUX_COMPATIBLE
1366           else if (fmt_spec == 'p'
1367          /* HPUX 10: for an alternate form of p conversion,
1368           *          a nonzero result is prefixed by 0x. */
1369 #ifndef HPUX_BUG_COMPATIBLE
1370          /* Actually it uses 0x prefix even for a zero value. */
1371                    && arg_sign != 0
1372 #endif
1373                   ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1374 #endif
1375         }
1376         zero_padding_insertion_ind = str_arg_l;
1377         if (!precision_specified) precision = 1;   /* default precision is 1 */
1378         if (precision == 0 && arg_sign == 0
1379 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1380             && fmt_spec != 'p'
1381          /* HPUX 10 man page claims: With conversion character p the result of
1382           * converting a zero value with a precision of zero is a null string.
1383           * Actually HP returns all zeroes, and Linux returns "(nil)". */
1384 #endif
1385         ) {
1386          /* converted to null string */
1387          /* When zero value is formatted with an explicit precision 0,
1388             the resulting formatted string is empty (d, i, u, o, x, X, p).   */
1389         } else {
1390           char f[5]; int f_l = 0;
1391           f[f_l++] = '%';    /* construct a simple format string for sprintf */
1392           if (!length_modifier) { }
1393           else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1394           else f[f_l++] = length_modifier;
1395           f[f_l++] = fmt_spec; f[f_l++] = '\0';
1396           if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1397           else if (fmt_spec == 'd') {  /* signed */
1398             switch (length_modifier) {
1399             case '\0':
1400             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
1401             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1402 #ifdef SNPRINTF_LONGLONG_SUPPORT
1403             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1404 #endif
1405             }
1406           } else {  /* unsigned */
1407             switch (length_modifier) {
1408             case '\0':
1409             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg);  break;
1410             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1411 #ifdef SNPRINTF_LONGLONG_SUPPORT
1412             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1413 #endif
1414             }
1415           }
1416          /* include the optional minus sign and possible "0x"
1417             in the region before the zero padding insertion point */
1418           if (zero_padding_insertion_ind < str_arg_l &&
1419               tmp[zero_padding_insertion_ind] == '-') {
1420             zero_padding_insertion_ind++;
1421           }
1422           if (zero_padding_insertion_ind+1 < str_arg_l &&
1423               tmp[zero_padding_insertion_ind]   == '0' &&
1424              (tmp[zero_padding_insertion_ind+1] == 'x' ||
1425               tmp[zero_padding_insertion_ind+1] == 'X') ) {
1426             zero_padding_insertion_ind += 2;
1427           }
1428         }
1429         { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1430           if (alternate_form && fmt_spec == 'o'
1431 #ifdef HPUX_COMPATIBLE                                  /* ("%#.o",0) -> ""  */
1432               && (str_arg_l > 0)
1433 #endif
1434 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE                      /* ("%#o",0) -> "00" */
1435 #else
1436               /* unless zero is already the first character */
1437               && !(zero_padding_insertion_ind < str_arg_l
1438                    && tmp[zero_padding_insertion_ind] == '0')
1439 #endif
1440           ) {        /* assure leading zero for alternate-form octal numbers */
1441             if (!precision_specified || precision < num_of_digits+1) {
1442              /* precision is increased to force the first character to be zero,
1443                 except if a zero value is formatted with an explicit precision
1444                 of zero */
1445               precision = num_of_digits+1; precision_specified = 1;
1446             }
1447           }
1448        /* zero padding to specified precision? */
1449           if (num_of_digits < precision) 
1450             number_of_zeros_to_pad = precision - num_of_digits;
1451         }
1452      /* zero padding to specified minimal field width? */
1453         if (!justify_left && zero_padding) {
1454           int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1455           if (n > 0) number_of_zeros_to_pad += n;
1456         }
1457         break;
1458       }
1459       default: /* unrecognized conversion specifier, keep format string as-is*/
1460         zero_padding = 0;  /* turn zero padding off for non-numeric convers. */
1461 #ifndef DIGITAL_UNIX_COMPATIBLE
1462         justify_left = 1; min_field_width = 0;                /* reset flags */
1463 #endif
1464 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1465      /* keep the entire format string unchanged */
1466         str_arg = starting_p; str_arg_l = p - starting_p;
1467      /* well, not exactly so for Linux, which does something inbetween,
1468       * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y"  */
1469 #else
1470      /* discard the unrecognized conversion, just keep *
1471       * the unrecognized conversion character          */
1472         str_arg = p; str_arg_l = 0;
1473 #endif
1474         if (*p) str_arg_l++;  /* include invalid conversion specifier unchanged
1475                                  if not at end-of-string */
1476         break;
1477       }
1478       if (*p) p++;      /* step over the just processed conversion specifier */
1479    /* insert padding to the left as requested by min_field_width;
1480       this does not include the zero padding in case of numerical conversions*/
1481       if (!justify_left) {                /* left padding with blank or zero */
1482         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1483         if (n > 0) {
1484           if (str_l < str_m) {
1485             size_t avail = str_m-str_l;
1486             fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1487           }
1488           str_l += n;
1489         }
1490       }
1491    /* zero padding as requested by the precision or by the minimal field width
1492     * for numeric conversions required? */
1493       if (number_of_zeros_to_pad <= 0) {
1494      /* will not copy first part of numeric right now, *
1495       * force it to be copied later in its entirety    */
1496         zero_padding_insertion_ind = 0;
1497       } else {
1498      /* insert first part of numerics (sign or '0x') before zero padding */
1499         int n = zero_padding_insertion_ind;
1500         if (n > 0) {
1501           if (str_l < str_m) {
1502             size_t avail = str_m-str_l;
1503             fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1504           }
1505           str_l += n;
1506         }
1507      /* insert zero padding as requested by the precision or min field width */
1508         n = number_of_zeros_to_pad;
1509         if (n > 0) {
1510           if (str_l < str_m) {
1511             size_t avail = str_m-str_l;
1512             fast_memset(str+str_l, '0', (n>avail?avail:n));
1513           }
1514           str_l += n;
1515         }
1516       }
1517    /* insert formatted string
1518     * (or as-is conversion specifier for unknown conversions) */
1519       { int n = str_arg_l - zero_padding_insertion_ind;
1520         if (n > 0) {
1521           if (str_l < str_m) {
1522             size_t avail = str_m-str_l;
1523             fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1524                         (n>avail?avail:n));
1525           }
1526           str_l += n;
1527         }
1528       }
1529    /* insert right padding */
1530       if (justify_left) {          /* right blank padding to the field width */
1531         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1532         if (n > 0) {
1533           if (str_l < str_m) {
1534             size_t avail = str_m-str_l;
1535             fast_memset(str+str_l, ' ', (n>avail?avail:n));
1536           }
1537           str_l += n;
1538         }
1539       }
1540     }
1541   }
1542 #if defined(NEED_SNPRINTF_ONLY)
1543   va_end(ap);
1544 #endif
1545   if (str_m > 0) { /* make sure the string is null-terminated
1546                       even at the expense of overwriting the last character
1547                       (shouldn't happen, but just in case) */
1548     str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1549   }
1550   /* Return the number of characters formatted (excluding trailing null
1551    * character), that is, the number of characters that would have been
1552    * written to the buffer if it were large enough.
1553    *
1554    * The value of str_l should be returned, but str_l is of unsigned type
1555    * size_t, and snprintf is int, possibly leading to an undetected
1556    * integer overflow, resulting in a negative return value, which is illegal.
1557    * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1558    * Should errno be set to EOVERFLOW and EOF returned in this case???
1559    */
1560   return (int) str_l;
1561 }
1562 #endif
1563 #endif /* __OS2__ */
1564 /*
1565   Local Variables:
1566   tab-width: 3
1567   end:
1568 */