Skip to content

Commit

Permalink
remove snprintf/strncat/strlen from fp_ident
Browse files Browse the repository at this point in the history
fp_ident is the only place tomsfast math uses string manipulation
functions when built as a library. This commit replaces them with
safe, trivial functions for concatonating static strings and numbers
together.
  • Loading branch information
ryancdotorg authored and sjaeckel committed Sep 21, 2024
1 parent 5602f64 commit 537ba3e
Showing 1 changed file with 56 additions and 9 deletions.
65 changes: 56 additions & 9 deletions src/misc/fp_ident.c
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,65 @@
#define GIT_VERSION TFM_VERSION_S
#endif

#define dnstrcon(D, N, S) dnmemcpy((D), (N), S, sizeof(S)-1)
static signed long dnmemcpy(char **d, size_t *n, const char *s, size_t len) {
if (len >= *n) return -1;
memcpy(*d, s, len);
*n -= len;
*d += len;
**d = '\0';
return len;
}

/* log(2)/log(10) ~= 0.30102999... ~= 30103 / 100000
* we need to add one byte because this rounds to zero, and one for sign
* these provide exact answer for integers up to 4720 bytes wide... */
#define U_DIGITS(T) (1 + ((sizeof(T) * 8UL) * 30103UL) / 100000UL)
#define S_DIGITS(T) (2 + ((sizeof(T) * 8UL - 1) * 30103UL) / 100000UL)

static signed long dnstrul(char **d, size_t *n, unsigned long value) {
char digits[U_DIGITS(unsigned long)+1]; /* fit digits plus null byte */
char *digit = digits + (sizeof(digits) - 1);
size_t len = 0;
*digit = '\0';
do {
*--digit = '0' + (value % 10);
value /= 10;
++len;
if (digit < digits) return -1;
} while (value);
if (len >= *n) return -1;
return dnmemcpy(d, n, digit, len);
}

const char *fp_ident(void)
{
static char buf[1024];
char *d = buf;
size_t n = sizeof(buf);

memset(buf, 0, sizeof(buf));
snprintf(buf, sizeof(buf)-1,
dnstrcon(&d, &n,
"TomsFastMath " GIT_VERSION "\n"
#if defined(TFM_IDENT_BUILD_DATE)
"Built on " __DATE__ " at " __TIME__ "\n"
#endif
"\n"
"Sizeofs\n"
"\tfp_digit = %lu\n"
"\tfp_word = %lu\n"
"\n"
"FP_MAX_SIZE = %u\n"
"\tfp_digit = "
);
dnstrul(&d, &n, sizeof(fp_digit));
dnstrcon(&d, &n,
"\n"
"\tfp_word = "
);
dnstrul(&d, &n, sizeof(fp_word));
dnstrcon(&d, &n,
"\n\n"
"FP_MAX_SIZE = "
);
dnstrul(&d, &n, FP_MAX_SIZE);
dnstrcon(&d, &n,
"\n\n"
"Defines: \n"
#ifdef __i386__
" __i386__ "
Expand Down Expand Up @@ -70,12 +112,17 @@ const char *fp_ident(void)
#ifdef TFM_HUGE
" TFM_HUGE "
#endif
"\n", (unsigned long)sizeof(fp_digit), (unsigned long)sizeof(fp_word), FP_MAX_SIZE);
"\n"
);

if (sizeof(fp_digit) == sizeof(fp_word)) {
strncat(buf, "WARNING: sizeof(fp_digit) == sizeof(fp_word), this build is likely to not work properly.\n",
sizeof(buf) - strlen(buf) - 1);
dnstrcon(&d, &n,
"WARNING: sizeof(fp_digit) == sizeof(fp_word),"
" this build is likely to not work properly.\n"
);
}

memset(d, 0, n);
return buf;
}

Expand Down

0 comments on commit 537ba3e

Please sign in to comment.