Commit 4bf4ef52 authored by Wander Lairson Costa's avatar Wander Lairson Costa Committed by Tomas Glozar
Browse files

rtla/trace: Fix write loop in trace_event_save_hist()



The write loop in trace_event_save_hist() does not correctly handle
errors from the write() system call. If write() returns -1, this value
is added to the loop index, leading to an incorrect memory access on
the next iteration and potentially an infinite loop. The loop also
fails to handle EINTR.

Fix the write loop by introducing proper error handling. The return
value of write() is now stored in a ssize_t variable and checked for
errors. The loop retries the call if interrupted by a signal and breaks
on any other error after logging it with strerror().

Additionally, change the index variable type from int to size_t to
match the type used for buffer sizes and by strlen(), improving type
safety.

Fixes: 761916fd ("rtla/trace: Save event histogram output to a file")
Signed-off-by: default avatarWander Lairson Costa <wander@redhat.com>
Link: https://lore.kernel.org/r/20260309195040.1019085-16-wander@redhat.com


Signed-off-by: default avatarTomas Glozar <tglozar@redhat.com>
parent 48fbcd4d
Loading
Loading
Loading
Loading
+11 −3
Original line number Diff line number Diff line
@@ -342,11 +342,11 @@ static void trace_event_disable_filter(struct trace_instance *instance,
static void trace_event_save_hist(struct trace_instance *instance,
				  struct trace_events *tevent)
{
	int index, out_fd;
	size_t index, hist_len;
	mode_t mode = 0644;
	char path[MAX_PATH];
	char *hist;
	size_t hist_len;
	int out_fd;

	if (!tevent)
		return;
@@ -378,7 +378,15 @@ static void trace_event_save_hist(struct trace_instance *instance,
	index = 0;
	hist_len = strlen(hist);
	do {
		index += write(out_fd, &hist[index], hist_len - index);
		const ssize_t written = write(out_fd, &hist[index], hist_len - index);

		if (written < 0) {
			if (errno == EINTR)
				continue;
			err_msg("  Error writing hist file: %s\n", strerror(errno));
			break;
		}
		index += written;
	} while (index < hist_len);

	free(hist);