[lttng-dev] [PATCH] Avoid using the heap for small strings with tracef/tracelog

Norbert Lange nolange79 at gmail.com
Wed May 19 12:56:48 EDT 2021


Try to use vsnprintf with a 512 Byte buffer on the Stack,
if that fails allocate a larger one.

Signed-off-by: Norbert Lange <nolange79 at gmail.com>
---
 liblttng-ust/tracef.c   | 13 ++++++++++---
 liblttng-ust/tracelog.c | 12 +++++++++---
 2 files changed, 19 insertions(+), 6 deletions(-)

diff --git a/liblttng-ust/tracef.c b/liblttng-ust/tracef.c
index ea98e43e..18c29e25 100644
--- a/liblttng-ust/tracef.c
+++ b/liblttng-ust/tracef.c
@@ -32,17 +32,24 @@
 void _lttng_ust_tracef(const char *fmt, ...)
 {
 	va_list ap;
-	char *msg;
+	char local_buf[512];
+	char *msg = local_buf;
 	int len;
 
 	va_start(ap, fmt);
-	len = vasprintf(&msg, fmt, ap);
+	len = vsnprintf(local_buf, sizeof(local_buf), fmt, ap);
+	if (len >= sizeof(local_buf)) {
+		msg = (char *)malloc(len + 1);
+		len = msg ? vsnprintf(msg, len + 1, fmt, ap) : -1;
+	}
+
 	/* len does not include the final \0 */
 	if (len < 0)
 		goto end;
 	__tracepoint_cb_lttng_ust_tracef___event(msg, len,
 		LTTNG_UST_CALLER_IP());
-	free(msg);
 end:
+	if (msg != local_buf)
+		free(msg);
 	va_end(ap);
 }
diff --git a/liblttng-ust/tracelog.c b/liblttng-ust/tracelog.c
index 65fc87ed..a5d110fa 100644
--- a/liblttng-ust/tracelog.c
+++ b/liblttng-ust/tracelog.c
@@ -35,19 +35,25 @@
 			const char *fmt, ...) \
 	{ \
 		va_list ap; \
-		char *msg; \
+		char local_buf[512]; \
+		char *msg = local_buf; \
 		int len; \
 		\
 		va_start(ap, fmt); \
-		len = vasprintf(&msg, fmt, ap); \
+		len = vsnprintf(local_buf, sizeof(local_buf), fmt, ap); \
+		if (len >= sizeof(local_buf)) { \
+			msg = (char *)malloc(len + 1); \
+			len = msg ? vsnprintf(msg, len + 1, fmt, ap) : -1; \
+		} \
 		/* len does not include the final \0 */ \
 		if (len < 0) \
 			goto end; \
 		__tracepoint_cb_lttng_ust_tracelog___##level(file, \
 			line, func, msg, len, \
 			LTTNG_UST_CALLER_IP()); \
-		free(msg); \
 	end: \
+		if (msg != local_buf) \
+			free(msg); \
 		va_end(ap); \
 	}
 
-- 
2.30.2



More information about the lttng-dev mailing list