xref: /aosp_15_r20/external/sandboxed-api/sandboxed_api/testing.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/testing.h"
16 
17 #include <cstdlib>
18 #include <string>
19 
20 #include "absl/strings/string_view.h"
21 #include "sandboxed_api/config.h"
22 #include "sandboxed_api/sandbox2/allow_all_syscalls.h"
23 #include "sandboxed_api/sandbox2/policybuilder.h"
24 #include "sandboxed_api/util/path.h"
25 
26 namespace sapi {
27 
CreateDefaultPermissiveTestPolicy(absl::string_view bin_path)28 sandbox2::PolicyBuilder CreateDefaultPermissiveTestPolicy(
29     absl::string_view bin_path) {
30   sandbox2::PolicyBuilder builder;
31   // Don't restrict the syscalls at all.
32   builder.DefaultAction(sandbox2::AllowAllSyscalls());
33   if (sapi::host_os::IsAndroid()) {
34     builder.DisableNamespaces();
35     return builder;
36   }
37   if (IsCoverageRun()) {
38     builder.AddDirectory(getenv("COVERAGE_DIR"), /*is_ro=*/false);
39   }
40   if constexpr (sapi::sanitizers::IsAny()) {
41     builder.AddLibrariesForBinary(bin_path);
42   }
43   if constexpr (sapi::sanitizers::IsAny()) {
44     builder.AddDirectory("/proc");
45   }
46   builder.AllowTcMalloc();
47   return builder;
48 }
49 
GetTestTempPath(absl::string_view name)50 std::string GetTestTempPath(absl::string_view name) {
51   // When using Bazel, the environment variable TEST_TMPDIR is guaranteed to be
52   // set.
53   // See https://bazel.build/reference/test-encyclopedia#initial-conditions for
54   // details.
55   const char* test_tmpdir = getenv("TEST_TMPDIR");
56   return file::JoinPath(test_tmpdir ? test_tmpdir : ".", name);
57 }
58 
GetTestSourcePath(absl::string_view name)59 std::string GetTestSourcePath(absl::string_view name) {
60   // Like in GetTestTempPath(), when using Bazel, the environment variable
61   // TEST_SRCDIR is guaranteed to be set.
62   const char* test_srcdir = getenv("TEST_SRCDIR");
63   return file::JoinPath(test_srcdir ? test_srcdir : ".",
64                         "com_google_sandboxed_api/sandboxed_api", name);
65 }
66 
67 }  // namespace sapi
68