mirror of
https://github.com/libratbag/libratbag.git
synced 2026-11-08 07:33:53 +01:00
Add snprintf_safe() and sprintf_safe helpers
Blows up when sprintf encounters an error, the result string is empty or the result string is truncated. Note: sprintf_safe only works on static buffers, it uses ARRAY_LENGTH. Fixes #14 Signed-off-by: Peter Hutterer <peter.hutterer@who-t.net>
This commit is contained in:
@@ -63,7 +63,7 @@ hidpp20_feature_get_name(uint16_t feature)
|
||||
CASE_RETURN_STRING(HIDPP_PAGE_ONBOARD_PROFILES);
|
||||
CASE_RETURN_STRING(HIDPP_PAGE_MOUSE_BUTTON_SPY);
|
||||
default:
|
||||
sprintf(numeric, "%#4x", feature);
|
||||
sprintf_safe(numeric, "%#4x", feature);
|
||||
str = numeric;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
#define LIBRATBAG_UTIL_H
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <libudev.h>
|
||||
@@ -117,6 +118,25 @@ strdup_safe(const char *str)
|
||||
return s;
|
||||
}
|
||||
|
||||
static inline int
|
||||
snprintf_safe(char *buf, size_t n, const char *fmt, ...)
|
||||
{
|
||||
va_list args;
|
||||
int rc;
|
||||
|
||||
va_start(args, fmt);
|
||||
rc = vsnprintf(buf, n, fmt, args);
|
||||
va_end(args);
|
||||
|
||||
if (rc < 0 || n < (size_t)rc)
|
||||
abort();
|
||||
|
||||
return rc;
|
||||
}
|
||||
|
||||
#define sprintf_safe(buf, fmt, ...) \
|
||||
snprintf_safe(buf, ARRAY_LENGTH(buf), fmt, __VA_ARGS__)
|
||||
|
||||
static inline void
|
||||
msleep(unsigned int ms)
|
||||
{
|
||||
|
||||
@@ -106,10 +106,10 @@ log_buffer(struct ratbag *ratbag,
|
||||
output_buf = zalloc(buf_len);
|
||||
n = 0;
|
||||
if (header)
|
||||
n += sprintf(output_buf, "%s", header);
|
||||
n += snprintf_safe(output_buf, buf_len - n, "%s", header);
|
||||
|
||||
for (i = 0; i < len; ++i) {
|
||||
n += sprintf(&output_buf[n], "%s%02x", sep, buf[i] & 0xFF);
|
||||
n += snprintf_safe(&output_buf[n], buf_len - n, "%s%02x", sep, buf[i] & 0xFF);
|
||||
sep = " ";
|
||||
}
|
||||
|
||||
|
||||
@@ -706,7 +706,7 @@ ratbag_cmd_list_supported_devices(const struct ratbag_cmd *cmd,
|
||||
|
||||
i = -1;
|
||||
while (++i < n) {
|
||||
sprintf(path, "/dev/input/%s", input_list[i]->d_name);
|
||||
sprintf_safe(path, "/dev/input/%s", input_list[i]->d_name);
|
||||
device = ratbag_cmd_open_device(ratbag, path);
|
||||
if (device) {
|
||||
printf("%s:\t%s\n", path, ratbag_device_get_name(device));
|
||||
|
||||
@@ -129,7 +129,7 @@ button_action_button_to_str(struct ratbag_button *button)
|
||||
{
|
||||
char str[96];
|
||||
|
||||
sprintf(str, "button %d", ratbag_button_get_button(button));
|
||||
sprintf_safe(str, "button %d", ratbag_button_get_button(button));
|
||||
|
||||
return strdup_safe(str);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user