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