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 <iomanip>
42 #include <string>
43 #include <regex>
44
45 #include <android-base/file.h>
46 #include <android-base/macros.h>
47 #include <android-base/scopeguard.h>
48 #include <android-base/stringprintf.h>
49
50 #if defined(__LP64__)
51 #define PATH_TO_SYSTEM_LIB "/system/lib64/"
52 #else
53 #define PATH_TO_SYSTEM_LIB "/system/lib/"
54 #endif
55
56 #if defined(__GLIBC__)
57 #define BIN_DIR "/bin/"
58 #else
59 #define BIN_DIR "/system/bin/"
60 #endif
61
62 #if defined(__BIONIC__)
63 #define KNOWN_FAILURE_ON_BIONIC(x) xfail_ ## x
64 #else
65 #define KNOWN_FAILURE_ON_BIONIC(x) x
66 #endif
67
running_with_native_bridge()68 static inline bool running_with_native_bridge() {
69 #if defined(__BIONIC__)
70 static const prop_info* pi = __system_property_find("ro.dalvik.vm.isa." ABI_STRING);
71 return pi != nullptr;
72 #endif
73 return false;
74 }
75
76 #define SKIP_WITH_NATIVE_BRIDGE if (running_with_native_bridge()) GTEST_SKIP()
77
78 #if defined(__linux__)
79
80 #include <sys/sysmacros.h>
81
82 struct map_record {
83 uintptr_t addr_start;
84 uintptr_t addr_end;
85
86 int perms;
87
88 size_t offset;
89
90 dev_t device;
91 ino_t inode;
92
93 std::string pathname;
94 };
95
96 class Maps {
97 public:
parse_maps(std::vector<map_record> * maps)98 static bool parse_maps(std::vector<map_record>* maps) {
99 maps->clear();
100
101 std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("/proc/self/maps", "re"), fclose);
102 if (!fp) return false;
103
104 char line[BUFSIZ];
105 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
106 map_record record;
107 uint32_t dev_major, dev_minor;
108 int path_offset;
109 char prot[5]; // sizeof("rwxp")
110 if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %" SCNxPTR " %x:%x %lu %n",
111 &record.addr_start, &record.addr_end, prot, &record.offset,
112 &dev_major, &dev_minor, &record.inode, &path_offset) == 7) {
113 record.perms = 0;
114 if (prot[0] == 'r') {
115 record.perms |= PROT_READ;
116 }
117 if (prot[1] == 'w') {
118 record.perms |= PROT_WRITE;
119 }
120 if (prot[2] == 'x') {
121 record.perms |= PROT_EXEC;
122 }
123
124 // TODO: parse shared/private?
125
126 record.device = makedev(dev_major, dev_minor);
127 record.pathname = line + path_offset;
128 if (!record.pathname.empty() && record.pathname.back() == '\n') {
129 record.pathname.pop_back();
130 }
131 maps->push_back(record);
132 }
133 }
134
135 return true;
136 }
137 };
138
139 extern "C" pid_t gettid();
140
141 #endif
142
WaitUntilThreadSleep(std::atomic<pid_t> & tid)143 static inline void WaitUntilThreadSleep(std::atomic<pid_t>& tid) {
144 while (tid == 0) {
145 usleep(1000);
146 }
147 std::string filename = android::base::StringPrintf("/proc/%d/stat", tid.load());
148 std::regex regex {R"(\s+S\s+)"};
149
150 while (true) {
151 std::string content;
152 ASSERT_TRUE(android::base::ReadFileToString(filename, &content));
153 if (std::regex_search(content, regex)) {
154 break;
155 }
156 usleep(1000);
157 }
158 }
159
160 static inline void AssertChildExited(int pid, int expected_exit_status,
161 const std::string* error_msg = nullptr) {
162 int status;
163 std::string error;
164 if (error_msg == nullptr) {
165 error_msg = &error;
166 }
167 ASSERT_EQ(pid, TEMP_FAILURE_RETRY(waitpid(pid, &status, 0))) << *error_msg;
168 if (expected_exit_status >= 0) {
169 ASSERT_TRUE(WIFEXITED(status)) << *error_msg;
170 ASSERT_EQ(expected_exit_status, WEXITSTATUS(status)) << *error_msg;
171 } else {
172 ASSERT_TRUE(WIFSIGNALED(status)) << *error_msg;
173 ASSERT_EQ(-expected_exit_status, WTERMSIG(status)) << *error_msg;
174 }
175 }
176
CloseOnExec(int fd)177 static inline bool CloseOnExec(int fd) {
178 int flags = fcntl(fd, F_GETFD);
179 // This isn't ideal, but the alternatives are worse:
180 // * If we return void and use ASSERT_NE here, we get failures at utils.h:191
181 // rather than in the relevant test.
182 // * If we ignore failures of fcntl(), well, that's obviously a bad idea.
183 if (flags == -1) abort();
184 return flags & FD_CLOEXEC;
185 }
186
187 // The absolute path to the executable
188 const std::string& get_executable_path();
189
190 // Access to argc/argv/envp
191 int get_argc();
192 char** get_argv();
193 char** get_envp();
194
195 // ExecTestHelper is only used in bionic and glibc tests.
196 #ifndef __APPLE__
197 class ExecTestHelper {
198 public:
GetArgs()199 char** GetArgs() {
200 return const_cast<char**>(args_.data());
201 }
GetArg0()202 const char* GetArg0() {
203 return args_[0];
204 }
GetEnv()205 char** GetEnv() {
206 return const_cast<char**>(env_.data());
207 }
GetOutput()208 const std::string& GetOutput() {
209 return output_;
210 }
211
SetArgs(const std::vector<const char * > & args)212 void SetArgs(const std::vector<const char*>& args) {
213 args_ = args;
214 }
SetEnv(const std::vector<const char * > & env)215 void SetEnv(const std::vector<const char*>& env) {
216 env_ = env;
217 }
218
Run(const std::function<void ()> & child_fn,int expected_exit_status,const char * expected_output_regex)219 void Run(const std::function<void()>& child_fn, int expected_exit_status,
220 const char* expected_output_regex) {
221 int fds[2];
222 ASSERT_NE(pipe(fds), -1);
223
224 pid_t pid = fork();
225 ASSERT_NE(pid, -1);
226
227 if (pid == 0) {
228 // Child.
229 close(fds[0]);
230 dup2(fds[1], STDOUT_FILENO);
231 dup2(fds[1], STDERR_FILENO);
232 if (fds[1] != STDOUT_FILENO && fds[1] != STDERR_FILENO) close(fds[1]);
233 child_fn();
234 FAIL();
235 }
236
237 // Parent.
238 close(fds[1]);
239 output_.clear();
240 char buf[BUFSIZ];
241 ssize_t bytes_read;
242 while ((bytes_read = TEMP_FAILURE_RETRY(read(fds[0], buf, sizeof(buf)))) > 0) {
243 output_.append(buf, bytes_read);
244 }
245 close(fds[0]);
246
247 std::string error_msg("Test output:\n" + output_);
248 AssertChildExited(pid, expected_exit_status, &error_msg);
249 if (expected_output_regex != nullptr) {
250 if (!std::regex_search(output_, std::regex(expected_output_regex))) {
251 FAIL() << "regex " << std::quoted(expected_output_regex) << " didn't match " << std::quoted(output_);
252 }
253 }
254 }
255
256 private:
257 std::vector<const char*> args_;
258 std::vector<const char*> env_;
259 std::string output_;
260 };
261
262 void RunGwpAsanTest(const char* test_name);
263 void RunSubtestNoEnv(const char* test_name);
264 #endif
265
266 class FdLeakChecker {
267 public:
FdLeakChecker()268 FdLeakChecker() {
269 }
270
~FdLeakChecker()271 ~FdLeakChecker() {
272 size_t end_count = CountOpenFds();
273 EXPECT_EQ(start_count_, end_count);
274 }
275
276 private:
CountOpenFds()277 static size_t CountOpenFds() {
278 auto fd_dir = std::unique_ptr<DIR, decltype(&closedir)>{ opendir("/proc/self/fd"), closedir };
279 size_t count = 0;
280 dirent* de = nullptr;
281 while ((de = readdir(fd_dir.get())) != nullptr) {
282 if (de->d_type == DT_LNK) {
283 ++count;
284 }
285 }
286 return count;
287 }
288
289 size_t start_count_ = CountOpenFds();
290 };
291
292 bool IsLowRamDevice();
293
294 int64_t NanoTime();
295
296 class Errno {
297 public:
Errno(int e)298 Errno(int e) : errno_(e) {}
299 int errno_;
300 };
301 void PrintTo(const Errno& e, std::ostream* os);
302 bool operator==(const Errno& lhs, const Errno& rhs);
303 #define ASSERT_ERRNO(expected_errno) ASSERT_EQ(Errno(expected_errno), Errno(errno))
304 #define EXPECT_ERRNO(expected_errno) EXPECT_EQ(Errno(expected_errno), Errno(errno))
305