1 /*===- InstrProfilingUtil.c - Support library for PGO instrumentation -----===*\
2 |*
3 |* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 |* See https://llvm.org/LICENSE.txt for license information.
5 |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 |*
7 \*===----------------------------------------------------------------------===*/
8 
9 #ifdef _WIN32
10 #include <direct.h>
11 #include <process.h>
12 #include <windows.h>
13 #include "WindowsMMap.h"
14 #else
15 #include <sys/file.h>
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19 #include <fcntl.h>
20 #include <errno.h>
21 #endif
22 
23 #ifdef COMPILER_RT_HAS_UNAME
24 #include <sys/utsname.h>
25 #endif
26 
27 #include <stdlib.h>
28 #include <string.h>
29 
30 #if defined(__linux__)
31 #include <signal.h>
32 #include <sys/prctl.h>
33 #endif
34 
35 #include "InstrProfiling.h"
36 #include "InstrProfilingUtil.h"
37 
38 COMPILER_RT_WEAK unsigned lprofDirMode = 0755;
39 
40 COMPILER_RT_VISIBILITY
41 void __llvm_profile_recursive_mkdir(char *path) {
42   int i;
43   int start = 1;
44 
45 #if defined(__ANDROID__) && defined(__ANDROID_API__) &&                        \
46     defined(__ANDROID_API_FUTURE__) &&                                         \
47     __ANDROID_API__ == __ANDROID_API_FUTURE__
48   // Avoid spammy selinux denial messages in Android by not attempting to
49   // create directories in GCOV_PREFIX.  These denials occur when creating (or
50   // even attempting to stat()) top-level directories like "/data".
51   //
52   // Do so by ignoring ${GCOV_PREFIX} when invoking mkdir().
53   const char *gcov_prefix = getenv("GCOV_PREFIX");
54   if (gcov_prefix != NULL) {
55     const int gcov_prefix_len = strlen(gcov_prefix);
56     if (strncmp(path, gcov_prefix, gcov_prefix_len) == 0)
57       start = gcov_prefix_len;
58   }
59 #endif
60 
61   for (i = start; path[i] != '\0'; ++i) {
62     char save = path[i];
63     if (!IS_DIR_SEPARATOR(path[i]))
64       continue;
65     path[i] = '\0';
66 #ifdef _WIN32
67     _mkdir(path);
68 #else
69     /* Some of these will fail, ignore it. */
70     mkdir(path, __llvm_profile_get_dir_mode());
71 #endif
72     path[i] = save;
73   }
74 }
75 
76 COMPILER_RT_VISIBILITY
77 void __llvm_profile_set_dir_mode(unsigned Mode) { lprofDirMode = Mode; }
78 
79 COMPILER_RT_VISIBILITY
80 unsigned __llvm_profile_get_dir_mode(void) { return lprofDirMode; }
81 
82 #if COMPILER_RT_HAS_ATOMICS != 1
83 COMPILER_RT_VISIBILITY
84 uint32_t lprofBoolCmpXchg(void **Ptr, void *OldV, void *NewV) {
85   void *R = *Ptr;
86   if (R == OldV) {
87     *Ptr = NewV;
88     return 1;
89   }
90   return 0;
91 }
92 COMPILER_RT_VISIBILITY
93 void *lprofPtrFetchAdd(void **Mem, long ByteIncr) {
94   void *Old = *Mem;
95   *((char **)Mem) += ByteIncr;
96   return Old;
97 }
98 
99 #endif
100 
101 #ifdef _WIN32
102 COMPILER_RT_VISIBILITY int lprofGetHostName(char *Name, int Len) {
103   WCHAR Buffer[COMPILER_RT_MAX_HOSTLEN];
104   DWORD BufferSize = sizeof(Buffer);
105   BOOL Result =
106       GetComputerNameExW(ComputerNameDnsFullyQualified, Buffer, &BufferSize);
107   if (!Result)
108     return -1;
109   if (WideCharToMultiByte(CP_UTF8, 0, Buffer, -1, Name, Len, NULL, NULL) == 0)
110     return -1;
111   return 0;
112 }
113 #elif defined(COMPILER_RT_HAS_UNAME)
114 COMPILER_RT_VISIBILITY int lprofGetHostName(char *Name, int Len) {
115   struct utsname N;
116   int R = uname(&N);
117   if (R >= 0) {
118     strncpy(Name, N.nodename, Len);
119     return 0;
120   }
121   return R;
122 }
123 #endif
124 
125 COMPILER_RT_VISIBILITY int lprofLockFd(int fd) {
126 #ifdef COMPILER_RT_HAS_FCNTL_LCK
127   struct flock s_flock;
128 
129   s_flock.l_whence = SEEK_SET;
130   s_flock.l_start = 0;
131   s_flock.l_len = 0; /* Until EOF.  */
132   s_flock.l_pid = getpid();
133   s_flock.l_type = F_WRLCK;
134 
135   while (fcntl(fd, F_SETLKW, &s_flock) == -1) {
136     if (errno != EINTR) {
137       if (errno == ENOLCK) {
138         return -1;
139       }
140       break;
141     }
142   }
143   return 0;
144 #else
145   flock(fd, LOCK_EX);
146   return 0;
147 #endif
148 }
149 
150 COMPILER_RT_VISIBILITY int lprofUnlockFd(int fd) {
151 #ifdef COMPILER_RT_HAS_FCNTL_LCK
152   struct flock s_flock;
153 
154   s_flock.l_whence = SEEK_SET;
155   s_flock.l_start = 0;
156   s_flock.l_len = 0; /* Until EOF.  */
157   s_flock.l_pid = getpid();
158   s_flock.l_type = F_UNLCK;
159 
160   while (fcntl(fd, F_SETLKW, &s_flock) == -1) {
161     if (errno != EINTR) {
162       if (errno == ENOLCK) {
163         return -1;
164       }
165       break;
166     }
167   }
168   return 0;
169 #else
170   flock(fd, LOCK_UN);
171   return 0;
172 #endif
173 }
174 
175 COMPILER_RT_VISIBILITY int lprofLockFileHandle(FILE *F) {
176   int fd;
177 #if defined(_WIN32)
178   fd = _fileno(F);
179 #else
180   fd = fileno(F);
181 #endif
182   return lprofLockFd(fd);
183 }
184 
185 COMPILER_RT_VISIBILITY int lprofUnlockFileHandle(FILE *F) {
186   int fd;
187 #if defined(_WIN32)
188   fd = _fileno(F);
189 #else
190   fd = fileno(F);
191 #endif
192   return lprofUnlockFd(fd);
193 }
194 
195 COMPILER_RT_VISIBILITY FILE *lprofOpenFileEx(const char *ProfileName) {
196   FILE *f;
197   int fd;
198 #ifdef COMPILER_RT_HAS_FCNTL_LCK
199   fd = open(ProfileName, O_RDWR | O_CREAT, 0666);
200   if (fd < 0)
201     return NULL;
202 
203   if (lprofLockFd(fd) != 0)
204     PROF_WARN("Data may be corrupted during profile merging : %s\n",
205               "Fail to obtain file lock due to system limit.");
206 
207   f = fdopen(fd, "r+b");
208 #elif defined(_WIN32)
209   // FIXME: Use the wide variants to handle Unicode filenames.
210   HANDLE h = CreateFileA(ProfileName, GENERIC_READ | GENERIC_WRITE, 0, 0,
211                          OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
212   if (h == INVALID_HANDLE_VALUE)
213     return NULL;
214 
215   fd = _open_osfhandle((intptr_t)h, 0);
216   if (fd == -1) {
217     CloseHandle(h);
218     return NULL;
219   }
220 
221   f = _fdopen(fd, "r+b");
222   if (f == 0) {
223     CloseHandle(h);
224     return NULL;
225   }
226 #else
227   /* Worst case no locking applied.  */
228   PROF_WARN("Concurrent file access is not supported : %s\n",
229             "lack file locking");
230   fd = open(ProfileName, O_RDWR | O_CREAT, 0666);
231   if (fd < 0)
232     return NULL;
233   f = fdopen(fd, "r+b");
234 #endif
235 
236   return f;
237 }
238 
239 COMPILER_RT_VISIBILITY const char *lprofGetPathPrefix(int *PrefixStrip,
240                                                       size_t *PrefixLen) {
241   const char *Prefix = getenv("GCOV_PREFIX");
242   const char *PrefixStripStr = getenv("GCOV_PREFIX_STRIP");
243 
244   *PrefixLen = 0;
245   *PrefixStrip = 0;
246   if (Prefix == NULL || Prefix[0] == '\0')
247     return NULL;
248 
249   if (PrefixStripStr) {
250     *PrefixStrip = atoi(PrefixStripStr);
251 
252     /* Negative GCOV_PREFIX_STRIP values are ignored */
253     if (*PrefixStrip < 0)
254       *PrefixStrip = 0;
255   } else {
256     *PrefixStrip = 0;
257   }
258   *PrefixLen = strlen(Prefix);
259 
260   return Prefix;
261 }
262 
263 COMPILER_RT_VISIBILITY void
264 lprofApplyPathPrefix(char *Dest, const char *PathStr, const char *Prefix,
265                      size_t PrefixLen, int PrefixStrip) {
266 
267   const char *Ptr;
268   int Level;
269   const char *StrippedPathStr = PathStr;
270 
271   for (Level = 0, Ptr = PathStr + 1; Level < PrefixStrip; ++Ptr) {
272     if (*Ptr == '\0')
273       break;
274 
275     if (!IS_DIR_SEPARATOR(*Ptr))
276       continue;
277 
278     StrippedPathStr = Ptr;
279     ++Level;
280   }
281 
282   memcpy(Dest, Prefix, PrefixLen);
283 
284   if (!IS_DIR_SEPARATOR(Prefix[PrefixLen - 1]))
285     Dest[PrefixLen++] = DIR_SEPARATOR;
286 
287   memcpy(Dest + PrefixLen, StrippedPathStr, strlen(StrippedPathStr) + 1);
288 }
289 
290 COMPILER_RT_VISIBILITY const char *
291 lprofFindFirstDirSeparator(const char *Path) {
292   const char *Sep = strchr(Path, DIR_SEPARATOR);
293 #if defined(DIR_SEPARATOR_2)
294   const char *Sep2 = strchr(Path, DIR_SEPARATOR_2);
295   if (Sep2 && (!Sep || Sep2 < Sep))
296     Sep = Sep2;
297 #endif
298   return Sep;
299 }
300 
301 COMPILER_RT_VISIBILITY const char *lprofFindLastDirSeparator(const char *Path) {
302   const char *Sep = strrchr(Path, DIR_SEPARATOR);
303 #if defined(DIR_SEPARATOR_2)
304   const char *Sep2 = strrchr(Path, DIR_SEPARATOR_2);
305   if (Sep2 && (!Sep || Sep2 > Sep))
306     Sep = Sep2;
307 #endif
308   return Sep;
309 }
310 
311 COMPILER_RT_VISIBILITY int lprofSuspendSigKill() {
312 #if defined(__linux__)
313   int PDeachSig = 0;
314   /* Temporarily suspend getting SIGKILL upon exit of the parent process. */
315   if (prctl(PR_GET_PDEATHSIG, &PDeachSig) == 0 && PDeachSig == SIGKILL)
316     prctl(PR_SET_PDEATHSIG, 0);
317   return (PDeachSig == SIGKILL);
318 #else
319   return 0;
320 #endif
321 }
322 
323 COMPILER_RT_VISIBILITY void lprofRestoreSigKill() {
324 #if defined(__linux__)
325   prctl(PR_SET_PDEATHSIG, SIGKILL);
326 #endif
327 }
328