BugID:23251508: lwip_itoa: check 'bufsize' instead of ignoring it; ensure code is not stolen from GPL
commit
Author: goldsimon
Date:   Thu Apr 20 21:57:03 2017 +0200
@@ -198,26 +198,48 @@ lwip_strnicmp(const char* str1, const char* str2, size_t len)
void
lwip_itoa(char* result, size_t bufsize, int number)
{
- const int base = 10;
- char* ptr = result, *ptr1 = result, tmp_char;
- int tmp_value;
- LWIP_UNUSED_ARG(bufsize);
+ char *res = result;
+ char *tmp = result;
+ size_t res_left = bufsize;
+ size_t result_len;
+ int n = (number > 0) ? number : -number;
+
+ /* handle invalid bufsize */
+ if (bufsize < 2) {
+ if (bufsize == 1) {
+ *result = 0;
+ }
+ return;
+ }
+
+ /* ensure output string is zero terminated */
+ result[bufsize-1] = 0;
+ result_len = 1;
+ /* create the string in a temporary buffer since we don't know how long
+ it will get */
+ tmp = &result[bufsize-2];
+ while ((n != 0) && (result_len < (result_len - 1))) {
+ char val = '0' + (n % 10);
+ *tmp = val;
+ tmp--;
+ n = n / 10;
+ result_len++;
+ }
+
+ /* output sign first */
+ if (number < 0) {
+ *res = '-';
+ res++;
+ res_left--;
+ }
+ if (result_len > res_left) {
+ /* buffer is too small */
+ result[0] = '.';
+ result[1] = 0;
+ return;
+ }
+ /* copy from temporary buffer to output buffer */
+ memmove(res, tmp+1, result_len);
- do {
- tmp_value = number;
- number /= base;
- *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35 + (tmp_value - number * base)];
- } while(number);
-
- /* Apply negative sign */
- if (tmp_value < 0) {
- *ptr++ = '-';
- }
- *ptr-- = '\0';
- while(ptr1 < ptr) {
- tmp_char = *ptr;
- *ptr--= *ptr1;
- *ptr1++ = tmp_char;
- }
}
#endif
