From 0d65836866ed3a91fefd977d8a5da2034ad67ea2 Mon Sep 17 00:00:00 2001 From: Roberto Scolaro Date: Tue, 19 Dec 2023 13:54:38 +0000 Subject: [PATCH] fix: always initialize threadinfo on the stack Signed-off-by: Roberto Scolaro --- userspace/libscap/linux/scap_procs.c | 2 ++ userspace/libsinsp/parsers.cpp | 2 ++ userspace/libsinsp/threadinfo.cpp | 14 +++++++++++++- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/userspace/libscap/linux/scap_procs.c b/userspace/libscap/linux/scap_procs.c index f037669bd9..6e96ddfae7 100644 --- a/userspace/libscap/linux/scap_procs.c +++ b/userspace/libscap/linux/scap_procs.c @@ -565,6 +565,8 @@ static int32_t scap_proc_add_from_proc(struct scap_linux_platform* linux_platfor int32_t res = SCAP_SUCCESS; struct stat dirstat; + memset(&tinfo, 0, sizeof(scap_threadinfo)); + snprintf(dir_name, sizeof(dir_name), "%s/%u/", procdirname, tid); snprintf(filename, sizeof(filename), "%sexe", dir_name); diff --git a/userspace/libsinsp/parsers.cpp b/userspace/libsinsp/parsers.cpp index a69c07633b..709f3e42c7 100644 --- a/userspace/libsinsp/parsers.cpp +++ b/userspace/libsinsp/parsers.cpp @@ -4184,6 +4184,8 @@ void sinsp_parser::parse_rw_exit(sinsp_evt *evt) char error[SCAP_LASTERR_SIZE]; scap_threadinfo scap_tinfo {}; + memset(&scap_tinfo, 0, sizeof(scap_tinfo)); + m_inspector->m_thread_manager->thread_to_scap(*evt->m_tinfo, &scap_tinfo); // Get the new fds. The callbacks we have registered populate the fd table diff --git a/userspace/libsinsp/threadinfo.cpp b/userspace/libsinsp/threadinfo.cpp index a117d69183..3e855b07b4 100644 --- a/userspace/libsinsp/threadinfo.cpp +++ b/userspace/libsinsp/threadinfo.cpp @@ -1903,6 +1903,8 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) uint32_t entrylen = 0; auto cg = tinfo.cgroups(); + memset(&sctinfo, 0, sizeof(scap_threadinfo)); + thread_to_scap(tinfo, &sctinfo); tinfo.args_to_iovec(&args_iov, &argscnt, argsrem); tinfo.env_to_iovec(&envs_iov, &envscnt, envsrem); @@ -1949,6 +1951,8 @@ void sinsp_thread_manager::dump_threads_to_file(scap_dumper_t* dumper) scap_threadinfo sctinfo {}; + memset(&sctinfo, 0, sizeof(scap_threadinfo)); + // Note: as scap_fd_add/scap_write_proc_fds do not use // any of the array-based fields like comm, etc. a // shallow copy is safe @@ -2031,7 +2035,15 @@ threadinfo_map_t::ptr_t sinsp_thread_manager::get_thread_ref(int64_t tid, bool q } scap_threadinfo scap_proc {}; - bool have_scap_proc = false; + bool have_scap_proc = false; + + // leaving scap_proc uninitialized could lead to undefined behaviour. + // to be safe we should initialized to zero. + memset(&scap_proc, 0, sizeof(scap_threadinfo)); + + scap_proc.tid = -1; + scap_proc.pid = -1; + scap_proc.ptid = -1; // unfortunately, sinsp owns the threade factory sinsp_threadinfo* newti = m_inspector->build_threadinfo();