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