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 // TODO: Move these functions into InstrProfilingPlatform* files.
430 #if defined(__APPLE__)
431 static void assertIsZero(int *i) {
432   if (*i)
433     PROF_WARN("Expected flag to be 0, but got: %d\n", *i);
434 }
435 
436 /* Write a partial profile to \p Filename, which is required to be backed by
437  * the open file object \p File. */
438 static int writeProfileWithFileObject(const char *Filename, FILE *File) {
439   setProfileFile(File);
440   int rc = writeFile(Filename);
441   if (rc)
442     PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));
443   setProfileFile(NULL);
444   return rc;
445 }
446 
447 /* Unlock the profile \p File and clear the unlock flag. */
448 static void unlockProfile(int *ProfileRequiresUnlock, FILE *File) {
449   if (!*ProfileRequiresUnlock) {
450     PROF_WARN("%s", "Expected to require profile unlock\n");
451   }
452 
453   lprofUnlockFileHandle(File);
454   *ProfileRequiresUnlock = 0;
455 }
456 
457 static void initializeProfileForContinuousMode(void) {
458   if (!__llvm_profile_is_continuous_mode_enabled())
459     return;
460 
461   /* Get the sizes of various profile data sections. Taken from
462    * __llvm_profile_get_size_for_buffer(). */
463   const __llvm_profile_data *DataBegin = __llvm_profile_begin_data();
464   const __llvm_profile_data *DataEnd = __llvm_profile_end_data();
465   const uint64_t *CountersBegin = __llvm_profile_begin_counters();
466   const uint64_t *CountersEnd = __llvm_profile_end_counters();
467   const char *NamesBegin = __llvm_profile_begin_names();
468   const char *NamesEnd = __llvm_profile_end_names();
469   const uint64_t NamesSize = (NamesEnd - NamesBegin) * sizeof(char);
470   uint64_t DataSize = __llvm_profile_get_data_size(DataBegin, DataEnd);
471   uint64_t CountersSize = CountersEnd - CountersBegin;
472 
473   /* Check that the counter and data sections in this image are page-aligned. */
474   unsigned PageSize = getpagesize();
475   if ((intptr_t)CountersBegin % PageSize != 0) {
476     PROF_ERR("Counters section not page-aligned (start = %p, pagesz = %u).\n",
477              CountersBegin, PageSize);
478     return;
479   }
480   if ((intptr_t)DataBegin % PageSize != 0) {
481     PROF_ERR("Data section not page-aligned (start = %p, pagesz = %u).\n",
482              DataBegin, PageSize);
483     return;
484   }
485 
486   int Length = getCurFilenameLength();
487   char *FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
488   const char *Filename = getCurFilename(FilenameBuf, 0);
489   if (!Filename)
490     return;
491 
492   FILE *File = NULL;
493   off_t CurrentFileOffset = 0;
494   off_t OffsetModPage = 0;
495 
496   /* Whether an exclusive lock on the profile must be dropped after init.
497    * Use a cleanup to warn if the unlock does not occur. */
498   COMPILER_RT_CLEANUP(assertIsZero) int ProfileRequiresUnlock = 0;
499 
500   if (!doMerging()) {
501     /* We are not merging profiles, so open the raw profile in append mode. */
502     File = fopen(Filename, "a+b");
503     if (!File)
504       return;
505 
506     /* Check that the offset within the file is page-aligned. */
507     CurrentFileOffset = ftello(File);
508     OffsetModPage = CurrentFileOffset % PageSize;
509     if (OffsetModPage != 0) {
510       PROF_ERR("Continuous counter sync mode is enabled, but raw profile is not"
511                "page-aligned. CurrentFileOffset = %" PRIu64 ", pagesz = %u.\n",
512                (uint64_t)CurrentFileOffset, PageSize);
513       return;
514     }
515 
516     /* Grow the profile so that mmap() can succeed.  Leak the file handle, as
517      * the file should stay open. */
518     if (writeProfileWithFileObject(Filename, File) != 0)
519       return;
520   } else {
521     /* We are merging profiles. Map the counter section as shared memory into
522      * the profile, i.e. into each participating process. An increment in one
523      * process should be visible to every other process with the same counter
524      * section mapped. */
525     File = lprofOpenFileEx(Filename);
526     if (!File)
527       return;
528 
529     ProfileRequiresUnlock = 1;
530 
531     uint64_t ProfileFileSize;
532     if (getProfileFileSizeForMerging(File, &ProfileFileSize) == -1)
533       return unlockProfile(&ProfileRequiresUnlock, File);
534 
535     if (ProfileFileSize == 0) {
536       /* Grow the profile so that mmap() can succeed.  Leak the file handle, as
537        * the file should stay open. */
538       if (writeProfileWithFileObject(Filename, File) != 0)
539         return unlockProfile(&ProfileRequiresUnlock, File);
540     } else {
541       /* The merged profile has a non-zero length. Check that it is compatible
542        * with the data in this process. */
543       char *ProfileBuffer;
544       if (mmapProfileForMerging(File, ProfileFileSize, &ProfileBuffer) == -1 ||
545           munmap(ProfileBuffer, ProfileFileSize) == -1)
546         return unlockProfile(&ProfileRequiresUnlock, File);
547     }
548   }
549 
550   /* mmap() the profile counters so long as there is at least one counter.
551    * If there aren't any counters, mmap() would fail with EINVAL. */
552   if (CountersSize > 0) {
553     int Fileno = fileno(File);
554 
555     /* Determine how much padding is needed before/after the counters and after
556      * the names. */
557     uint64_t PaddingBytesBeforeCounters, PaddingBytesAfterCounters,
558         PaddingBytesAfterNames;
559     __llvm_profile_get_padding_sizes_for_counters(
560         DataSize, CountersSize, NamesSize, &PaddingBytesBeforeCounters,
561         &PaddingBytesAfterCounters, &PaddingBytesAfterNames);
562 
563     uint64_t PageAlignedCountersLength =
564         (CountersSize * sizeof(uint64_t)) + PaddingBytesAfterCounters;
565     uint64_t FileOffsetToCounters =
566         CurrentFileOffset + sizeof(__llvm_profile_header) +
567         (DataSize * sizeof(__llvm_profile_data)) + PaddingBytesBeforeCounters;
568 
569     uint64_t *CounterMmap = (uint64_t *)mmap(
570         (void *)CountersBegin, PageAlignedCountersLength, PROT_READ | PROT_WRITE,
571         MAP_FIXED | MAP_SHARED, Fileno, FileOffsetToCounters);
572     if (CounterMmap != CountersBegin) {
573       PROF_ERR(
574           "Continuous counter sync mode is enabled, but mmap() failed (%s).\n"
575           "  - CountersBegin: %p\n"
576           "  - PageAlignedCountersLength: %" PRIu64 "\n"
577           "  - Fileno: %d\n"
578           "  - FileOffsetToCounters: %" PRIu64 "\n",
579           strerror(errno), CountersBegin, PageAlignedCountersLength, Fileno,
580           FileOffsetToCounters);
581     }
582   }
583 
584   if (ProfileRequiresUnlock)
585     unlockProfile(&ProfileRequiresUnlock, File);
586 }
587 #elif defined(__ELF__) || defined(_WIN32)
588 
589 #define INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR                            \
590   INSTR_PROF_CONCAT(INSTR_PROF_PROFILE_COUNTER_BIAS_VAR, _default)
591 intptr_t INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR = 0;
592 
593 /* This variable is a weak external reference which could be used to detect
594  * whether or not the compiler defined this symbol. */
595 #if defined(_WIN32)
596 COMPILER_RT_VISIBILITY extern intptr_t INSTR_PROF_PROFILE_COUNTER_BIAS_VAR;
597 #if defined(_M_IX86) || defined(__i386__)
598 #define WIN_SYM_PREFIX "_"
599 #else
600 #define WIN_SYM_PREFIX
601 #endif
602 #pragma comment(                                                               \
603     linker, "/alternatename:" WIN_SYM_PREFIX INSTR_PROF_QUOTE(                 \
604                 INSTR_PROF_PROFILE_COUNTER_BIAS_VAR) "=" WIN_SYM_PREFIX        \
605                 INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR))
606 #else
607 COMPILER_RT_VISIBILITY extern intptr_t INSTR_PROF_PROFILE_COUNTER_BIAS_VAR
608     __attribute__((weak, alias(INSTR_PROF_QUOTE(
609                              INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR))));
610 #endif
611 
612 static int writeMMappedFile(FILE *OutputFile, char **Profile) {
613   if (!OutputFile)
614     return -1;
615 
616   /* Write the data into a file. */
617   setupIOBuffer();
618   ProfDataWriter fileWriter;
619   initFileWriter(&fileWriter, OutputFile);
620   if (lprofWriteData(&fileWriter, NULL, 0)) {
621     PROF_ERR("Failed to write profile: %s\n", strerror(errno));
622     return -1;
623   }
624   fflush(OutputFile);
625 
626   /* Get the file size. */
627   uint64_t FileSize = ftell(OutputFile);
628 
629   /* Map the profile. */
630   *Profile = (char *)mmap(
631       NULL, FileSize, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(OutputFile), 0);
632   if (*Profile == MAP_FAILED) {
633     PROF_ERR("Unable to mmap profile: %s\n", strerror(errno));
634     return -1;
635   }
636 
637   return 0;
638 }
639 
640 static void initializeProfileForContinuousMode(void) {
641   if (!__llvm_profile_is_continuous_mode_enabled())
642     return;
643 
644   /* This symbol is defined by the compiler when runtime counter relocation is
645    * used and runtime provides a weak alias so we can check if it's defined. */
646   void *BiasAddr = &INSTR_PROF_PROFILE_COUNTER_BIAS_VAR;
647   void *BiasDefaultAddr = &INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR;
648   if (BiasAddr == BiasDefaultAddr) {
649     PROF_ERR("%s\n", "__llvm_profile_counter_bias is undefined");
650     return;
651   }
652 
653   /* Get the sizes of various profile data sections. Taken from
654    * __llvm_profile_get_size_for_buffer(). */
655   const __llvm_profile_data *DataBegin = __llvm_profile_begin_data();
656   const __llvm_profile_data *DataEnd = __llvm_profile_end_data();
657   const uint64_t *CountersBegin = __llvm_profile_begin_counters();
658   const uint64_t *CountersEnd = __llvm_profile_end_counters();
659   uint64_t DataSize = __llvm_profile_get_data_size(DataBegin, DataEnd);
660   const uint64_t CountersOffset =
661       sizeof(__llvm_profile_header) + (DataSize * sizeof(__llvm_profile_data));
662 
663   int Length = getCurFilenameLength();
664   char *FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
665   const char *Filename = getCurFilename(FilenameBuf, 0);
666   if (!Filename)
667     return;
668 
669   FILE *File = NULL;
670   char *Profile = NULL;
671 
672   if (!doMerging()) {
673     File = fopen(Filename, "w+b");
674     if (!File)
675       return;
676 
677     if (writeMMappedFile(File, &Profile) == -1) {
678       fclose(File);
679       return;
680     }
681   } else {
682     File = lprofOpenFileEx(Filename);
683     if (!File)
684       return;
685 
686     uint64_t ProfileFileSize = 0;
687     if (getProfileFileSizeForMerging(File, &ProfileFileSize) == -1) {
688       lprofUnlockFileHandle(File);
689       fclose(File);
690       return;
691     }
692 
693     if (!ProfileFileSize) {
694       if (writeMMappedFile(File, &Profile) == -1) {
695         fclose(File);
696         return;
697       }
698     } else {
699       /* The merged profile has a non-zero length. Check that it is compatible
700        * with the data in this process. */
701       if (mmapProfileForMerging(File, ProfileFileSize, &Profile) == -1) {
702         fclose(File);
703         return;
704       }
705     }
706 
707     lprofUnlockFileHandle(File);
708   }
709 
710   /* Update the profile fields based on the current mapping. */
711   INSTR_PROF_PROFILE_COUNTER_BIAS_VAR =
712       (intptr_t)Profile - (uintptr_t)CountersBegin +
713       CountersOffset;
714 
715   /* Return the memory allocated for counters to OS. */
716   lprofReleaseMemoryPagesToOS((uintptr_t)CountersBegin, (uintptr_t)CountersEnd);
717 }
718 #else
719 static void initializeProfileForContinuousMode(void) {
720   PROF_ERR("%s\n", "continuous mode is unsupported on this platform");
721 }
722 #endif
723 
724 static const char *DefaultProfileName = "default.profraw";
725 static void resetFilenameToDefault(void) {
726   if (lprofCurFilename.FilenamePat && lprofCurFilename.OwnsFilenamePat) {
727     free((void *)lprofCurFilename.FilenamePat);
728   }
729   memset(&lprofCurFilename, 0, sizeof(lprofCurFilename));
730   lprofCurFilename.FilenamePat = DefaultProfileName;
731   lprofCurFilename.PNS = PNS_default;
732 }
733 
734 static unsigned getMergePoolSize(const char *FilenamePat, int *I) {
735   unsigned J = 0, Num = 0;
736   for (;; ++J) {
737     char C = FilenamePat[*I + J];
738     if (C == 'm') {
739       *I += J;
740       return Num ? Num : 1;
741     }
742     if (C < '0' || C > '9')
743       break;
744     Num = Num * 10 + C - '0';
745 
746     /* If FilenamePat[*I+J] is between '0' and '9', the next byte is guaranteed
747      * to be in-bound as the string is null terminated. */
748   }
749   return 0;
750 }
751 
752 /* Assert that Idx does index past a string null terminator. Return the
753  * result of the check. */
754 static int checkBounds(int Idx, int Strlen) {
755   assert(Idx <= Strlen && "Indexing past string null terminator");
756   return Idx <= Strlen;
757 }
758 
759 /* Parses the pattern string \p FilenamePat and stores the result to
760  * lprofcurFilename structure. */
761 static int parseFilenamePattern(const char *FilenamePat,
762                                 unsigned CopyFilenamePat) {
763   int NumPids = 0, NumHosts = 0, I;
764   char *PidChars = &lprofCurFilename.PidChars[0];
765   char *Hostname = &lprofCurFilename.Hostname[0];
766   int MergingEnabled = 0;
767   int FilenamePatLen = strlen(FilenamePat);
768 
769   /* Clean up cached prefix and filename.  */
770   if (lprofCurFilename.ProfilePathPrefix)
771     free((void *)lprofCurFilename.ProfilePathPrefix);
772 
773   if (lprofCurFilename.FilenamePat && lprofCurFilename.OwnsFilenamePat) {
774     free((void *)lprofCurFilename.FilenamePat);
775   }
776 
777   memset(&lprofCurFilename, 0, sizeof(lprofCurFilename));
778 
779   if (!CopyFilenamePat)
780     lprofCurFilename.FilenamePat = FilenamePat;
781   else {
782     lprofCurFilename.FilenamePat = strdup(FilenamePat);
783     lprofCurFilename.OwnsFilenamePat = 1;
784   }
785   /* Check the filename for "%p", which indicates a pid-substitution. */
786   for (I = 0; checkBounds(I, FilenamePatLen) && FilenamePat[I]; ++I) {
787     if (FilenamePat[I] == '%') {
788       ++I; /* Advance to the next character. */
789       if (!checkBounds(I, FilenamePatLen))
790         break;
791       if (FilenamePat[I] == 'p') {
792         if (!NumPids++) {
793           if (snprintf(PidChars, MAX_PID_SIZE, "%ld", (long)getpid()) <= 0) {
794             PROF_WARN("Unable to get pid for filename pattern %s. Using the "
795                       "default name.",
796                       FilenamePat);
797             return -1;
798           }
799         }
800       } else if (FilenamePat[I] == 'h') {
801         if (!NumHosts++)
802           if (COMPILER_RT_GETHOSTNAME(Hostname, COMPILER_RT_MAX_HOSTLEN)) {
803             PROF_WARN("Unable to get hostname for filename pattern %s. Using "
804                       "the default name.",
805                       FilenamePat);
806             return -1;
807           }
808       } else if (FilenamePat[I] == 't') {
809         lprofCurFilename.TmpDir = getenv("TMPDIR");
810         if (!lprofCurFilename.TmpDir) {
811           PROF_WARN("Unable to get the TMPDIR environment variable, referenced "
812                     "in %s. Using the default path.",
813                     FilenamePat);
814           return -1;
815         }
816       } else if (FilenamePat[I] == 'c') {
817         if (__llvm_profile_is_continuous_mode_enabled()) {
818           PROF_WARN("%%c specifier can only be specified once in %s.\n",
819                     FilenamePat);
820           return -1;
821         }
822 #if defined(__APPLE__) || defined(__ELF__) || defined(_WIN32)
823         __llvm_profile_set_page_size(getpagesize());
824         __llvm_profile_enable_continuous_mode();
825 #else
826         PROF_WARN("%s", "Continous mode is currently only supported for Mach-O,"
827                         " ELF and COFF formats.");
828         return -1;
829 #endif
830       } else {
831         unsigned MergePoolSize = getMergePoolSize(FilenamePat, &I);
832         if (!MergePoolSize)
833           continue;
834         if (MergingEnabled) {
835           PROF_WARN("%%m specifier can only be specified once in %s.\n",
836                     FilenamePat);
837           return -1;
838         }
839         MergingEnabled = 1;
840         lprofCurFilename.MergePoolSize = MergePoolSize;
841       }
842     }
843   }
844 
845   lprofCurFilename.NumPids = NumPids;
846   lprofCurFilename.NumHosts = NumHosts;
847   return 0;
848 }
849 
850 static void parseAndSetFilename(const char *FilenamePat,
851                                 ProfileNameSpecifier PNS,
852                                 unsigned CopyFilenamePat) {
853 
854   const char *OldFilenamePat = lprofCurFilename.FilenamePat;
855   ProfileNameSpecifier OldPNS = lprofCurFilename.PNS;
856 
857   /* The old profile name specifier takes precedence over the old one. */
858   if (PNS < OldPNS)
859     return;
860 
861   if (!FilenamePat)
862     FilenamePat = DefaultProfileName;
863 
864   if (OldFilenamePat && !strcmp(OldFilenamePat, FilenamePat)) {
865     lprofCurFilename.PNS = PNS;
866     return;
867   }
868 
869   /* When PNS >= OldPNS, the last one wins. */
870   if (!FilenamePat || parseFilenamePattern(FilenamePat, CopyFilenamePat))
871     resetFilenameToDefault();
872   lprofCurFilename.PNS = PNS;
873 
874   if (!OldFilenamePat) {
875     if (getenv("LLVM_PROFILE_VERBOSE"))
876       PROF_NOTE("Set profile file path to \"%s\" via %s.\n",
877                 lprofCurFilename.FilenamePat, getPNSStr(PNS));
878   } else {
879     if (getenv("LLVM_PROFILE_VERBOSE"))
880       PROF_NOTE("Override old profile path \"%s\" via %s to \"%s\" via %s.\n",
881                 OldFilenamePat, getPNSStr(OldPNS), lprofCurFilename.FilenamePat,
882                 getPNSStr(PNS));
883   }
884 
885   truncateCurrentFile();
886   if (__llvm_profile_is_continuous_mode_enabled())
887     initializeProfileForContinuousMode();
888 }
889 
890 /* Return buffer length that is required to store the current profile
891  * filename with PID and hostname substitutions. */
892 /* The length to hold uint64_t followed by 3 digits pool id including '_' */
893 #define SIGLEN 24
894 static int getCurFilenameLength() {
895   int Len;
896   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
897     return 0;
898 
899   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
900         lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize))
901     return strlen(lprofCurFilename.FilenamePat);
902 
903   Len = strlen(lprofCurFilename.FilenamePat) +
904         lprofCurFilename.NumPids * (strlen(lprofCurFilename.PidChars) - 2) +
905         lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2) +
906         (lprofCurFilename.TmpDir ? (strlen(lprofCurFilename.TmpDir) - 1) : 0);
907   if (lprofCurFilename.MergePoolSize)
908     Len += SIGLEN;
909   return Len;
910 }
911 
912 /* Return the pointer to the current profile file name (after substituting
913  * PIDs and Hostnames in filename pattern. \p FilenameBuf is the buffer
914  * to store the resulting filename. If no substitution is needed, the
915  * current filename pattern string is directly returned, unless ForceUseBuf
916  * is enabled. */
917 static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
918   int I, J, PidLength, HostNameLength, TmpDirLength, FilenamePatLength;
919   const char *FilenamePat = lprofCurFilename.FilenamePat;
920 
921   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
922     return 0;
923 
924   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
925         lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize ||
926         __llvm_profile_is_continuous_mode_enabled())) {
927     if (!ForceUseBuf)
928       return lprofCurFilename.FilenamePat;
929 
930     FilenamePatLength = strlen(lprofCurFilename.FilenamePat);
931     memcpy(FilenameBuf, lprofCurFilename.FilenamePat, FilenamePatLength);
932     FilenameBuf[FilenamePatLength] = '\0';
933     return FilenameBuf;
934   }
935 
936   PidLength = strlen(lprofCurFilename.PidChars);
937   HostNameLength = strlen(lprofCurFilename.Hostname);
938   TmpDirLength = lprofCurFilename.TmpDir ? strlen(lprofCurFilename.TmpDir) : 0;
939   /* Construct the new filename. */
940   for (I = 0, J = 0; FilenamePat[I]; ++I)
941     if (FilenamePat[I] == '%') {
942       if (FilenamePat[++I] == 'p') {
943         memcpy(FilenameBuf + J, lprofCurFilename.PidChars, PidLength);
944         J += PidLength;
945       } else if (FilenamePat[I] == 'h') {
946         memcpy(FilenameBuf + J, lprofCurFilename.Hostname, HostNameLength);
947         J += HostNameLength;
948       } else if (FilenamePat[I] == 't') {
949         memcpy(FilenameBuf + J, lprofCurFilename.TmpDir, TmpDirLength);
950         FilenameBuf[J + TmpDirLength] = DIR_SEPARATOR;
951         J += TmpDirLength + 1;
952       } else {
953         if (!getMergePoolSize(FilenamePat, &I))
954           continue;
955         char LoadModuleSignature[SIGLEN + 1];
956         int S;
957         int ProfilePoolId = getpid() % lprofCurFilename.MergePoolSize;
958         S = snprintf(LoadModuleSignature, SIGLEN + 1, "%" PRIu64 "_%d",
959                      lprofGetLoadModuleSignature(), ProfilePoolId);
960         if (S == -1 || S > SIGLEN)
961           S = SIGLEN;
962         memcpy(FilenameBuf + J, LoadModuleSignature, S);
963         J += S;
964       }
965       /* Drop any unknown substitutions. */
966     } else
967       FilenameBuf[J++] = FilenamePat[I];
968   FilenameBuf[J] = 0;
969 
970   return FilenameBuf;
971 }
972 
973 /* Returns the pointer to the environment variable
974  * string. Returns null if the env var is not set. */
975 static const char *getFilenamePatFromEnv(void) {
976   const char *Filename = getenv("LLVM_PROFILE_FILE");
977   if (!Filename || !Filename[0])
978     return 0;
979   return Filename;
980 }
981 
982 COMPILER_RT_VISIBILITY
983 const char *__llvm_profile_get_path_prefix(void) {
984   int Length;
985   char *FilenameBuf, *Prefix;
986   const char *Filename, *PrefixEnd;
987 
988   if (lprofCurFilename.ProfilePathPrefix)
989     return lprofCurFilename.ProfilePathPrefix;
990 
991   Length = getCurFilenameLength();
992   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
993   Filename = getCurFilename(FilenameBuf, 0);
994   if (!Filename)
995     return "\0";
996 
997   PrefixEnd = lprofFindLastDirSeparator(Filename);
998   if (!PrefixEnd)
999     return "\0";
1000 
1001   Length = PrefixEnd - Filename + 1;
1002   Prefix = (char *)malloc(Length + 1);
1003   if (!Prefix) {
1004     PROF_ERR("Failed to %s\n", "allocate memory.");
1005     return "\0";
1006   }
1007   memcpy(Prefix, Filename, Length);
1008   Prefix[Length] = '\0';
1009   lprofCurFilename.ProfilePathPrefix = Prefix;
1010   return Prefix;
1011 }
1012 
1013 COMPILER_RT_VISIBILITY
1014 const char *__llvm_profile_get_filename(void) {
1015   int Length;
1016   char *FilenameBuf;
1017   const char *Filename;
1018 
1019   Length = getCurFilenameLength();
1020   FilenameBuf = (char *)malloc(Length + 1);
1021   if (!FilenameBuf) {
1022     PROF_ERR("Failed to %s\n", "allocate memory.");
1023     return "\0";
1024   }
1025   Filename = getCurFilename(FilenameBuf, 1);
1026   if (!Filename)
1027     return "\0";
1028 
1029   return FilenameBuf;
1030 }
1031 
1032 /* This API initializes the file handling, both user specified
1033  * profile path via -fprofile-instr-generate= and LLVM_PROFILE_FILE
1034  * environment variable can override this default value.
1035  */
1036 COMPILER_RT_VISIBILITY
1037 void __llvm_profile_initialize_file(void) {
1038   const char *EnvFilenamePat;
1039   const char *SelectedPat = NULL;
1040   ProfileNameSpecifier PNS = PNS_unknown;
1041   int hasCommandLineOverrider = (INSTR_PROF_PROFILE_NAME_VAR[0] != 0);
1042 
1043   EnvFilenamePat = getFilenamePatFromEnv();
1044   if (EnvFilenamePat) {
1045     /* Pass CopyFilenamePat = 1, to ensure that the filename would be valid
1046        at the  moment when __llvm_profile_write_file() gets executed. */
1047     parseAndSetFilename(EnvFilenamePat, PNS_environment, 1);
1048     return;
1049   } else if (hasCommandLineOverrider) {
1050     SelectedPat = INSTR_PROF_PROFILE_NAME_VAR;
1051     PNS = PNS_command_line;
1052   } else {
1053     SelectedPat = NULL;
1054     PNS = PNS_default;
1055   }
1056 
1057   parseAndSetFilename(SelectedPat, PNS, 0);
1058 }
1059 
1060 /* This method is invoked by the runtime initialization hook
1061  * InstrProfilingRuntime.o if it is linked in.
1062  */
1063 COMPILER_RT_VISIBILITY
1064 void __llvm_profile_initialize(void) {
1065   __llvm_profile_initialize_file();
1066   if (!__llvm_profile_is_continuous_mode_enabled())
1067     __llvm_profile_register_write_file_atexit();
1068 }
1069 
1070 /* This API is directly called by the user application code. It has the
1071  * highest precedence compared with LLVM_PROFILE_FILE environment variable
1072  * and command line option -fprofile-instr-generate=<profile_name>.
1073  */
1074 COMPILER_RT_VISIBILITY
1075 void __llvm_profile_set_filename(const char *FilenamePat) {
1076   if (__llvm_profile_is_continuous_mode_enabled())
1077     return;
1078   parseAndSetFilename(FilenamePat, PNS_runtime_api, 1);
1079 }
1080 
1081 /* The public API for writing profile data into the file with name
1082  * set by previous calls to __llvm_profile_set_filename or
1083  * __llvm_profile_override_default_filename or
1084  * __llvm_profile_initialize_file. */
1085 COMPILER_RT_VISIBILITY
1086 int __llvm_profile_write_file(void) {
1087   int rc, Length;
1088   const char *Filename;
1089   char *FilenameBuf;
1090   int PDeathSig = 0;
1091 
1092   if (lprofProfileDumped() || __llvm_profile_is_continuous_mode_enabled()) {
1093     PROF_NOTE("Profile data not written to file: %s.\n", "already written");
1094     return 0;
1095   }
1096 
1097   Length = getCurFilenameLength();
1098   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
1099   Filename = getCurFilename(FilenameBuf, 0);
1100 
1101   /* Check the filename. */
1102   if (!Filename) {
1103     PROF_ERR("Failed to write file : %s\n", "Filename not set");
1104     return -1;
1105   }
1106 
1107   /* Check if there is llvm/runtime version mismatch.  */
1108   if (GET_VERSION(__llvm_profile_get_version()) != INSTR_PROF_RAW_VERSION) {
1109     PROF_ERR("Runtime and instrumentation version mismatch : "
1110              "expected %d, but get %d\n",
1111              INSTR_PROF_RAW_VERSION,
1112              (int)GET_VERSION(__llvm_profile_get_version()));
1113     return -1;
1114   }
1115 
1116   // Temporarily suspend getting SIGKILL when the parent exits.
1117   PDeathSig = lprofSuspendSigKill();
1118 
1119   /* Write profile data to the file. */
1120   rc = writeFile(Filename);
1121   if (rc)
1122     PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));
1123 
1124   // Restore SIGKILL.
1125   if (PDeathSig == 1)
1126     lprofRestoreSigKill();
1127 
1128   return rc;
1129 }
1130 
1131 COMPILER_RT_VISIBILITY
1132 int __llvm_profile_dump(void) {
1133   if (!doMerging())
1134     PROF_WARN("Later invocation of __llvm_profile_dump can lead to clobbering "
1135               " of previously dumped profile data : %s. Either use %%m "
1136               "in profile name or change profile name before dumping.\n",
1137               "online profile merging is not on");
1138   int rc = __llvm_profile_write_file();
1139   lprofSetProfileDumped(1);
1140   return rc;
1141 }
1142 
1143 /* Order file data will be saved in a file with suffx .order. */
1144 static const char *OrderFileSuffix = ".order";
1145 
1146 COMPILER_RT_VISIBILITY
1147 int __llvm_orderfile_write_file(void) {
1148   int rc, Length, LengthBeforeAppend, SuffixLength;
1149   const char *Filename;
1150   char *FilenameBuf;
1151   int PDeathSig = 0;
1152 
1153   SuffixLength = strlen(OrderFileSuffix);
1154   Length = getCurFilenameLength() + SuffixLength;
1155   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
1156   Filename = getCurFilename(FilenameBuf, 1);
1157 
1158   /* Check the filename. */
1159   if (!Filename) {
1160     PROF_ERR("Failed to write file : %s\n", "Filename not set");
1161     return -1;
1162   }
1163 
1164   /* Append order file suffix */
1165   LengthBeforeAppend = strlen(Filename);
1166   memcpy(FilenameBuf + LengthBeforeAppend, OrderFileSuffix, SuffixLength);
1167   FilenameBuf[LengthBeforeAppend + SuffixLength] = '\0';
1168 
1169   /* Check if there is llvm/runtime version mismatch.  */
1170   if (GET_VERSION(__llvm_profile_get_version()) != INSTR_PROF_RAW_VERSION) {
1171     PROF_ERR("Runtime and instrumentation version mismatch : "
1172              "expected %d, but get %d\n",
1173              INSTR_PROF_RAW_VERSION,
1174              (int)GET_VERSION(__llvm_profile_get_version()));
1175     return -1;
1176   }
1177 
1178   // Temporarily suspend getting SIGKILL when the parent exits.
1179   PDeathSig = lprofSuspendSigKill();
1180 
1181   /* Write order data to the file. */
1182   rc = writeOrderFile(Filename);
1183   if (rc)
1184     PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));
1185 
1186   // Restore SIGKILL.
1187   if (PDeathSig == 1)
1188     lprofRestoreSigKill();
1189 
1190   return rc;
1191 }
1192 
1193 COMPILER_RT_VISIBILITY
1194 int __llvm_orderfile_dump(void) {
1195   int rc = __llvm_orderfile_write_file();
1196   return rc;
1197 }
1198 
1199 static void writeFileWithoutReturn(void) { __llvm_profile_write_file(); }
1200 
1201 COMPILER_RT_VISIBILITY
1202 int __llvm_profile_register_write_file_atexit(void) {
1203   static int HasBeenRegistered = 0;
1204 
1205   if (HasBeenRegistered)
1206     return 0;
1207 
1208   lprofSetupValueProfiler();
1209 
1210   HasBeenRegistered = 1;
1211   return atexit(writeFileWithoutReturn);
1212 }
1213 
1214 #endif
1215