From dc1bf5b9bbaa7cc204519b5984005271598d2e4e Mon Sep 17 00:00:00 2001
From: Aleksandr Nogikh <nogikh@google.com>
Date: Wed, 12 Jun 2024 14:04:25 +0200
Subject: [PATCH] executor: use different remote kcov handles each time

It serves two purposes:
1) Ignore the remote coverage that was initiated by the already exited
   executor instances.
2) Circumvent the KCOV bug that sometimes results in dangling remote
   kcov handles. The bug is fixed in [1], but it will take time for it
   to reach all the kernels we fuzz.

Fixes #4626.

[1] https://lore.kernel.org/all/20240611133229.527822-1-nogikh@google.com/
---
 executor/executor_linux.h | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/executor/executor_linux.h b/executor/executor_linux.h
index 984c0ba62477..f8d76b77e23a 100644
--- a/executor/executor_linux.h
+++ b/executor/executor_linux.h
@@ -150,8 +150,16 @@ static void cover_enable(cover_t* cov, bool collect_comps, bool extra)
 	    .area_size = kExtraCoverSize,
 	    .num_handles = 1,
 	};
-	arg.common_handle = kcov_remote_handle(KCOV_SUBSYSTEM_COMMON, procid + 1);
-	arg.handles[0] = kcov_remote_handle(KCOV_SUBSYSTEM_USB, procid + 1);
+
+	// Let's use a different kcov remote handle each restart -- we don't want to
+	// see the remote coverage triggered by the already exited executors.
+	struct timeval curr_time;
+	gettimeofday(&curr_time, NULL);
+	uint64 current_usec = curr_time.tv_sec * 1000000 + curr_time.tv_usec;
+	// Combine procid with the current time.
+	uint64 instance_id = (current_usec & KCOV_INSTANCE_MASK & ~0xF) | (procid & 0xF);
+	arg.common_handle = kcov_remote_handle(KCOV_SUBSYSTEM_COMMON, instance_id);
+	arg.handles[0] = kcov_remote_handle(KCOV_SUBSYSTEM_USB, instance_id);
 	if (ioctl(cov->fd, KCOV_REMOTE_ENABLE, &arg))
 		exitf("remote cover enable write trace failed");
 }