Only run the exec once if test passes.

I accidentally made the tests run MAX_RETRIES times instead of
running once when passing, and at most MAX_RETRIES when the
test fails. Also, add a bit of randomness to the usleep to try and
avoid tests syncing up on failures.

Bug: 193898572

Test: Ran unit tests and verified that a pass doesn't result in another run.
Test: Ran three copies of the unit tests at the same time to verify that
Test: there isn't a flaky test failure.
Change-Id: I8b8d3cd05ca7d1e87ce34bf10aeef84f6989fdab
diff --git a/libc/malloc_debug/tests/malloc_debug_system_tests.cpp b/libc/malloc_debug/tests/malloc_debug_system_tests.cpp
index 59729d0..eaf86c5 100644
--- a/libc/malloc_debug/tests/malloc_debug_system_tests.cpp
+++ b/libc/malloc_debug/tests/malloc_debug_system_tests.cpp
@@ -46,6 +46,7 @@
 
 #include <atomic>
 #include <mutex>
+#include <random>
 #include <string>
 #include <thread>
 #include <vector>
@@ -218,20 +219,31 @@
   }
 
   void Exec(const char* test_name, const char* debug_options, int expected_exit_code = 0) {
+    std::random_device rd;
+    std::mt19937 generator(rd());
+    std::uniform_int_distribution<> rand_usleep_time(1, 10);
+    std::srand(std::time(nullptr));
+
     for (size_t i = 0; i < kMaxRetries; i++) {
       ASSERT_NO_FATAL_FAILURE(InternalExec(test_name, debug_options, expected_exit_code));
 
       // Due to log messages sometimes getting lost, if a log message
       // is not present, allow retrying the test.
       std::string error_msg;
-      if (!CheckExpectedLogStrings(&error_msg)) {
+      bool found_expected = CheckExpectedLogStrings(&error_msg);
+      if (!found_expected) {
         ASSERT_NE(i, kMaxRetries - 1) << error_msg;
-        usleep(1000);
+        // Sleep a random amount of time to attempt to avoid tests syncing
+        // up and sending the log messages at the same time.
+        usleep(1000 * rand_usleep_time(generator));
       }
 
       // This doesn't need to be retried since if the log message is
       // present, that is an immediate fail.
       ASSERT_NO_FATAL_FAILURE(VerifyUnexpectedLogStrings());
+      if (found_expected) {
+        break;
+      }
     }
   }