xref: /aosp_15_r20/external/sandboxed-api/sandboxed_api/sandbox2/forkingclient.cc (revision ec63e07ab9515d95e79c211197c445ef84cefa6a)
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "sandboxed_api/sandbox2/forkingclient.h"
16 
17 #include <unistd.h>
18 
19 #include <cstdlib>
20 #include <memory>
21 
22 #include "absl/log/check.h"
23 #include "absl/log/log.h"
24 #include "sandboxed_api/sandbox2/forkserver.h"
25 #include "sandboxed_api/sandbox2/sanitizer.h"
26 #include "sandboxed_api/util/raw_logging.h"
27 
28 namespace sandbox2 {
29 
WaitAndFork()30 pid_t ForkingClient::WaitAndFork() {
31   // We don't instantiate the Fork-Server until the first Fork() call takes
32   // place (in order to conserve resources, and avoid calling Fork-Server
33   // initialization routines).
34   if (!fork_server_worker_) {
35     sanitizer::WaitForSanitizer();
36     // Perform that check once only, because it's quite CPU-expensive.
37     int n = sanitizer::GetNumberOfThreads(getpid());
38     CHECK_NE(n, -1) << "sanitizer::GetNumberOfThreads failed";
39     CHECK_EQ(n, 1) << "Too many threads (" << n
40                    << ") during sandbox2::Client::WaitAndFork()";
41     fork_server_worker_ = std::make_unique<ForkServer>(comms_);
42   }
43   pid_t pid = fork_server_worker_->ServeRequest();
44   if (pid == -1 && fork_server_worker_->IsTerminated()) {
45     VLOG(1) << "ForkServer Comms closed. Exiting";
46     exit(0);
47   }
48   return pid;
49 }
50 
51 }  // namespace sandbox2
52