#include <openssl/base.h>
#if defined(OPENSSL_LINUX) && !defined(OPENSSL_TSAN)
#include <errno.h>
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <functional>
#if defined(OPENSSL_THREADS)
#include <thread>
#include <vector>
#endif
#include <gtest/gtest.h>
#include "fork_detect.h"
static pid_t WaitpidEINTR(pid_t pid, int *out_status, int options) {
pid_t ret;
do {
ret = waitpid(pid, out_status, options);
} while (ret < 0 && errno == EINTR);
return ret;
}
static void CheckGenerationInChild(const char *name, uint64_t expected) {
uint64_t generation = CRYPTO_get_fork_generation();
if (generation != expected) {
fprintf(stderr, "%s generation (#1) was %" PRIu64 ", wanted %" PRIu64 ".\n",
name, generation, expected);
_exit(1);
}
generation = CRYPTO_get_fork_generation();
if (generation != expected) {
fprintf(stderr, "%s generation (#2) was %" PRIu64 ", wanted %" PRIu64 ".\n",
name, generation, expected);
_exit(1);
}
}
static void ForkInChild(std::function<void()> f) {
fflush(stderr);
const pid_t pid = fork();
if (pid < 0) {
perror("fork");
_exit(1);
} else if (pid == 0) {
f();
_exit(0);
}
int status;
if (WaitpidEINTR(pid, &status, 0) < 0) {
perror("waitpid");
_exit(1);
}
if (!WIFEXITED(status)) {
fprintf(stderr, "Child did not exit cleanly.\n");
_exit(1);
}
if (WEXITSTATUS(status) != 0) {
_exit(WEXITSTATUS(status));
}
}
TEST(ForkDetect, Test) {
if (getenv("BORINGSSL_IGNORE_MADV_WIPEONFORK")) {
CRYPTO_fork_detect_ignore_madv_wipeonfork_for_testing();
}
const uint64_t start = CRYPTO_get_fork_generation();
if (start == 0) {
fprintf(stderr, "Fork detection not supported. Skipping test.\n");
return;
}
EXPECT_EQ(start, CRYPTO_get_fork_generation());
fflush(stderr);
const pid_t child = fork();
if (child == 0) {
for (int i = 0; i < 2; i++) {
ForkInChild([&] { CheckGenerationInChild("Grandchild", start + 1); });
}
CheckGenerationInChild("Child", start + 1);
for (int i = 0; i < 2; i++) {
ForkInChild([&] { CheckGenerationInChild("Grandchild", start + 2); });
}
#if defined(OPENSSL_THREADS)
ForkInChild([&] {
std::vector<std::thread> threads(4);
for (int i = 0; i < 2; i++) {
for (auto &t : threads) {
t = std::thread(
[&] { CheckGenerationInChild("Grandchild thread", start + 2); });
}
for (auto &t : threads) {
t.join();
}
}
});
#endif
CheckGenerationInChild("Child", start + 1);
_exit(0);
}
ASSERT_GT(child, 0) << "Error in fork: " << strerror(errno);
int status;
ASSERT_EQ(child, WaitpidEINTR(child, &status, 0))
<< "Error in waitpid: " << strerror(errno);
ASSERT_TRUE(WIFEXITED(status));
EXPECT_EQ(0, WEXITSTATUS(status)) << "Error in child process";
EXPECT_EQ(start, CRYPTO_get_fork_generation());
}
#endif