| 28 | */ |
| 29 | __rte_format_printf(3, 4) |
| 30 | static inline int |
| 31 | __json_snprintf(char *buf, const int len, const char *format, ...) |
| 32 | { |
| 33 | va_list ap; |
| 34 | char tmp[4]; |
| 35 | char *newbuf; |
| 36 | int ret; |
| 37 | |
| 38 | if (len == 0) |
| 39 | return 0; |
| 40 | |
| 41 | /* to ensure unmodified if we overflow, we save off any values currently in buf |
| 42 | * before we printf, if they are short enough. We restore them on error. |
| 43 | */ |
| 44 | if (strnlen(buf, sizeof(tmp)) < sizeof(tmp)) { |
| 45 | strcpy(tmp, buf); /* strcpy is safe as we know the length */ |
| 46 | va_start(ap, format); |
| 47 | ret = vsnprintf(buf, len, format, ap); |
| 48 | va_end(ap); |
| 49 | if (ret > 0 && ret < len) |
| 50 | return ret; |
| 51 | strcpy(buf, tmp); /* restore on error */ |
| 52 | return 0; |
| 53 | } |
| 54 | |
| 55 | /* in normal operations should never hit this, but can do if buffer is |
| 56 | * incorrectly initialized e.g. in unit test cases |
| 57 | */ |
| 58 | newbuf = malloc(len); |
| 59 | if (newbuf == NULL) |
| 60 | return 0; |
| 61 | |
| 62 | va_start(ap, format); |
| 63 | ret = vsnprintf(newbuf, len, format, ap); |
| 64 | va_end(ap); |
| 65 | if (ret > 0 && ret < len) { |
| 66 | strcpy(buf, newbuf); |
| 67 | free(newbuf); |
| 68 | return ret; |
| 69 | } |
| 70 | free(newbuf); |
| 71 | return 0; /* nothing written or modified */ |
| 72 | } |
| 73 | |
| 74 | static const char control_chars[0x20] = { |
| 75 | ['\n'] = 'n', |
no test coverage detected