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