1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #pragma once
18
19 #include <dirent.h>
20 #include <dlfcn.h>
21 #include <fcntl.h>
22 #include <gtest/gtest.h>
23 #include <inttypes.h>
24 #include <sys/mman.h>
25 #include <sys/prctl.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29
30 #if defined(__BIONIC__)
31 #include <sys/system_properties.h>
32 #endif
33
34 #if defined(__BIONIC__)
35 #include <bionic/macros.h>
36 #else
37 #define untag_address(p) p
38 #endif
39
40 #include <atomic>
41 #include <string>
42 #include <regex>
43
44 #include <android-base/file.h>
45 #include <android-base/macros.h>
46 #include <android-base/scopeguard.h>
47 #include <android-base/stringprintf.h>
48
49 #if defined(__LP64__)
50 #define PATH_TO_SYSTEM_LIB "/system/lib64/"
51 #else
52 #define PATH_TO_SYSTEM_LIB "/system/lib/"
53 #endif
54
55 #if defined(__GLIBC__)
56 #define BIN_DIR "/bin/"
57 #else
58 #define BIN_DIR "/system/bin/"
59 #endif
60
61 #if defined(__BIONIC__)
62 #define KNOWN_FAILURE_ON_BIONIC(x) xfail_ ## x
63 #else
64 #define KNOWN_FAILURE_ON_BIONIC(x) x
65 #endif
66
67 // bionic's dlsym doesn't work in static binaries, so we can't access icu,
68 // so any unicode test case will fail.
have_dl()69 static inline bool have_dl() {
70 return (dlopen("libc.so", 0) != nullptr);
71 }
72
running_with_native_bridge()73 static inline bool running_with_native_bridge() {
74 #if defined(__BIONIC__)
75 static const prop_info* pi = __system_property_find("ro.dalvik.vm.isa." ABI_STRING);
76 return pi != nullptr;
77 #endif
78 return false;
79 }
80
81 #define SKIP_WITH_NATIVE_BRIDGE if (running_with_native_bridge()) GTEST_SKIP()
82
83 #if defined(__linux__)
84
85 #include <sys/sysmacros.h>
86
87 struct map_record {
88 uintptr_t addr_start;
89 uintptr_t addr_end;
90
91 int perms;
92
93 size_t offset;
94
95 dev_t device;
96 ino_t inode;
97
98 std::string pathname;
99 };
100
101 class Maps {
102 public:
parse_maps(std::vector<map_record> * maps)103 static bool parse_maps(std::vector<map_record>* maps) {
104 maps->clear();
105
106 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("/proc/self/maps", "re"), fclose);
107 if (!fp) return false;
108
109 char line[BUFSIZ];
110 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
111 map_record record;
112 uint32_t dev_major, dev_minor;
113 int path_offset;
114 char prot[5]; // sizeof("rwxp")
115 if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %" SCNxPTR " %x:%x %lu %n",
116 &record.addr_start, &record.addr_end, prot, &record.offset,
117 &dev_major, &dev_minor, &record.inode, &path_offset) == 7) {
118 record.perms = 0;
119 if (prot[0] == 'r') {
120 record.perms |= PROT_READ;
121 }
122 if (prot[1] == 'w') {
123 record.perms |= PROT_WRITE;
124 }
125 if (prot[2] == 'x') {
126 record.perms |= PROT_EXEC;
127 }
128
129 // TODO: parse shared/private?
130
131 record.device = makedev(dev_major, dev_minor);
132 record.pathname = line + path_offset;
133 if (!record.pathname.empty() && record.pathname.back() == '\n') {
134 record.pathname.pop_back();
135 }
136 maps->push_back(record);
137 }
138 }
139
140 return true;
141 }
142 };
143
144 extern "C" pid_t gettid();
145
146 #endif
147
WaitUntilThreadSleep(std::atomic<pid_t> & tid)148 static inline void WaitUntilThreadSleep(std::atomic<pid_t>& tid) {
149 while (tid == 0) {
150 usleep(1000);
151 }
152 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid.load());
153 std::regex regex {R"(\s+S\s+)"};
154
155 while (true) {
156 std::string content;
157 ASSERT_TRUE(android::base::ReadFileToString(filename, &content));
158 if (std::regex_search(content, regex)) {
159 break;
160 }
161 usleep(1000);
162 }
163 }
164
165 static inline void AssertChildExited(int pid, int expected_exit_status,
166 const std::string* error_msg = nullptr) {
167 int status;
168 std::string error;
169 if (error_msg == nullptr) {
170 error_msg = &error;
171 }
172 ASSERT_EQ(pid, TEMP_FAILURE_RETRY(waitpid(pid, &status, 0))) << *error_msg;
173 if (expected_exit_status >= 0) {
174 ASSERT_TRUE(WIFEXITED(status)) << *error_msg;
175 ASSERT_EQ(expected_exit_status, WEXITSTATUS(status)) << *error_msg;
176 } else {
177 ASSERT_TRUE(WIFSIGNALED(status)) << *error_msg;
178 ASSERT_EQ(-expected_exit_status, WTERMSIG(status)) << *error_msg;
179 }
180 }
181
CloseOnExec(int fd)182 static inline bool CloseOnExec(int fd) {
183 int flags = fcntl(fd, F_GETFD);
184 // This isn't ideal, but the alternatives are worse:
185 // * If we return void and use ASSERT_NE here, we get failures at utils.h:191
186 // rather than in the relevant test.
187 // * If we ignore failures of fcntl(), well, that's obviously a bad idea.
188 if (flags == -1) abort();
189 return flags & FD_CLOEXEC;
190 }
191
192 // The absolute path to the executable
193 const std::string& get_executable_path();
194
195 // Access to argc/argv/envp
196 int get_argc();
197 char** get_argv();
198 char** get_envp();
199
200 // ExecTestHelper is only used in bionic and glibc tests.
201 #ifndef __APPLE__
202 class ExecTestHelper {
203 public:
GetArgs()204 char** GetArgs() {
205 return const_cast<char**>(args_.data());
206 }
GetArg0()207 const char* GetArg0() {
208 return args_[0];
209 }
GetEnv()210 char** GetEnv() {
211 return const_cast<char**>(env_.data());
212 }
GetOutput()213 const std::string& GetOutput() {
214 return output_;
215 }
216
SetArgs(const std::vector<const char * > & args)217 void SetArgs(const std::vector<const char*>& args) {
218 args_ = args;
219 }
SetEnv(const std::vector<const char * > & env)220 void SetEnv(const std::vector<const char*>& env) {
221 env_ = env;
222 }
223
Run(const std::function<void ()> & child_fn,int expected_exit_status,const char * expected_output_regex)224 void Run(const std::function<void()>& child_fn, int expected_exit_status,
225 const char* expected_output_regex) {
226 int fds[2];
227 ASSERT_NE(pipe(fds), -1);
228
229 pid_t pid = fork();
230 ASSERT_NE(pid, -1);
231
232 if (pid == 0) {
233 // Child.
234 close(fds[0]);
235 dup2(fds[1], STDOUT_FILENO);
236 dup2(fds[1], STDERR_FILENO);
237 if (fds[1] != STDOUT_FILENO && fds[1] != STDERR_FILENO) close(fds[1]);
238 child_fn();
239 FAIL();
240 }
241
242 // Parent.
243 close(fds[1]);
244 output_.clear();
245 char buf[BUFSIZ];
246 ssize_t bytes_read;
247 while ((bytes_read = TEMP_FAILURE_RETRY(read(fds[0], buf, sizeof(buf)))) > 0) {
248 output_.append(buf, bytes_read);
249 }
250 close(fds[0]);
251
252 std::string error_msg("Test output:\n" + output_);
253 AssertChildExited(pid, expected_exit_status, &error_msg);
254 if (expected_output_regex != nullptr) {
255 if (!std::regex_search(output_, std::regex(expected_output_regex))) {
256 FAIL() << "regex " << expected_output_regex << " didn't match " << output_;
257 }
258 }
259 }
260
261 private:
262 std::vector<const char*> args_;
263 std::vector<const char*> env_;
264 std::string output_;
265 };
266
267 void RunGwpAsanTest(const char* test_name);
268 void RunSubtestNoEnv(const char* test_name);
269 #endif
270
271 class FdLeakChecker {
272 public:
FdLeakChecker()273 FdLeakChecker() {
274 }
275
~FdLeakChecker()276 ~FdLeakChecker() {
277 size_t end_count = CountOpenFds();
278 EXPECT_EQ(start_count_, end_count);
279 }
280
281 private:
CountOpenFds()282 static size_t CountOpenFds() {
283 auto fd_dir = std::unique_ptr<DIR, decltype(&closedir)>{ opendir("/proc/self/fd"), closedir };
284 size_t count = 0;
285 dirent* de = nullptr;
286 while ((de = readdir(fd_dir.get())) != nullptr) {
287 if (de->d_type == DT_LNK) {
288 ++count;
289 }
290 }
291 return count;
292 }
293
294 size_t start_count_ = CountOpenFds();
295 };
296
297 // From <benchmark/benchmark.h>.
298 template <class Tp>
DoNotOptimize(Tp const & value)299 static inline void DoNotOptimize(Tp const& value) {
300 asm volatile("" : : "r,m"(value) : "memory");
301 }
302 template <class Tp>
DoNotOptimize(Tp & value)303 static inline void DoNotOptimize(Tp& value) {
304 asm volatile("" : "+r,m"(value) : : "memory");
305 }
306
running_with_mte()307 static inline bool running_with_mte() {
308 #ifdef __aarch64__
309 int level = prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0);
310 return level >= 0 && (level & PR_TAGGED_ADDR_ENABLE) &&
311 (level & PR_MTE_TCF_MASK) != PR_MTE_TCF_NONE;
312 #else
313 return false;
314 #endif
315 }
316
317 bool IsLowRamDevice();
318