1 /*===- InstrProfilingFile.c - Write instrumentation to a file -------------===*\
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 #if !defined(__Fuchsia__)
10 
11 #include <assert.h>
12 #include <errno.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #ifdef _MSC_VER
17 /* For _alloca. */
18 #include <malloc.h>
19 #endif
20 #if defined(_WIN32)
21 #include "WindowsMMap.h"
22 /* For _chsize_s */
23 #include <io.h>
24 #include <process.h>
25 #else
26 #include <sys/file.h>
27 #include <sys/mman.h>
28 #include <unistd.h>
29 #if defined(__linux__)
30 #include <sys/types.h>
31 #endif
32 #endif
33 
34 #include "InstrProfiling.h"
35 #include "InstrProfilingInternal.h"
36 #include "InstrProfilingPort.h"
37 #include "InstrProfilingUtil.h"
38 
39 /* From where is profile name specified.
40  * The order the enumerators define their
41  * precedence. Re-order them may lead to
42  * runtime behavior change. */
43 typedef enum ProfileNameSpecifier {
44   PNS_unknown = 0,
45   PNS_default,
46   PNS_command_line,
47   PNS_environment,
48   PNS_runtime_api
49 } ProfileNameSpecifier;
50 
51 static const char *getPNSStr(ProfileNameSpecifier PNS) {
52   switch (PNS) {
53   case PNS_default:
54     return "default setting";
55   case PNS_command_line:
56     return "command line";
57   case PNS_environment:
58     return "environment variable";
59   case PNS_runtime_api:
60     return "runtime API";
61   default:
62     return "Unknown";
63   }
64 }
65 
66 #define MAX_PID_SIZE 16
67 /* Data structure holding the result of parsed filename pattern. */
68 typedef struct lprofFilename {
69   /* File name string possibly with %p or %h specifiers. */
70   const char *FilenamePat;
71   /* A flag indicating if FilenamePat's memory is allocated
72    * by runtime. */
73   unsigned OwnsFilenamePat;
74   const char *ProfilePathPrefix;
75   char PidChars[MAX_PID_SIZE];
76   char *TmpDir;
77   char Hostname[COMPILER_RT_MAX_HOSTLEN];
78   unsigned NumPids;
79   unsigned NumHosts;
80   /* When in-process merging is enabled, this parameter specifies
81    * the total number of profile data files shared by all the processes
82    * spawned from the same binary. By default the value is 1. If merging
83    * is not enabled, its value should be 0. This parameter is specified
84    * by the %[0-9]m specifier. For instance %2m enables merging using
85    * 2 profile data files. %1m is equivalent to %m. Also %m specifier
86    * can only appear once at the end of the name pattern. */
87   unsigned MergePoolSize;
88   ProfileNameSpecifier PNS;
89 } lprofFilename;
90 
91 static lprofFilename lprofCurFilename = {0,   0, 0, {0}, NULL,
92                                          {0}, 0, 0, 0,   PNS_unknown};
93 
94 static int ProfileMergeRequested = 0;
95 static int isProfileMergeRequested() { return ProfileMergeRequested; }
96 static void setProfileMergeRequested(int EnableMerge) {
97   ProfileMergeRequested = EnableMerge;
98 }
99 
100 static FILE *ProfileFile = NULL;
101 static FILE *getProfileFile() { return ProfileFile; }
102 static void setProfileFile(FILE *File) { ProfileFile = File; }
103 
104 COMPILER_RT_VISIBILITY void __llvm_profile_set_file_object(FILE *File,
105                                                            int EnableMerge) {
106   if (__llvm_profile_is_continuous_mode_enabled()) {
107     PROF_WARN("__llvm_profile_set_file_object(fd=%d) not supported, because "
108               "continuous sync mode (%%c) is enabled",
109               fileno(File));
110     return;
111   }
112   setProfileFile(File);
113   setProfileMergeRequested(EnableMerge);
114 }
115 
116 static int getCurFilenameLength();
117 static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf);
118 static unsigned doMerging() {
119   return lprofCurFilename.MergePoolSize || isProfileMergeRequested();
120 }
121 
122 /* Return 1 if there is an error, otherwise return  0.  */
123 static uint32_t fileWriter(ProfDataWriter *This, ProfDataIOVec *IOVecs,
124                            uint32_t NumIOVecs) {
125   uint32_t I;
126   FILE *File = (FILE *)This->WriterCtx;
127   char Zeroes[sizeof(uint64_t)] = {0};
128   for (I = 0; I < NumIOVecs; I++) {
129     if (IOVecs[I].Data) {
130       if (fwrite(IOVecs[I].Data, IOVecs[I].ElmSize, IOVecs[I].NumElm, File) !=
131           IOVecs[I].NumElm)
132         return 1;
133     } else if (IOVecs[I].UseZeroPadding) {
134       size_t BytesToWrite = IOVecs[I].ElmSize * IOVecs[I].NumElm;
135       while (BytesToWrite > 0) {
136         size_t PartialWriteLen =
137             (sizeof(uint64_t) > BytesToWrite) ? BytesToWrite : sizeof(uint64_t);
138         if (fwrite(Zeroes, sizeof(uint8_t), PartialWriteLen, File) !=
139             PartialWriteLen) {
140           return 1;
141         }
142         BytesToWrite -= PartialWriteLen;
143       }
144     } else {
145       if (fseek(File, IOVecs[I].ElmSize * IOVecs[I].NumElm, SEEK_CUR) == -1)
146         return 1;
147     }
148   }
149   return 0;
150 }
151 
152 /* TODO: make buffer size controllable by an internal option, and compiler can pass the size
153    to runtime via a variable. */
154 static uint32_t orderFileWriter(FILE *File, const uint32_t *DataStart) {
155   if (fwrite(DataStart, sizeof(uint32_t), INSTR_ORDER_FILE_BUFFER_SIZE, File) !=
156       INSTR_ORDER_FILE_BUFFER_SIZE)
157     return 1;
158   return 0;
159 }
160 
161 static void initFileWriter(ProfDataWriter *This, FILE *File) {
162   This->Write = fileWriter;
163   This->WriterCtx = File;
164 }
165 
166 COMPILER_RT_VISIBILITY ProfBufferIO *
167 lprofCreateBufferIOInternal(void *File, uint32_t BufferSz) {
168   FreeHook = &free;
169   DynamicBufferIOBuffer = (uint8_t *)calloc(BufferSz, 1);
170   VPBufferSize = BufferSz;
171   ProfDataWriter *fileWriter =
172       (ProfDataWriter *)calloc(sizeof(ProfDataWriter), 1);
173   initFileWriter(fileWriter, File);
174   ProfBufferIO *IO = lprofCreateBufferIO(fileWriter);
175   IO->OwnFileWriter = 1;
176   return IO;
177 }
178 
179 static void setupIOBuffer() {
180   const char *BufferSzStr = 0;
181   BufferSzStr = getenv("LLVM_VP_BUFFER_SIZE");
182   if (BufferSzStr && BufferSzStr[0]) {
183     VPBufferSize = atoi(BufferSzStr);
184     DynamicBufferIOBuffer = (uint8_t *)calloc(VPBufferSize, 1);
185   }
186 }
187 
188 /* Get the size of the profile file. If there are any errors, print the
189  * message under the assumption that the profile is being read for merging
190  * purposes, and return -1. Otherwise return the file size in the inout param
191  * \p ProfileFileSize. */
192 static int getProfileFileSizeForMerging(FILE *ProfileFile,
193                                         uint64_t *ProfileFileSize) {
194   if (fseek(ProfileFile, 0L, SEEK_END) == -1) {
195     PROF_ERR("Unable to merge profile data, unable to get size: %s\n",
196              strerror(errno));
197     return -1;
198   }
199   *ProfileFileSize = ftell(ProfileFile);
200 
201   /* Restore file offset.  */
202   if (fseek(ProfileFile, 0L, SEEK_SET) == -1) {
203     PROF_ERR("Unable to merge profile data, unable to rewind: %s\n",
204              strerror(errno));
205     return -1;
206   }
207 
208   if (*ProfileFileSize > 0 &&
209       *ProfileFileSize < sizeof(__llvm_profile_header)) {
210     PROF_WARN("Unable to merge profile data: %s\n",
211               "source profile file is too small.");
212     return -1;
213   }
214   return 0;
215 }
216 
217 /* mmap() \p ProfileFile for profile merging purposes, assuming that an
218  * exclusive lock is held on the file and that \p ProfileFileSize is the
219  * length of the file. Return the mmap'd buffer in the inout variable
220  * \p ProfileBuffer. Returns -1 on failure. On success, the caller is
221  * responsible for unmapping the mmap'd buffer in \p ProfileBuffer. */
222 static int mmapProfileForMerging(FILE *ProfileFile, uint64_t ProfileFileSize,
223                                  char **ProfileBuffer) {
224   *ProfileBuffer = mmap(NULL, ProfileFileSize, PROT_READ, MAP_SHARED | MAP_FILE,
225                         fileno(ProfileFile), 0);
226   if (*ProfileBuffer == MAP_FAILED) {
227     PROF_ERR("Unable to merge profile data, mmap failed: %s\n",
228              strerror(errno));
229     return -1;
230   }
231 
232   if (__llvm_profile_check_compatibility(*ProfileBuffer, ProfileFileSize)) {
233     (void)munmap(*ProfileBuffer, ProfileFileSize);
234     PROF_WARN("Unable to merge profile data: %s\n",
235               "source profile file is not compatible.");
236     return -1;
237   }
238   return 0;
239 }
240 
241 /* Read profile data in \c ProfileFile and merge with in-memory
242    profile counters. Returns -1 if there is fatal error, otheriwse
243    0 is returned. Returning 0 does not mean merge is actually
244    performed. If merge is actually done, *MergeDone is set to 1.
245 */
246 static int doProfileMerging(FILE *ProfileFile, int *MergeDone) {
247   uint64_t ProfileFileSize;
248   char *ProfileBuffer;
249 
250   /* Get the size of the profile on disk. */
251   if (getProfileFileSizeForMerging(ProfileFile, &ProfileFileSize) == -1)
252     return -1;
253 
254   /* Nothing to merge.  */
255   if (!ProfileFileSize)
256     return 0;
257 
258   /* mmap() the profile and check that it is compatible with the data in
259    * the current image. */
260   if (mmapProfileForMerging(ProfileFile, ProfileFileSize, &ProfileBuffer) == -1)
261     return -1;
262 
263   /* Now start merging */
264   if (__llvm_profile_merge_from_buffer(ProfileBuffer, ProfileFileSize)) {
265     PROF_ERR("%s\n", "Invalid profile data to merge");
266     (void)munmap(ProfileBuffer, ProfileFileSize);
267     return -1;
268   }
269 
270   // Truncate the file in case merging of value profile did not happen to
271   // prevent from leaving garbage data at the end of the profile file.
272   (void)COMPILER_RT_FTRUNCATE(ProfileFile,
273                               __llvm_profile_get_size_for_buffer());
274 
275   (void)munmap(ProfileBuffer, ProfileFileSize);
276   *MergeDone = 1;
277 
278   return 0;
279 }
280 
281 /* Create the directory holding the file, if needed. */
282 static void createProfileDir(const char *Filename) {
283   size_t Length = strlen(Filename);
284   if (lprofFindFirstDirSeparator(Filename)) {
285     char *Copy = (char *)COMPILER_RT_ALLOCA(Length + 1);
286     strncpy(Copy, Filename, Length + 1);
287     __llvm_profile_recursive_mkdir(Copy);
288   }
289 }
290 
291 /* Open the profile data for merging. It opens the file in r+b mode with
292  * file locking.  If the file has content which is compatible with the
293  * current process, it also reads in the profile data in the file and merge
294  * it with in-memory counters. After the profile data is merged in memory,
295  * the original profile data is truncated and gets ready for the profile
296  * dumper. With profile merging enabled, each executable as well as any of
297  * its instrumented shared libraries dump profile data into their own data file.
298 */
299 static FILE *openFileForMerging(const char *ProfileFileName, int *MergeDone) {
300   FILE *ProfileFile = NULL;
301   int rc;
302 
303   ProfileFile = getProfileFile();
304   if (ProfileFile) {
305     lprofLockFileHandle(ProfileFile);
306   } else {
307     createProfileDir(ProfileFileName);
308     ProfileFile = lprofOpenFileEx(ProfileFileName);
309   }
310   if (!ProfileFile)
311     return NULL;
312 
313   rc = doProfileMerging(ProfileFile, MergeDone);
314   if (rc || (!*MergeDone && COMPILER_RT_FTRUNCATE(ProfileFile, 0L)) ||
315       fseek(ProfileFile, 0L, SEEK_SET) == -1) {
316     PROF_ERR("Profile Merging of file %s failed: %s\n", ProfileFileName,
317              strerror(errno));
318     fclose(ProfileFile);
319     return NULL;
320   }
321   return ProfileFile;
322 }
323 
324 static FILE *getFileObject(const char *OutputName) {
325   FILE *File;
326   File = getProfileFile();
327   if (File != NULL) {
328     return File;
329   }
330 
331   return fopen(OutputName, "ab");
332 }
333 
334 /* Write profile data to file \c OutputName.  */
335 static int writeFile(const char *OutputName) {
336   int RetVal;
337   FILE *OutputFile;
338 
339   int MergeDone = 0;
340   VPMergeHook = &lprofMergeValueProfData;
341   if (doMerging())
342     OutputFile = openFileForMerging(OutputName, &MergeDone);
343   else
344     OutputFile = getFileObject(OutputName);
345 
346   if (!OutputFile)
347     return -1;
348 
349   FreeHook = &free;
350   setupIOBuffer();
351   ProfDataWriter fileWriter;
352   initFileWriter(&fileWriter, OutputFile);
353   RetVal = lprofWriteData(&fileWriter, lprofGetVPDataReader(), MergeDone);
354 
355   if (OutputFile == getProfileFile()) {
356     fflush(OutputFile);
357     if (doMerging()) {
358       lprofUnlockFileHandle(OutputFile);
359     }
360   } else {
361     fclose(OutputFile);
362   }
363 
364   return RetVal;
365 }
366 
367 /* Write order data to file \c OutputName.  */
368 static int writeOrderFile(const char *OutputName) {
369   int RetVal;
370   FILE *OutputFile;
371 
372   OutputFile = fopen(OutputName, "w");
373 
374   if (!OutputFile) {
375     PROF_WARN("can't open file with mode ab: %s\n", OutputName);
376     return -1;
377   }
378 
379   FreeHook = &free;
380   setupIOBuffer();
381   const uint32_t *DataBegin = __llvm_profile_begin_orderfile();
382   RetVal = orderFileWriter(OutputFile, DataBegin);
383 
384   fclose(OutputFile);
385   return RetVal;
386 }
387 
388 #define LPROF_INIT_ONCE_ENV "__LLVM_PROFILE_RT_INIT_ONCE"
389 
390 static void truncateCurrentFile(void) {
391   const char *Filename;
392   char *FilenameBuf;
393   FILE *File;
394   int Length;
395 
396   Length = getCurFilenameLength();
397   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
398   Filename = getCurFilename(FilenameBuf, 0);
399   if (!Filename)
400     return;
401 
402   /* Only create the profile directory and truncate an existing profile once.
403    * In continuous mode, this is necessary, as the profile is written-to by the
404    * runtime initializer. */
405   int initialized = getenv(LPROF_INIT_ONCE_ENV) != NULL;
406   if (initialized)
407     return;
408 #if defined(_WIN32)
409   _putenv(LPROF_INIT_ONCE_ENV "=" LPROF_INIT_ONCE_ENV);
410 #else
411   setenv(LPROF_INIT_ONCE_ENV, LPROF_INIT_ONCE_ENV, 1);
412 #endif
413 
414   /* Create the profile dir (even if online merging is enabled), so that
415    * the profile file can be set up if continuous mode is enabled. */
416   createProfileDir(Filename);
417 
418   /* By pass file truncation to allow online raw profile merging. */
419   if (lprofCurFilename.MergePoolSize)
420     return;
421 
422   /* Truncate the file.  Later we'll reopen and append. */
423   File = fopen(Filename, "w");
424   if (!File)
425     return;
426   fclose(File);
427 }
428 
429 #if !defined(__Fuchsia__) && !defined(_WIN32)
430 static void assertIsZero(int *i) {
431   if (*i)
432     PROF_WARN("Expected flag to be 0, but got: %d\n", *i);
433 }
434 
435 /* Write a partial profile to \p Filename, which is required to be backed by
436  * the open file object \p File. */
437 static int writeProfileWithFileObject(const char *Filename, FILE *File) {
438   setProfileFile(File);
439   int rc = writeFile(Filename);
440   if (rc)
441     PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));
442   setProfileFile(NULL);
443   return rc;
444 }
445 
446 /* Unlock the profile \p File and clear the unlock flag. */
447 static void unlockProfile(int *ProfileRequiresUnlock, FILE *File) {
448   if (!*ProfileRequiresUnlock) {
449     PROF_WARN("%s", "Expected to require profile unlock\n");
450   }
451   lprofUnlockFileHandle(File);
452   *ProfileRequiresUnlock = 0;
453 }
454 #endif // !defined(__Fuchsia__) && !defined(_WIN32)
455 
456 static int writeMMappedFile(FILE *OutputFile, char **Profile) {
457   if (!OutputFile)
458     return -1;
459 
460   /* Write the data into a file. */
461   setupIOBuffer();
462   ProfDataWriter fileWriter;
463   initFileWriter(&fileWriter, OutputFile);
464   if (lprofWriteData(&fileWriter, NULL, 0)) {
465     PROF_ERR("Failed to write profile: %s\n", strerror(errno));
466     return -1;
467   }
468   fflush(OutputFile);
469 
470   /* Get the file size. */
471   uint64_t FileSize = ftell(OutputFile);
472 
473   /* Map the profile. */
474   *Profile = (char *)mmap(
475       NULL, FileSize, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(OutputFile), 0);
476   if (*Profile == MAP_FAILED) {
477     PROF_ERR("Unable to mmap profile: %s\n", strerror(errno));
478     return -1;
479   }
480 
481   return 0;
482 }
483 
484 static void relocateCounters(void) {
485   if (!__llvm_profile_is_continuous_mode_enabled() ||
486       !lprofRuntimeCounterRelocation())
487     return;
488 
489   /* Get the sizes of various profile data sections. Taken from
490    * __llvm_profile_get_size_for_buffer(). */
491   const __llvm_profile_data *DataBegin = __llvm_profile_begin_data();
492   const __llvm_profile_data *DataEnd = __llvm_profile_end_data();
493   uint64_t DataSize = __llvm_profile_get_data_size(DataBegin, DataEnd);
494   const uint64_t CountersOffset = sizeof(__llvm_profile_header) +
495       (DataSize * sizeof(__llvm_profile_data));
496 
497   int Length = getCurFilenameLength();
498   char *FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
499   const char *Filename = getCurFilename(FilenameBuf, 0);
500   if (!Filename)
501     return;
502 
503   FILE *File = NULL;
504   char *Profile = NULL;
505 
506   if (!doMerging()) {
507     File = fopen(Filename, "w+b");
508     if (!File)
509       return;
510 
511     if (writeMMappedFile(File, &Profile) == -1) {
512       fclose(File);
513       return;
514     }
515   } else {
516     File = lprofOpenFileEx(Filename);
517     if (!File)
518       return;
519 
520     uint64_t ProfileFileSize = 0;
521     if (getProfileFileSizeForMerging(File, &ProfileFileSize) == -1) {
522       lprofUnlockFileHandle(File);
523       fclose(File);
524       return;
525     }
526 
527     if (!ProfileFileSize) {
528       if (writeMMappedFile(File, &Profile) == -1) {
529         fclose(File);
530         return;
531       }
532     } else {
533       /* The merged profile has a non-zero length. Check that it is compatible
534        * with the data in this process. */
535       if (mmapProfileForMerging(File, ProfileFileSize, &Profile) == -1) {
536         fclose(File);
537         return;
538       }
539     }
540 
541     lprofUnlockFileHandle(File);
542   }
543 
544   /* Update the profile fields based on the current mapping. */
545   __llvm_profile_counter_bias = (intptr_t)Profile -
546       (uintptr_t)__llvm_profile_begin_counters() + CountersOffset;
547 }
548 
549 static void initializeProfileForContinuousMode(void) {
550   if (!__llvm_profile_is_continuous_mode_enabled())
551     return;
552 
553 #if defined(__Fuchsia__) || defined(_WIN32)
554   PROF_ERR("%s\n", "Continuous mode not yet supported on Fuchsia or Windows.");
555 #else // defined(__Fuchsia__) || defined(_WIN32)
556   /* Get the sizes of various profile data sections. Taken from
557    * __llvm_profile_get_size_for_buffer(). */
558   const __llvm_profile_data *DataBegin = __llvm_profile_begin_data();
559   const __llvm_profile_data *DataEnd = __llvm_profile_end_data();
560   const uint64_t *CountersBegin = __llvm_profile_begin_counters();
561   const uint64_t *CountersEnd = __llvm_profile_end_counters();
562   const char *NamesBegin = __llvm_profile_begin_names();
563   const char *NamesEnd = __llvm_profile_end_names();
564   const uint64_t NamesSize = (NamesEnd - NamesBegin) * sizeof(char);
565   uint64_t DataSize = __llvm_profile_get_data_size(DataBegin, DataEnd);
566   uint64_t CountersSize = CountersEnd - CountersBegin;
567 
568   /* Check that the counter and data sections in this image are page-aligned. */
569   unsigned PageSize = getpagesize();
570   if ((intptr_t)CountersBegin % PageSize != 0) {
571     PROF_ERR("Counters section not page-aligned (start = %p, pagesz = %u).\n",
572              CountersBegin, PageSize);
573     return;
574   }
575   if ((intptr_t)DataBegin % PageSize != 0) {
576     PROF_ERR("Data section not page-aligned (start = %p, pagesz = %u).\n",
577              DataBegin, PageSize);
578     return;
579   }
580 
581   int Length = getCurFilenameLength();
582   char *FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
583   const char *Filename = getCurFilename(FilenameBuf, 0);
584   if (!Filename)
585     return;
586 
587   FILE *File = NULL;
588   off_t CurrentFileOffset = 0;
589   off_t OffsetModPage = 0;
590 
591   /* Whether an exclusive lock on the profile must be dropped after init.
592    * Use a cleanup to warn if the unlock does not occur. */
593   COMPILER_RT_CLEANUP(assertIsZero) int ProfileRequiresUnlock = 0;
594 
595   if (!doMerging()) {
596     /* We are not merging profiles, so open the raw profile in append mode. */
597     File = fopen(Filename, "a+b");
598     if (!File)
599       return;
600 
601     /* Check that the offset within the file is page-aligned. */
602     CurrentFileOffset = ftello(File);
603     OffsetModPage = CurrentFileOffset % PageSize;
604     if (OffsetModPage != 0) {
605       PROF_ERR("Continuous counter sync mode is enabled, but raw profile is not"
606                "page-aligned. CurrentFileOffset = %" PRIu64 ", pagesz = %u.\n",
607                (uint64_t)CurrentFileOffset, PageSize);
608       return;
609     }
610 
611     /* Grow the profile so that mmap() can succeed.  Leak the file handle, as
612      * the file should stay open. */
613     if (writeProfileWithFileObject(Filename, File) != 0)
614       return;
615   } else {
616     /* We are merging profiles. Map the counter section as shared memory into
617      * the profile, i.e. into each participating process. An increment in one
618      * process should be visible to every other process with the same counter
619      * section mapped. */
620     File = lprofOpenFileEx(Filename);
621     if (!File)
622       return;
623 
624     ProfileRequiresUnlock = 1;
625 
626     uint64_t ProfileFileSize;
627     if (getProfileFileSizeForMerging(File, &ProfileFileSize) == -1)
628       return unlockProfile(&ProfileRequiresUnlock, File);
629 
630     if (ProfileFileSize == 0) {
631       /* Grow the profile so that mmap() can succeed.  Leak the file handle, as
632        * the file should stay open. */
633       if (writeProfileWithFileObject(Filename, File) != 0)
634         return unlockProfile(&ProfileRequiresUnlock, File);
635     } else {
636       /* The merged profile has a non-zero length. Check that it is compatible
637        * with the data in this process. */
638       char *ProfileBuffer;
639       if (mmapProfileForMerging(File, ProfileFileSize, &ProfileBuffer) == -1 ||
640           munmap(ProfileBuffer, ProfileFileSize) == -1)
641         return unlockProfile(&ProfileRequiresUnlock, File);
642     }
643   }
644 
645   /* mmap() the profile counters so long as there is at least one counter.
646    * If there aren't any counters, mmap() would fail with EINVAL. */
647   if (CountersSize > 0) {
648     int Fileno = fileno(File);
649 
650     /* Determine how much padding is needed before/after the counters and after
651      * the names. */
652     uint64_t PaddingBytesBeforeCounters, PaddingBytesAfterCounters,
653         PaddingBytesAfterNames;
654     __llvm_profile_get_padding_sizes_for_counters(
655         DataSize, CountersSize, NamesSize, &PaddingBytesBeforeCounters,
656         &PaddingBytesAfterCounters, &PaddingBytesAfterNames);
657 
658     uint64_t PageAlignedCountersLength =
659         (CountersSize * sizeof(uint64_t)) + PaddingBytesAfterCounters;
660     uint64_t FileOffsetToCounters =
661         CurrentFileOffset + sizeof(__llvm_profile_header) +
662         (DataSize * sizeof(__llvm_profile_data)) + PaddingBytesBeforeCounters;
663 
664     uint64_t *CounterMmap = (uint64_t *)mmap(
665         (void *)CountersBegin, PageAlignedCountersLength, PROT_READ | PROT_WRITE,
666         MAP_FIXED | MAP_SHARED, Fileno, FileOffsetToCounters);
667     if (CounterMmap != CountersBegin) {
668       PROF_ERR(
669           "Continuous counter sync mode is enabled, but mmap() failed (%s).\n"
670           "  - CountersBegin: %p\n"
671           "  - PageAlignedCountersLength: %" PRIu64 "\n"
672           "  - Fileno: %d\n"
673           "  - FileOffsetToCounters: %" PRIu64 "\n",
674           strerror(errno), CountersBegin, PageAlignedCountersLength, Fileno,
675           FileOffsetToCounters);
676     }
677   }
678 
679   if (ProfileRequiresUnlock)
680     unlockProfile(&ProfileRequiresUnlock, File);
681 #endif // defined(__Fuchsia__) || defined(_WIN32)
682 }
683 
684 static const char *DefaultProfileName = "default.profraw";
685 static void resetFilenameToDefault(void) {
686   if (lprofCurFilename.FilenamePat && lprofCurFilename.OwnsFilenamePat) {
687     free((void *)lprofCurFilename.FilenamePat);
688   }
689   memset(&lprofCurFilename, 0, sizeof(lprofCurFilename));
690   lprofCurFilename.FilenamePat = DefaultProfileName;
691   lprofCurFilename.PNS = PNS_default;
692 }
693 
694 static unsigned getMergePoolSize(const char *FilenamePat, int *I) {
695   unsigned J = 0, Num = 0;
696   for (;; ++J) {
697     char C = FilenamePat[*I + J];
698     if (C == 'm') {
699       *I += J;
700       return Num ? Num : 1;
701     }
702     if (C < '0' || C > '9')
703       break;
704     Num = Num * 10 + C - '0';
705 
706     /* If FilenamePat[*I+J] is between '0' and '9', the next byte is guaranteed
707      * to be in-bound as the string is null terminated. */
708   }
709   return 0;
710 }
711 
712 /* Assert that Idx does index past a string null terminator. Return the
713  * result of the check. */
714 static int checkBounds(int Idx, int Strlen) {
715   assert(Idx <= Strlen && "Indexing past string null terminator");
716   return Idx <= Strlen;
717 }
718 
719 /* Parses the pattern string \p FilenamePat and stores the result to
720  * lprofcurFilename structure. */
721 static int parseFilenamePattern(const char *FilenamePat,
722                                 unsigned CopyFilenamePat) {
723   int NumPids = 0, NumHosts = 0, I;
724   char *PidChars = &lprofCurFilename.PidChars[0];
725   char *Hostname = &lprofCurFilename.Hostname[0];
726   int MergingEnabled = 0;
727   int FilenamePatLen = strlen(FilenamePat);
728 
729   /* Clean up cached prefix and filename.  */
730   if (lprofCurFilename.ProfilePathPrefix)
731     free((void *)lprofCurFilename.ProfilePathPrefix);
732 
733   if (lprofCurFilename.FilenamePat && lprofCurFilename.OwnsFilenamePat) {
734     free((void *)lprofCurFilename.FilenamePat);
735   }
736 
737   memset(&lprofCurFilename, 0, sizeof(lprofCurFilename));
738 
739   if (!CopyFilenamePat)
740     lprofCurFilename.FilenamePat = FilenamePat;
741   else {
742     lprofCurFilename.FilenamePat = strdup(FilenamePat);
743     lprofCurFilename.OwnsFilenamePat = 1;
744   }
745   /* Check the filename for "%p", which indicates a pid-substitution. */
746   for (I = 0; checkBounds(I, FilenamePatLen) && FilenamePat[I]; ++I) {
747     if (FilenamePat[I] == '%') {
748       ++I; /* Advance to the next character. */
749       if (!checkBounds(I, FilenamePatLen))
750         break;
751       if (FilenamePat[I] == 'p') {
752         if (!NumPids++) {
753           if (snprintf(PidChars, MAX_PID_SIZE, "%ld", (long)getpid()) <= 0) {
754             PROF_WARN("Unable to get pid for filename pattern %s. Using the "
755                       "default name.",
756                       FilenamePat);
757             return -1;
758           }
759         }
760       } else if (FilenamePat[I] == 'h') {
761         if (!NumHosts++)
762           if (COMPILER_RT_GETHOSTNAME(Hostname, COMPILER_RT_MAX_HOSTLEN)) {
763             PROF_WARN("Unable to get hostname for filename pattern %s. Using "
764                       "the default name.",
765                       FilenamePat);
766             return -1;
767           }
768       } else if (FilenamePat[I] == 't') {
769         lprofCurFilename.TmpDir = getenv("TMPDIR");
770         if (!lprofCurFilename.TmpDir) {
771           PROF_WARN("Unable to get the TMPDIR environment variable, referenced "
772                     "in %s. Using the default path.",
773                     FilenamePat);
774           return -1;
775         }
776       } else if (FilenamePat[I] == 'c') {
777         if (__llvm_profile_is_continuous_mode_enabled()) {
778           PROF_WARN("%%c specifier can only be specified once in %s.\n",
779                     FilenamePat);
780           return -1;
781         }
782 
783         __llvm_profile_set_page_size(getpagesize());
784         __llvm_profile_enable_continuous_mode();
785       } else {
786         unsigned MergePoolSize = getMergePoolSize(FilenamePat, &I);
787         if (!MergePoolSize)
788           continue;
789         if (MergingEnabled) {
790           PROF_WARN("%%m specifier can only be specified once in %s.\n",
791                     FilenamePat);
792           return -1;
793         }
794         MergingEnabled = 1;
795         lprofCurFilename.MergePoolSize = MergePoolSize;
796       }
797     }
798   }
799 
800   lprofCurFilename.NumPids = NumPids;
801   lprofCurFilename.NumHosts = NumHosts;
802   return 0;
803 }
804 
805 static void parseAndSetFilename(const char *FilenamePat,
806                                 ProfileNameSpecifier PNS,
807                                 unsigned CopyFilenamePat) {
808 
809   const char *OldFilenamePat = lprofCurFilename.FilenamePat;
810   ProfileNameSpecifier OldPNS = lprofCurFilename.PNS;
811 
812   /* The old profile name specifier takes precedence over the old one. */
813   if (PNS < OldPNS)
814     return;
815 
816   if (!FilenamePat)
817     FilenamePat = DefaultProfileName;
818 
819   if (OldFilenamePat && !strcmp(OldFilenamePat, FilenamePat)) {
820     lprofCurFilename.PNS = PNS;
821     return;
822   }
823 
824   /* When PNS >= OldPNS, the last one wins. */
825   if (!FilenamePat || parseFilenamePattern(FilenamePat, CopyFilenamePat))
826     resetFilenameToDefault();
827   lprofCurFilename.PNS = PNS;
828 
829   if (!OldFilenamePat) {
830     if (getenv("LLVM_PROFILE_VERBOSE"))
831       PROF_NOTE("Set profile file path to \"%s\" via %s.\n",
832                 lprofCurFilename.FilenamePat, getPNSStr(PNS));
833   } else {
834     if (getenv("LLVM_PROFILE_VERBOSE"))
835       PROF_NOTE("Override old profile path \"%s\" via %s to \"%s\" via %s.\n",
836                 OldFilenamePat, getPNSStr(OldPNS), lprofCurFilename.FilenamePat,
837                 getPNSStr(PNS));
838   }
839 
840   truncateCurrentFile();
841   if (__llvm_profile_is_continuous_mode_enabled()) {
842     if (lprofRuntimeCounterRelocation())
843       relocateCounters();
844     else
845       initializeProfileForContinuousMode();
846   }
847 }
848 
849 /* Return buffer length that is required to store the current profile
850  * filename with PID and hostname substitutions. */
851 /* The length to hold uint64_t followed by 3 digits pool id including '_' */
852 #define SIGLEN 24
853 static int getCurFilenameLength() {
854   int Len;
855   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
856     return 0;
857 
858   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
859         lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize))
860     return strlen(lprofCurFilename.FilenamePat);
861 
862   Len = strlen(lprofCurFilename.FilenamePat) +
863         lprofCurFilename.NumPids * (strlen(lprofCurFilename.PidChars) - 2) +
864         lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2) +
865         (lprofCurFilename.TmpDir ? (strlen(lprofCurFilename.TmpDir) - 1) : 0);
866   if (lprofCurFilename.MergePoolSize)
867     Len += SIGLEN;
868   return Len;
869 }
870 
871 /* Return the pointer to the current profile file name (after substituting
872  * PIDs and Hostnames in filename pattern. \p FilenameBuf is the buffer
873  * to store the resulting filename. If no substitution is needed, the
874  * current filename pattern string is directly returned, unless ForceUseBuf
875  * is enabled. */
876 static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
877   int I, J, PidLength, HostNameLength, TmpDirLength, FilenamePatLength;
878   const char *FilenamePat = lprofCurFilename.FilenamePat;
879 
880   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
881     return 0;
882 
883   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
884         lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize ||
885         __llvm_profile_is_continuous_mode_enabled())) {
886     if (!ForceUseBuf)
887       return lprofCurFilename.FilenamePat;
888 
889     FilenamePatLength = strlen(lprofCurFilename.FilenamePat);
890     memcpy(FilenameBuf, lprofCurFilename.FilenamePat, FilenamePatLength);
891     FilenameBuf[FilenamePatLength] = '\0';
892     return FilenameBuf;
893   }
894 
895   PidLength = strlen(lprofCurFilename.PidChars);
896   HostNameLength = strlen(lprofCurFilename.Hostname);
897   TmpDirLength = lprofCurFilename.TmpDir ? strlen(lprofCurFilename.TmpDir) : 0;
898   /* Construct the new filename. */
899   for (I = 0, J = 0; FilenamePat[I]; ++I)
900     if (FilenamePat[I] == '%') {
901       if (FilenamePat[++I] == 'p') {
902         memcpy(FilenameBuf + J, lprofCurFilename.PidChars, PidLength);
903         J += PidLength;
904       } else if (FilenamePat[I] == 'h') {
905         memcpy(FilenameBuf + J, lprofCurFilename.Hostname, HostNameLength);
906         J += HostNameLength;
907       } else if (FilenamePat[I] == 't') {
908         memcpy(FilenameBuf + J, lprofCurFilename.TmpDir, TmpDirLength);
909         FilenameBuf[J + TmpDirLength] = DIR_SEPARATOR;
910         J += TmpDirLength + 1;
911       } else {
912         if (!getMergePoolSize(FilenamePat, &I))
913           continue;
914         char LoadModuleSignature[SIGLEN + 1];
915         int S;
916         int ProfilePoolId = getpid() % lprofCurFilename.MergePoolSize;
917         S = snprintf(LoadModuleSignature, SIGLEN + 1, "%" PRIu64 "_%d",
918                      lprofGetLoadModuleSignature(), ProfilePoolId);
919         if (S == -1 || S > SIGLEN)
920           S = SIGLEN;
921         memcpy(FilenameBuf + J, LoadModuleSignature, S);
922         J += S;
923       }
924       /* Drop any unknown substitutions. */
925     } else
926       FilenameBuf[J++] = FilenamePat[I];
927   FilenameBuf[J] = 0;
928 
929   return FilenameBuf;
930 }
931 
932 /* Returns the pointer to the environment variable
933  * string. Returns null if the env var is not set. */
934 static const char *getFilenamePatFromEnv(void) {
935   const char *Filename = getenv("LLVM_PROFILE_FILE");
936   if (!Filename || !Filename[0])
937     return 0;
938   return Filename;
939 }
940 
941 COMPILER_RT_VISIBILITY
942 const char *__llvm_profile_get_path_prefix(void) {
943   int Length;
944   char *FilenameBuf, *Prefix;
945   const char *Filename, *PrefixEnd;
946 
947   if (lprofCurFilename.ProfilePathPrefix)
948     return lprofCurFilename.ProfilePathPrefix;
949 
950   Length = getCurFilenameLength();
951   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
952   Filename = getCurFilename(FilenameBuf, 0);
953   if (!Filename)
954     return "\0";
955 
956   PrefixEnd = lprofFindLastDirSeparator(Filename);
957   if (!PrefixEnd)
958     return "\0";
959 
960   Length = PrefixEnd - Filename + 1;
961   Prefix = (char *)malloc(Length + 1);
962   if (!Prefix) {
963     PROF_ERR("Failed to %s\n", "allocate memory.");
964     return "\0";
965   }
966   memcpy(Prefix, Filename, Length);
967   Prefix[Length] = '\0';
968   lprofCurFilename.ProfilePathPrefix = Prefix;
969   return Prefix;
970 }
971 
972 COMPILER_RT_VISIBILITY
973 const char *__llvm_profile_get_filename(void) {
974   int Length;
975   char *FilenameBuf;
976   const char *Filename;
977 
978   Length = getCurFilenameLength();
979   FilenameBuf = (char *)malloc(Length + 1);
980   if (!FilenameBuf) {
981     PROF_ERR("Failed to %s\n", "allocate memory.");
982     return "\0";
983   }
984   Filename = getCurFilename(FilenameBuf, 1);
985   if (!Filename)
986     return "\0";
987 
988   return FilenameBuf;
989 }
990 
991 /* This API initializes the file handling, both user specified
992  * profile path via -fprofile-instr-generate= and LLVM_PROFILE_FILE
993  * environment variable can override this default value.
994  */
995 COMPILER_RT_VISIBILITY
996 void __llvm_profile_initialize_file(void) {
997   const char *EnvFilenamePat;
998   const char *SelectedPat = NULL;
999   ProfileNameSpecifier PNS = PNS_unknown;
1000   int hasCommandLineOverrider = (INSTR_PROF_PROFILE_NAME_VAR[0] != 0);
1001 
1002   if (__llvm_profile_counter_bias != -1)
1003     lprofSetRuntimeCounterRelocation(1);
1004 
1005   EnvFilenamePat = getFilenamePatFromEnv();
1006   if (EnvFilenamePat) {
1007     /* Pass CopyFilenamePat = 1, to ensure that the filename would be valid
1008        at the  moment when __llvm_profile_write_file() gets executed. */
1009     parseAndSetFilename(EnvFilenamePat, PNS_environment, 1);
1010     return;
1011   } else if (hasCommandLineOverrider) {
1012     SelectedPat = INSTR_PROF_PROFILE_NAME_VAR;
1013     PNS = PNS_command_line;
1014   } else {
1015     SelectedPat = NULL;
1016     PNS = PNS_default;
1017   }
1018 
1019   parseAndSetFilename(SelectedPat, PNS, 0);
1020 }
1021 
1022 /* This method is invoked by the runtime initialization hook
1023  * InstrProfilingRuntime.o if it is linked in.
1024  */
1025 COMPILER_RT_VISIBILITY
1026 void __llvm_profile_initialize(void) {
1027   __llvm_profile_initialize_file();
1028   if (!__llvm_profile_is_continuous_mode_enabled())
1029     __llvm_profile_register_write_file_atexit();
1030 }
1031 
1032 /* This API is directly called by the user application code. It has the
1033  * highest precedence compared with LLVM_PROFILE_FILE environment variable
1034  * and command line option -fprofile-instr-generate=<profile_name>.
1035  */
1036 COMPILER_RT_VISIBILITY
1037 void __llvm_profile_set_filename(const char *FilenamePat) {
1038   if (__llvm_profile_is_continuous_mode_enabled())
1039     return;
1040   parseAndSetFilename(FilenamePat, PNS_runtime_api, 1);
1041 }
1042 
1043 /* The public API for writing profile data into the file with name
1044  * set by previous calls to __llvm_profile_set_filename or
1045  * __llvm_profile_override_default_filename or
1046  * __llvm_profile_initialize_file. */
1047 COMPILER_RT_VISIBILITY
1048 int __llvm_profile_write_file(void) {
1049   int rc, Length;
1050   const char *Filename;
1051   char *FilenameBuf;
1052   int PDeathSig = 0;
1053 
1054   if (lprofProfileDumped() || __llvm_profile_is_continuous_mode_enabled()) {
1055     PROF_NOTE("Profile data not written to file: %s.\n", "already written");
1056     return 0;
1057   }
1058 
1059   Length = getCurFilenameLength();
1060   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
1061   Filename = getCurFilename(FilenameBuf, 0);
1062 
1063   /* Check the filename. */
1064   if (!Filename) {
1065     PROF_ERR("Failed to write file : %s\n", "Filename not set");
1066     return -1;
1067   }
1068 
1069   /* Check if there is llvm/runtime version mismatch.  */
1070   if (GET_VERSION(__llvm_profile_get_version()) != INSTR_PROF_RAW_VERSION) {
1071     PROF_ERR("Runtime and instrumentation version mismatch : "
1072              "expected %d, but get %d\n",
1073              INSTR_PROF_RAW_VERSION,
1074              (int)GET_VERSION(__llvm_profile_get_version()));
1075     return -1;
1076   }
1077 
1078   // Temporarily suspend getting SIGKILL when the parent exits.
1079   PDeathSig = lprofSuspendSigKill();
1080 
1081   /* Write profile data to the file. */
1082   rc = writeFile(Filename);
1083   if (rc)
1084     PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));
1085 
1086   // Restore SIGKILL.
1087   if (PDeathSig == 1)
1088     lprofRestoreSigKill();
1089 
1090   return rc;
1091 }
1092 
1093 COMPILER_RT_VISIBILITY
1094 int __llvm_profile_dump(void) {
1095   if (!doMerging())
1096     PROF_WARN("Later invocation of __llvm_profile_dump can lead to clobbering "
1097               " of previously dumped profile data : %s. Either use %%m "
1098               "in profile name or change profile name before dumping.\n",
1099               "online profile merging is not on");
1100   int rc = __llvm_profile_write_file();
1101   lprofSetProfileDumped(1);
1102   return rc;
1103 }
1104 
1105 /* Order file data will be saved in a file with suffx .order. */
1106 static const char *OrderFileSuffix = ".order";
1107 
1108 COMPILER_RT_VISIBILITY
1109 int __llvm_orderfile_write_file(void) {
1110   int rc, Length, LengthBeforeAppend, SuffixLength;
1111   const char *Filename;
1112   char *FilenameBuf;
1113   int PDeathSig = 0;
1114 
1115   SuffixLength = strlen(OrderFileSuffix);
1116   Length = getCurFilenameLength() + SuffixLength;
1117   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
1118   Filename = getCurFilename(FilenameBuf, 1);
1119 
1120   /* Check the filename. */
1121   if (!Filename) {
1122     PROF_ERR("Failed to write file : %s\n", "Filename not set");
1123     return -1;
1124   }
1125 
1126   /* Append order file suffix */
1127   LengthBeforeAppend = strlen(Filename);
1128   memcpy(FilenameBuf + LengthBeforeAppend, OrderFileSuffix, SuffixLength);
1129   FilenameBuf[LengthBeforeAppend + SuffixLength] = '\0';
1130 
1131   /* Check if there is llvm/runtime version mismatch.  */
1132   if (GET_VERSION(__llvm_profile_get_version()) != INSTR_PROF_RAW_VERSION) {
1133     PROF_ERR("Runtime and instrumentation version mismatch : "
1134              "expected %d, but get %d\n",
1135              INSTR_PROF_RAW_VERSION,
1136              (int)GET_VERSION(__llvm_profile_get_version()));
1137     return -1;
1138   }
1139 
1140   // Temporarily suspend getting SIGKILL when the parent exits.
1141   PDeathSig = lprofSuspendSigKill();
1142 
1143   /* Write order data to the file. */
1144   rc = writeOrderFile(Filename);
1145   if (rc)
1146     PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));
1147 
1148   // Restore SIGKILL.
1149   if (PDeathSig == 1)
1150     lprofRestoreSigKill();
1151 
1152   return rc;
1153 }
1154 
1155 COMPILER_RT_VISIBILITY
1156 int __llvm_orderfile_dump(void) {
1157   int rc = __llvm_orderfile_write_file();
1158   return rc;
1159 }
1160 
1161 static void writeFileWithoutReturn(void) { __llvm_profile_write_file(); }
1162 
1163 COMPILER_RT_VISIBILITY
1164 int __llvm_profile_register_write_file_atexit(void) {
1165   static int HasBeenRegistered = 0;
1166 
1167   if (HasBeenRegistered)
1168     return 0;
1169 
1170   lprofSetupValueProfiler();
1171 
1172   HasBeenRegistered = 1;
1173   return atexit(writeFileWithoutReturn);
1174 }
1175 
1176 #endif
1177