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.

Signed-off-by: Wander Lairson Costa <[email protected]>
---
 tools/tracing/rtla/src/trace.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)

diff --git a/tools/tracing/rtla/src/trace.c b/tools/tracing/rtla/src/trace.c
index ed7db5f4115ce..fed3362527b08 100644
--- a/tools/tracing/rtla/src/trace.c
+++ b/tools/tracing/rtla/src/trace.c
@@ -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);
-- 
2.52.0


Reply via email to