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/types.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 
28 #if defined(__BIONIC__)
29 #include <sys/system_properties.h>
30 #endif
31 
32 #if defined(__BIONIC__)
33 #include <bionic/macros.h>
34 #else
35 #define untag_address(p) p
36 #endif
37 
38 #include <atomic>
39 #include <string>
40 #include <regex>
41 
42 #include <android-base/file.h>
43 #include <android-base/macros.h>
44 #include <android-base/scopeguard.h>
45 #include <android-base/stringprintf.h>
46 
47 #if defined(__LP64__)
48 #define PATH_TO_SYSTEM_LIB "/system/lib64/"
49 #else
50 #define PATH_TO_SYSTEM_LIB "/system/lib/"
51 #endif
52 
53 #if defined(__GLIBC__)
54 #define BIN_DIR "/bin/"
55 #else
56 #define BIN_DIR "/system/bin/"
57 #endif
58 
59 #if defined(__BIONIC__)
60 #define KNOWN_FAILURE_ON_BIONIC(x) xfail_ ## x
61 #else
62 #define KNOWN_FAILURE_ON_BIONIC(x) x
63 #endif
64 
65 // bionic's dlsym doesn't work in static binaries, so we can't access icu,
66 // so any unicode test case will fail.
have_dl()67 static inline bool have_dl() {
68   return (dlopen("libc.so", 0) != nullptr);
69 }
70 
71 extern "C" void __hwasan_init() __attribute__((weak));
72 
running_with_hwasan()73 static inline bool running_with_hwasan() {
74   return &__hwasan_init != 0;
75 }
76 
77 #define SKIP_WITH_HWASAN if (running_with_hwasan()) GTEST_SKIP()
78 
running_with_native_bridge()79 static inline bool running_with_native_bridge() {
80 #if defined(__BIONIC__)
81 #if defined(__arm__)
82   static const prop_info* pi = __system_property_find("ro.dalvik.vm.isa.arm");
83   return pi != nullptr;
84 #elif defined(__aarch64__)
85   static const prop_info* pi = __system_property_find("ro.dalvik.vm.isa.arm64");
86   return pi != nullptr;
87 #endif
88 #endif
89   return false;
90 }
91 
92 #define SKIP_WITH_NATIVE_BRIDGE if (running_with_native_bridge()) GTEST_SKIP()
93 
94 #if defined(__linux__)
95 
96 #include <sys/sysmacros.h>
97 
98 struct map_record {
99   uintptr_t addr_start;
100   uintptr_t addr_end;
101 
102   int perms;
103 
104   size_t offset;
105 
106   dev_t device;
107   ino_t inode;
108 
109   std::string pathname;
110 };
111 
112 class Maps {
113  public:
parse_maps(std::vector<map_record> * maps)114   static bool parse_maps(std::vector<map_record>* maps) {
115     maps->clear();
116 
117     std::unique_ptr<FILE, decltype(&fclose)> fp(fopen("/proc/self/maps", "re"), fclose);
118     if (!fp) return false;
119 
120     char line[BUFSIZ];
121     while (fgets(line, sizeof(line), fp.get()) != nullptr) {
122       map_record record;
123       uint32_t dev_major, dev_minor;
124       int path_offset;
125       char prot[5]; // sizeof("rwxp")
126       if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %" SCNxPTR " %x:%x %lu %n",
127             &record.addr_start, &record.addr_end, prot, &record.offset,
128             &dev_major, &dev_minor, &record.inode, &path_offset) == 7) {
129         record.perms = 0;
130         if (prot[0] == 'r') {
131           record.perms |= PROT_READ;
132         }
133         if (prot[1] == 'w') {
134           record.perms |= PROT_WRITE;
135         }
136         if (prot[2] == 'x') {
137           record.perms |= PROT_EXEC;
138         }
139 
140         // TODO: parse shared/private?
141 
142         record.device = makedev(dev_major, dev_minor);
143         record.pathname = line + path_offset;
144         if (!record.pathname.empty() && record.pathname.back() == '\n') {
145           record.pathname.pop_back();
146         }
147         maps->push_back(record);
148       }
149     }
150 
151     return true;
152   }
153 };
154 
155 extern "C" pid_t gettid();
156 
157 #endif
158 
WaitUntilThreadSleep(std::atomic<pid_t> & tid)159 static inline void WaitUntilThreadSleep(std::atomic<pid_t>& tid) {
160   while (tid == 0) {
161     usleep(1000);
162   }
163   std::string filename = android::base::StringPrintf("/proc/%d/stat", tid.load());
164   std::regex regex {R"(\s+S\s+)"};
165 
166   while (true) {
167     std::string content;
168     ASSERT_TRUE(android::base::ReadFileToString(filename, &content));
169     if (std::regex_search(content, regex)) {
170       break;
171     }
172     usleep(1000);
173   }
174 }
175 
176 static inline void AssertChildExited(int pid, int expected_exit_status,
177                                      const std::string* error_msg = nullptr) {
178   int status;
179   std::string error;
180   if (error_msg == nullptr) {
181     error_msg = &error;
182   }
183   ASSERT_EQ(pid, TEMP_FAILURE_RETRY(waitpid(pid, &status, 0))) << *error_msg;
184   if (expected_exit_status >= 0) {
185     ASSERT_TRUE(WIFEXITED(status)) << *error_msg;
186     ASSERT_EQ(expected_exit_status, WEXITSTATUS(status)) << *error_msg;
187   } else {
188     ASSERT_TRUE(WIFSIGNALED(status)) << *error_msg;
189     ASSERT_EQ(-expected_exit_status, WTERMSIG(status)) << *error_msg;
190   }
191 }
192 
AssertCloseOnExec(int fd,bool close_on_exec)193 static inline void AssertCloseOnExec(int fd, bool close_on_exec) {
194   int flags = fcntl(fd, F_GETFD);
195   ASSERT_NE(flags, -1);
196   ASSERT_EQ(close_on_exec ? FD_CLOEXEC : 0, 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