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