Fix a race between NotifyMonitor/AwaitResult

PiperOrigin-RevId: 410463096
Change-Id: I370705131ac78f26736646596189d8cad2bb70c2
This commit is contained in:
Wiktor Garbacz 2021-11-17 01:39:46 -08:00 committed by Copybara-Service
parent 04503f9bbe
commit e86322db84
3 changed files with 16 additions and 7 deletions

View File

@ -301,11 +301,11 @@ target_link_libraries(sandbox2_sandbox2
absl::optional
absl::str_format
absl::strings
absl::synchronization
sapi::strerror
sapi::base
PUBLIC absl::status
absl::statusor
absl::synchronization
absl::time
sapi::config
sapi::file_base

View File

@ -22,6 +22,7 @@
#include "absl/memory/memory.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "sandboxed_api/sandbox2/monitor.h"
#include "sandboxed_api/sandbox2/result.h"
@ -44,14 +45,17 @@ absl::StatusOr<Result> Sandbox2::AwaitResultWithTimeout(
if (!done) {
return absl::DeadlineExceededError("Sandbox did not finish within timeout");
}
monitor_thread_->join();
{
absl::MutexLock lock(&monitor_notify_mutex_);
monitor_thread_->join();
CHECK(IsTerminated()) << "Monitor did not terminate";
CHECK(IsTerminated()) << "Monitor did not terminate";
// Reset the Monitor Thread object to its initial state, as to mark that this
// object cannot be used anymore to control behavior of the sandboxee (e.g.
// via signals).
monitor_thread_.reset(nullptr);
// Reset the Monitor Thread object to its initial state, as to mark that
// this object cannot be used anymore to control behavior of the sandboxee
// (e.g. via signals).
monitor_thread_.reset();
}
VLOG(1) << "Final execution status: " << monitor_->result_.ToString();
CHECK(monitor_->result_.final_status() != Result::UNSET);
@ -74,6 +78,7 @@ bool Sandbox2::RunAsync() {
}
void Sandbox2::NotifyMonitor() {
absl::ReaderMutexLock lock(&monitor_notify_mutex_);
if (monitor_thread_ != nullptr) {
pthread_kill(monitor_thread_->native_handle(), SIGCHLD);
}

View File

@ -27,6 +27,7 @@
#include "absl/base/macros.h"
#include "absl/memory/memory.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "sandboxed_api/sandbox2/comms.h"
#include "sandboxed_api/sandbox2/executor.h"
#include "sandboxed_api/sandbox2/ipc.h"
@ -136,6 +137,9 @@ class Sandbox2 final {
// Monitor thread object - owned by Sandbox2.
std::unique_ptr<std::thread> monitor_thread_;
// Synchronizes monitor thread deletion and notifying the monitor.
absl::Mutex monitor_notify_mutex_;
};
} // namespace sandbox2