• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
27 namespace sandbox2 {
28 
WaitAndFork()29 pid_t ForkingClient::WaitAndFork() {
30   // We don't instantiate the Fork-Server until the first Fork() call takes
31   // place (in order to conserve resources, and avoid calling Fork-Server
32   // initialization routines).
33   if (!fork_server_worker_) {
34     sanitizer::WaitForSanitizer();
35     // Perform that check once only, because it's quite CPU-expensive.
36     int n = sanitizer::GetNumberOfThreads(getpid());
37     CHECK_NE(n, -1) << "sanitizer::GetNumberOfThreads failed";
38     CHECK_EQ(n, 1) << "Too many threads (" << n
39                    << ") during sandbox2::Client::WaitAndFork()";
40     fork_server_worker_ = std::make_unique<ForkServer>(comms_);
41   }
42   pid_t pid = fork_server_worker_->ServeRequest();
43   if (pid == -1 && fork_server_worker_->IsTerminated()) {
44     VLOG(1) << "ForkServer Comms closed. Exiting";
45     exit(0);
46   }
47   return pid;
48 }
49 
50 }  // namespace sandbox2
51