X-Git-Url: http://nsz.repo.hu/git/?a=blobdiff_plain;f=ir%2Fobstack%2Fobstack_printf.c;h=a270fea800623ff41b1866675aab28eb135fca10;hb=b9a8e2e9a91905899d4b11d31105b8303d1ce81d;hp=1b432e2ec53d424c3b88a1ebed7989406adaef8e;hpb=8dc2105e636a5d40655bf7701b90bd2af68f9a19;p=libfirm diff --git a/ir/obstack/obstack_printf.c b/ir/obstack/obstack_printf.c index 1b432e2ec..a270fea80 100644 --- a/ir/obstack/obstack_printf.c +++ b/ir/obstack/obstack_printf.c @@ -1,50 +1,68 @@ +#include #include #include #include +#include #include "obstack.h" #ifdef _WIN32 -#define vsnprintf _vsnprintf +/* win32/C89 has no va_copy function... so we have to use the stupid fixed-length version */ +int obstack_vprintf(struct obstack *obst, const char *fmt, va_list ap) FIRM_NOTHROW +{ + char buf[16384]; + int len = _vsnprintf(buf, sizeof(buf), fmt, ap); + obstack_grow(obst, buf, len); + return len; +} +#else +int obstack_vprintf(struct obstack *obst, const char *fmt, va_list ap) FIRM_NOTHROW +{ + char buf[128]; + char *buffer = buf; + size_t size = sizeof(buf); + int len; + + for (;;) { + va_list tap; + va_copy(tap, ap); + len = vsnprintf(buffer, size, fmt, tap); + + /* snprintf should return -1 only in the error case, but older glibcs + * and probably other systems are buggy in this respect and return -1 if + * the buffer was too small. We only abort for LARGE unrealistic buffer + * sizes here */ + if (len < 0) { + if (buffer != buf) + free(buffer); + if (size > 65536) + return -1; + size *= 2; + } else if ((size_t)len >= size) { + /* If we come here more than once, vsnprintf() returned garbage */ + assert(buffer == buf); + size = (size_t)len + 1; + } else { + break; + } + buffer = (char*)malloc(size); + } + + obstack_grow(obst, buffer, len); + if (buffer != buf) + free(buffer); + + return len; +} #endif -int obstack_printf(struct obstack *obst, const char *fmt, ...) +int obstack_printf(struct obstack *obst, const char *fmt, ...) FIRM_NOTHROW { - char buf[128]; - char *buffer = buf; va_list ap; - int len; + int res; va_start(ap, fmt); - len = vsnprintf(buffer, sizeof(buffer), fmt, ap); + res = obstack_vprintf(obst, fmt, ap); va_end(ap); - if (len < 0 || len >= (int) sizeof(buffer)) { - size_t size = len >= 0 ? (size_t) len : sizeof(buffer) * 2; - char *buffer = malloc(size); - do { - if (buffer == NULL) - return -1; - va_start(ap, fmt); - len = vsnprintf(buffer, size, fmt, ap); - va_end(ap); - - /* snprintf should return -1 only in the error case, but older - * glibcs and probably other systems are buggy in this respect and - * return -1 if the buffer was too small. We only abort for LARGE - * unrealistic buffer sizes here */ - if (len < 0) { - if (size > 65536) - return -1; - size *= 2; - buffer = realloc(buffer, size); - } else if (len >= (int) size) { - /* this should not happen if snprintf works correctly */ - abort(); - } - } while (len < 0); - free(buffer); - } - obstack_grow(obst, buffer, len); - - return len; + return res; }