1be0a5e17SDuncan P. N. Exon Smith /*===- InstrProfilingFile.c - Write instrumentation to a file -------------===*\
2be0a5e17SDuncan P. N. Exon Smith |*
32946cd70SChandler Carruth |* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth |* See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6be0a5e17SDuncan P. N. Exon Smith |*
7be0a5e17SDuncan P. N. Exon Smith \*===----------------------------------------------------------------------===*/
8be0a5e17SDuncan P. N. Exon Smith 
947e5fcbaSPetr Hosek #if !defined(__Fuchsia__)
1047e5fcbaSPetr Hosek 
11a7d48261SVedant Kumar #include <assert.h>
12ef24b417SJoerg Sonnenberger #include <errno.h>
13be0a5e17SDuncan P. N. Exon Smith #include <stdio.h>
14be0a5e17SDuncan P. N. Exon Smith #include <stdlib.h>
15be0a5e17SDuncan P. N. Exon Smith #include <string.h>
1671eddbf5SXinliang David Li #ifdef _MSC_VER
17315e49d2SXinliang David Li /* For _alloca. */
1871eddbf5SXinliang David Li #include <malloc.h>
19fb320a11SXinliang David Li #endif
20e2ce2e00SXinliang David Li #if defined(_WIN32)
21e2ce2e00SXinliang David Li #include "WindowsMMap.h"
22e2ce2e00SXinliang David Li /* For _chsize_s */
23e2ce2e00SXinliang David Li #include <io.h>
24963aba34SReid Kleckner #include <process.h>
25e2ce2e00SXinliang David Li #else
26e2ce2e00SXinliang David Li #include <sys/file.h>
27e2ce2e00SXinliang David Li #include <sys/mman.h>
28e2ce2e00SXinliang David Li #include <unistd.h>
29e2ce2e00SXinliang David Li #if defined(__linux__)
30e2ce2e00SXinliang David Li #include <sys/types.h>
31e2ce2e00SXinliang David Li #endif
32e2ce2e00SXinliang David Li #endif
3371eddbf5SXinliang David Li 
34d7c9336aSVedant Kumar #include "InstrProfiling.h"
35d7c9336aSVedant Kumar #include "InstrProfilingInternal.h"
36d889d1efSVedant Kumar #include "InstrProfilingPort.h"
37d7c9336aSVedant Kumar #include "InstrProfilingUtil.h"
38d7c9336aSVedant Kumar 
39153e8b6cSXinliang David Li /* From where is profile name specified.
40153e8b6cSXinliang David Li  * The order the enumerators define their
41153e8b6cSXinliang David Li  * precedence. Re-order them may lead to
42153e8b6cSXinliang David Li  * runtime behavior change. */
43153e8b6cSXinliang David Li typedef enum ProfileNameSpecifier {
44153e8b6cSXinliang David Li   PNS_unknown = 0,
45153e8b6cSXinliang David Li   PNS_default,
46153e8b6cSXinliang David Li   PNS_command_line,
47153e8b6cSXinliang David Li   PNS_environment,
48153e8b6cSXinliang David Li   PNS_runtime_api
49153e8b6cSXinliang David Li } ProfileNameSpecifier;
50153e8b6cSXinliang David Li 
getPNSStr(ProfileNameSpecifier PNS)51153e8b6cSXinliang David Li static const char *getPNSStr(ProfileNameSpecifier PNS) {
52153e8b6cSXinliang David Li   switch (PNS) {
53153e8b6cSXinliang David Li   case PNS_default:
54153e8b6cSXinliang David Li     return "default setting";
55153e8b6cSXinliang David Li   case PNS_command_line:
56153e8b6cSXinliang David Li     return "command line";
57153e8b6cSXinliang David Li   case PNS_environment:
58153e8b6cSXinliang David Li     return "environment variable";
59153e8b6cSXinliang David Li   case PNS_runtime_api:
60153e8b6cSXinliang David Li     return "runtime API";
61153e8b6cSXinliang David Li   default:
62153e8b6cSXinliang David Li     return "Unknown";
63153e8b6cSXinliang David Li   }
64153e8b6cSXinliang David Li }
65153e8b6cSXinliang David Li 
66315e49d2SXinliang David Li #define MAX_PID_SIZE 16
67315e49d2SXinliang David Li /* Data structure holding the result of parsed filename pattern. */
68315e49d2SXinliang David Li typedef struct lprofFilename {
69315e49d2SXinliang David Li   /* File name string possibly with %p or %h specifiers. */
70315e49d2SXinliang David Li   const char *FilenamePat;
7114c91c4eSXinliang David Li   /* A flag indicating if FilenamePat's memory is allocated
7214c91c4eSXinliang David Li    * by runtime. */
7314c91c4eSXinliang David Li   unsigned OwnsFilenamePat;
74eaf238d4SXinliang David Li   const char *ProfilePathPrefix;
75315e49d2SXinliang David Li   char PidChars[MAX_PID_SIZE];
7662c37277SVedant Kumar   char *TmpDir;
77315e49d2SXinliang David Li   char Hostname[COMPILER_RT_MAX_HOSTLEN];
78315e49d2SXinliang David Li   unsigned NumPids;
79315e49d2SXinliang David Li   unsigned NumHosts;
80e2ce2e00SXinliang David Li   /* When in-process merging is enabled, this parameter specifies
81e2ce2e00SXinliang David Li    * the total number of profile data files shared by all the processes
82e2ce2e00SXinliang David Li    * spawned from the same binary. By default the value is 1. If merging
83e2ce2e00SXinliang David Li    * is not enabled, its value should be 0. This parameter is specified
84e2ce2e00SXinliang David Li    * by the %[0-9]m specifier. For instance %2m enables merging using
85e2ce2e00SXinliang David Li    * 2 profile data files. %1m is equivalent to %m. Also %m specifier
86e2ce2e00SXinliang David Li    * can only appear once at the end of the name pattern. */
87e2ce2e00SXinliang David Li   unsigned MergePoolSize;
88153e8b6cSXinliang David Li   ProfileNameSpecifier PNS;
89315e49d2SXinliang David Li } lprofFilename;
90be0a5e17SDuncan P. N. Exon Smith 
9162c37277SVedant Kumar static lprofFilename lprofCurFilename = {0,   0, 0, {0}, NULL,
9262c37277SVedant Kumar                                          {0}, 0, 0, 0,   PNS_unknown};
93315e49d2SXinliang David Li 
946694b2b3SSajjad Mirza static int ProfileMergeRequested = 0;
951b052451SZequan Wu static int getProfileFileSizeForMerging(FILE *ProfileFile,
961b052451SZequan Wu                                         uint64_t *ProfileFileSize);
978c4208d5SZequan Wu 
988c4208d5SZequan Wu #if defined(__APPLE__)
998c4208d5SZequan Wu static const int ContinuousModeSupported = 1;
1008c4208d5SZequan Wu static const int UseBiasVar = 0;
1018c4208d5SZequan Wu static const char *FileOpenMode = "a+b";
1028c4208d5SZequan Wu static void *BiasAddr = NULL;
1038c4208d5SZequan Wu static void *BiasDefaultAddr = NULL;
mmapForContinuousMode(uint64_t CurrentFileOffset,FILE * File)1041b052451SZequan Wu static int mmapForContinuousMode(uint64_t CurrentFileOffset, FILE *File) {
1051b052451SZequan Wu   /* Get the sizes of various profile data sections. Taken from
1061b052451SZequan Wu    * __llvm_profile_get_size_for_buffer(). */
1071b052451SZequan Wu   const __llvm_profile_data *DataBegin = __llvm_profile_begin_data();
1081b052451SZequan Wu   const __llvm_profile_data *DataEnd = __llvm_profile_end_data();
109f2147375SEllis Hoag   const char *CountersBegin = __llvm_profile_begin_counters();
110f2147375SEllis Hoag   const char *CountersEnd = __llvm_profile_end_counters();
1111b052451SZequan Wu   const char *NamesBegin = __llvm_profile_begin_names();
1121b052451SZequan Wu   const char *NamesEnd = __llvm_profile_end_names();
1131b052451SZequan Wu   const uint64_t NamesSize = (NamesEnd - NamesBegin) * sizeof(char);
1141b052451SZequan Wu   uint64_t DataSize = __llvm_profile_get_data_size(DataBegin, DataEnd);
115f2147375SEllis Hoag   uint64_t CountersSize =
116f2147375SEllis Hoag       __llvm_profile_get_counters_size(CountersBegin, CountersEnd);
1171b052451SZequan Wu 
1181b052451SZequan Wu   /* Check that the counter and data sections in this image are
1191b052451SZequan Wu    * page-aligned. */
1201b052451SZequan Wu   unsigned PageSize = getpagesize();
1211b052451SZequan Wu   if ((intptr_t)CountersBegin % PageSize != 0) {
1221b052451SZequan Wu     PROF_ERR("Counters section not page-aligned (start = %p, pagesz = %u).\n",
1231b052451SZequan Wu              CountersBegin, PageSize);
1241b052451SZequan Wu     return 1;
1251b052451SZequan Wu   }
1261b052451SZequan Wu   if ((intptr_t)DataBegin % PageSize != 0) {
1271b052451SZequan Wu     PROF_ERR("Data section not page-aligned (start = %p, pagesz = %u).\n",
1281b052451SZequan Wu              DataBegin, PageSize);
1291b052451SZequan Wu     return 1;
1301b052451SZequan Wu   }
1311b052451SZequan Wu   int Fileno = fileno(File);
1321b052451SZequan Wu   /* Determine how much padding is needed before/after the counters and
1331b052451SZequan Wu    * after the names. */
1341b052451SZequan Wu   uint64_t PaddingBytesBeforeCounters, PaddingBytesAfterCounters,
1351b052451SZequan Wu       PaddingBytesAfterNames;
1361b052451SZequan Wu   __llvm_profile_get_padding_sizes_for_counters(
1371b052451SZequan Wu       DataSize, CountersSize, NamesSize, &PaddingBytesBeforeCounters,
1381b052451SZequan Wu       &PaddingBytesAfterCounters, &PaddingBytesAfterNames);
1391b052451SZequan Wu 
140f2147375SEllis Hoag   uint64_t PageAlignedCountersLength = CountersSize + PaddingBytesAfterCounters;
141f2147375SEllis Hoag   uint64_t FileOffsetToCounters = CurrentFileOffset +
142f2147375SEllis Hoag                                   sizeof(__llvm_profile_header) + DataSize +
143f2147375SEllis Hoag                                   PaddingBytesBeforeCounters;
1449c353039SEllis Hoag   void *CounterMmap = mmap((void *)CountersBegin, PageAlignedCountersLength,
1459c353039SEllis Hoag                            PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED,
1469c353039SEllis Hoag                            Fileno, FileOffsetToCounters);
1471b052451SZequan Wu   if (CounterMmap != CountersBegin) {
1481b052451SZequan Wu     PROF_ERR(
1491b052451SZequan Wu         "Continuous counter sync mode is enabled, but mmap() failed (%s).\n"
1501b052451SZequan Wu         "  - CountersBegin: %p\n"
1511b052451SZequan Wu         "  - PageAlignedCountersLength: %" PRIu64 "\n"
1521b052451SZequan Wu         "  - Fileno: %d\n"
1531b052451SZequan Wu         "  - FileOffsetToCounters: %" PRIu64 "\n",
1541b052451SZequan Wu         strerror(errno), CountersBegin, PageAlignedCountersLength, Fileno,
1551b052451SZequan Wu         FileOffsetToCounters);
1561b052451SZequan Wu     return 1;
1571b052451SZequan Wu   }
1581b052451SZequan Wu   return 0;
1591b052451SZequan Wu }
1608c4208d5SZequan Wu #elif defined(__ELF__) || defined(_WIN32)
1618c4208d5SZequan Wu 
1628c4208d5SZequan Wu #define INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR                            \
1638c4208d5SZequan Wu   INSTR_PROF_CONCAT(INSTR_PROF_PROFILE_COUNTER_BIAS_VAR, _default)
1648c4208d5SZequan Wu intptr_t INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR = 0;
1658c4208d5SZequan Wu 
1668c4208d5SZequan Wu /* This variable is a weak external reference which could be used to detect
1678c4208d5SZequan Wu  * whether or not the compiler defined this symbol. */
1684cfb047dSNikita Popov #if defined(_MSC_VER)
1698c4208d5SZequan Wu COMPILER_RT_VISIBILITY extern intptr_t INSTR_PROF_PROFILE_COUNTER_BIAS_VAR;
1708c4208d5SZequan Wu #if defined(_M_IX86) || defined(__i386__)
1718c4208d5SZequan Wu #define WIN_SYM_PREFIX "_"
1728c4208d5SZequan Wu #else
1738c4208d5SZequan Wu #define WIN_SYM_PREFIX
1748c4208d5SZequan Wu #endif
1758c4208d5SZequan Wu #pragma comment(                                                               \
1768c4208d5SZequan Wu     linker, "/alternatename:" WIN_SYM_PREFIX INSTR_PROF_QUOTE(                 \
1778c4208d5SZequan Wu                 INSTR_PROF_PROFILE_COUNTER_BIAS_VAR) "=" WIN_SYM_PREFIX        \
1788c4208d5SZequan Wu                 INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR))
1798c4208d5SZequan Wu #else
1808c4208d5SZequan Wu COMPILER_RT_VISIBILITY extern intptr_t INSTR_PROF_PROFILE_COUNTER_BIAS_VAR
1818c4208d5SZequan Wu     __attribute__((weak, alias(INSTR_PROF_QUOTE(
1828c4208d5SZequan Wu                              INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR))));
1838c4208d5SZequan Wu #endif
1848c4208d5SZequan Wu static const int ContinuousModeSupported = 1;
1858c4208d5SZequan Wu static const int UseBiasVar = 1;
1868c4208d5SZequan Wu /* TODO: If there are two DSOs, the second DSO initilization will truncate the
1878c4208d5SZequan Wu  * first profile file. */
1888c4208d5SZequan Wu static const char *FileOpenMode = "w+b";
1898c4208d5SZequan Wu /* This symbol is defined by the compiler when runtime counter relocation is
1908c4208d5SZequan Wu  * used and runtime provides a weak alias so we can check if it's defined. */
1918c4208d5SZequan Wu static void *BiasAddr = &INSTR_PROF_PROFILE_COUNTER_BIAS_VAR;
1928c4208d5SZequan Wu static void *BiasDefaultAddr = &INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR;
mmapForContinuousMode(uint64_t CurrentFileOffset,FILE * File)1931b052451SZequan Wu static int mmapForContinuousMode(uint64_t CurrentFileOffset, FILE *File) {
1941b052451SZequan Wu   /* Get the sizes of various profile data sections. Taken from
1951b052451SZequan Wu    * __llvm_profile_get_size_for_buffer(). */
1961b052451SZequan Wu   const __llvm_profile_data *DataBegin = __llvm_profile_begin_data();
1971b052451SZequan Wu   const __llvm_profile_data *DataEnd = __llvm_profile_end_data();
198f2147375SEllis Hoag   const char *CountersBegin = __llvm_profile_begin_counters();
199f2147375SEllis Hoag   const char *CountersEnd = __llvm_profile_end_counters();
2001b052451SZequan Wu   uint64_t DataSize = __llvm_profile_get_data_size(DataBegin, DataEnd);
2011b052451SZequan Wu   /* Get the file size. */
2021b052451SZequan Wu   uint64_t FileSize = 0;
2031b052451SZequan Wu   if (getProfileFileSizeForMerging(File, &FileSize))
2041b052451SZequan Wu     return 1;
2051b052451SZequan Wu 
2061b052451SZequan Wu   /* Map the profile. */
2071b052451SZequan Wu   char *Profile = (char *)mmap(NULL, FileSize, PROT_READ | PROT_WRITE,
2081b052451SZequan Wu                                MAP_SHARED, fileno(File), 0);
2091b052451SZequan Wu   if (Profile == MAP_FAILED) {
2101b052451SZequan Wu     PROF_ERR("Unable to mmap profile: %s\n", strerror(errno));
2111b052451SZequan Wu     return 1;
2121b052451SZequan Wu   }
2131b052451SZequan Wu   const uint64_t CountersOffsetInBiasMode =
214f2147375SEllis Hoag       sizeof(__llvm_profile_header) + __llvm_write_binary_ids(NULL) + DataSize;
2151b052451SZequan Wu   /* Update the profile fields based on the current mapping. */
2161b052451SZequan Wu   INSTR_PROF_PROFILE_COUNTER_BIAS_VAR =
2171b052451SZequan Wu       (intptr_t)Profile - (uintptr_t)CountersBegin + CountersOffsetInBiasMode;
2181b052451SZequan Wu 
2191b052451SZequan Wu   /* Return the memory allocated for counters to OS. */
2201b052451SZequan Wu   lprofReleaseMemoryPagesToOS((uintptr_t)CountersBegin, (uintptr_t)CountersEnd);
2211b052451SZequan Wu   return 0;
2221b052451SZequan Wu }
2238c4208d5SZequan Wu #else
2248c4208d5SZequan Wu static const int ContinuousModeSupported = 0;
2258c4208d5SZequan Wu static const int UseBiasVar = 0;
2268c4208d5SZequan Wu static const char *FileOpenMode = "a+b";
2278c4208d5SZequan Wu static void *BiasAddr = NULL;
2288c4208d5SZequan Wu static void *BiasDefaultAddr = NULL;
mmapForContinuousMode(uint64_t CurrentFileOffset,FILE * File)2291b052451SZequan Wu static int mmapForContinuousMode(uint64_t CurrentFileOffset, FILE *File) {
2301b052451SZequan Wu   return 0;
2311b052451SZequan Wu }
2328c4208d5SZequan Wu #endif
2338c4208d5SZequan Wu 
isProfileMergeRequested(void)234*bdbfaf0cSAaron Ballman static int isProfileMergeRequested(void) { return ProfileMergeRequested; }
setProfileMergeRequested(int EnableMerge)2356694b2b3SSajjad Mirza static void setProfileMergeRequested(int EnableMerge) {
2366694b2b3SSajjad Mirza   ProfileMergeRequested = EnableMerge;
2376694b2b3SSajjad Mirza }
2386694b2b3SSajjad Mirza 
2396694b2b3SSajjad Mirza static FILE *ProfileFile = NULL;
getProfileFile(void)240*bdbfaf0cSAaron Ballman static FILE *getProfileFile(void) { return ProfileFile; }
setProfileFile(FILE * File)2416694b2b3SSajjad Mirza static void setProfileFile(FILE *File) { ProfileFile = File; }
2426694b2b3SSajjad Mirza 
243*bdbfaf0cSAaron Ballman static int getCurFilenameLength(void);
24473053b22STeresa Johnson static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf);
doMerging(void)245*bdbfaf0cSAaron Ballman static unsigned doMerging(void) {
2466694b2b3SSajjad Mirza   return lprofCurFilename.MergePoolSize || isProfileMergeRequested();
2476694b2b3SSajjad Mirza }
248b1cc6d56SJoerg Sonnenberger 
2492d5bf07cSXinliang David Li /* Return 1 if there is an error, otherwise return  0.  */
fileWriter(ProfDataWriter * This,ProfDataIOVec * IOVecs,uint32_t NumIOVecs)250967669f6SXinliang David Li static uint32_t fileWriter(ProfDataWriter *This, ProfDataIOVec *IOVecs,
251967669f6SXinliang David Li                            uint32_t NumIOVecs) {
2522d5bf07cSXinliang David Li   uint32_t I;
253967669f6SXinliang David Li   FILE *File = (FILE *)This->WriterCtx;
2545a486e0fSVedant Kumar   char Zeroes[sizeof(uint64_t)] = {0};
2552d5bf07cSXinliang David Li   for (I = 0; I < NumIOVecs; I++) {
256f50cc3edSXinliang David Li     if (IOVecs[I].Data) {
2572d5bf07cSXinliang David Li       if (fwrite(IOVecs[I].Data, IOVecs[I].ElmSize, IOVecs[I].NumElm, File) !=
2582d5bf07cSXinliang David Li           IOVecs[I].NumElm)
2592d5bf07cSXinliang David Li         return 1;
2605a486e0fSVedant Kumar     } else if (IOVecs[I].UseZeroPadding) {
2615a486e0fSVedant Kumar       size_t BytesToWrite = IOVecs[I].ElmSize * IOVecs[I].NumElm;
2625a486e0fSVedant Kumar       while (BytesToWrite > 0) {
2635a486e0fSVedant Kumar         size_t PartialWriteLen =
2645a486e0fSVedant Kumar             (sizeof(uint64_t) > BytesToWrite) ? BytesToWrite : sizeof(uint64_t);
2655a486e0fSVedant Kumar         if (fwrite(Zeroes, sizeof(uint8_t), PartialWriteLen, File) !=
2665a486e0fSVedant Kumar             PartialWriteLen) {
2675a486e0fSVedant Kumar           return 1;
2685a486e0fSVedant Kumar         }
2695a486e0fSVedant Kumar         BytesToWrite -= PartialWriteLen;
2705a486e0fSVedant Kumar       }
271f50cc3edSXinliang David Li     } else {
272f50cc3edSXinliang David Li       if (fseek(File, IOVecs[I].ElmSize * IOVecs[I].NumElm, SEEK_CUR) == -1)
273f50cc3edSXinliang David Li         return 1;
274f50cc3edSXinliang David Li     }
2751d8d46aeSXinliang David Li   }
2762d5bf07cSXinliang David Li   return 0;
2772d5bf07cSXinliang David Li }
278cf4bb960SDuncan P. N. Exon Smith 
279e73ae9a1SManman Ren /* TODO: make buffer size controllable by an internal option, and compiler can pass the size
280e73ae9a1SManman Ren    to runtime via a variable. */
orderFileWriter(FILE * File,const uint32_t * DataStart)281e73ae9a1SManman Ren static uint32_t orderFileWriter(FILE *File, const uint32_t *DataStart) {
282e73ae9a1SManman Ren   if (fwrite(DataStart, sizeof(uint32_t), INSTR_ORDER_FILE_BUFFER_SIZE, File) !=
283e73ae9a1SManman Ren       INSTR_ORDER_FILE_BUFFER_SIZE)
284e73ae9a1SManman Ren     return 1;
285e73ae9a1SManman Ren   return 0;
286e73ae9a1SManman Ren }
287e73ae9a1SManman Ren 
initFileWriter(ProfDataWriter * This,FILE * File)288967669f6SXinliang David Li static void initFileWriter(ProfDataWriter *This, FILE *File) {
289967669f6SXinliang David Li   This->Write = fileWriter;
290967669f6SXinliang David Li   This->WriterCtx = File;
291967669f6SXinliang David Li }
292967669f6SXinliang David Li 
293cda3bc20SXinliang David Li COMPILER_RT_VISIBILITY ProfBufferIO *
lprofCreateBufferIOInternal(void * File,uint32_t BufferSz)294cf1a8d69SXinliang David Li lprofCreateBufferIOInternal(void *File, uint32_t BufferSz) {
295609fae38SXinliang David Li   FreeHook = &free;
296609fae38SXinliang David Li   DynamicBufferIOBuffer = (uint8_t *)calloc(BufferSz, 1);
297609fae38SXinliang David Li   VPBufferSize = BufferSz;
298967669f6SXinliang David Li   ProfDataWriter *fileWriter =
299967669f6SXinliang David Li       (ProfDataWriter *)calloc(sizeof(ProfDataWriter), 1);
300967669f6SXinliang David Li   initFileWriter(fileWriter, File);
301967669f6SXinliang David Li   ProfBufferIO *IO = lprofCreateBufferIO(fileWriter);
302967669f6SXinliang David Li   IO->OwnFileWriter = 1;
303967669f6SXinliang David Li   return IO;
304609fae38SXinliang David Li }
305609fae38SXinliang David Li 
setupIOBuffer(void)306*bdbfaf0cSAaron Ballman static void setupIOBuffer(void) {
307609fae38SXinliang David Li   const char *BufferSzStr = 0;
308609fae38SXinliang David Li   BufferSzStr = getenv("LLVM_VP_BUFFER_SIZE");
309609fae38SXinliang David Li   if (BufferSzStr && BufferSzStr[0]) {
310609fae38SXinliang David Li     VPBufferSize = atoi(BufferSzStr);
311609fae38SXinliang David Li     DynamicBufferIOBuffer = (uint8_t *)calloc(VPBufferSize, 1);
312609fae38SXinliang David Li   }
313cda3bc20SXinliang David Li }
314cda3bc20SXinliang David Li 
315e7aab320SVedant Kumar /* Get the size of the profile file. If there are any errors, print the
316e7aab320SVedant Kumar  * message under the assumption that the profile is being read for merging
317e7aab320SVedant Kumar  * purposes, and return -1. Otherwise return the file size in the inout param
318e7aab320SVedant Kumar  * \p ProfileFileSize. */
getProfileFileSizeForMerging(FILE * ProfileFile,uint64_t * ProfileFileSize)319e7aab320SVedant Kumar static int getProfileFileSizeForMerging(FILE *ProfileFile,
320e7aab320SVedant Kumar                                         uint64_t *ProfileFileSize) {
321e7aab320SVedant Kumar   if (fseek(ProfileFile, 0L, SEEK_END) == -1) {
322e7aab320SVedant Kumar     PROF_ERR("Unable to merge profile data, unable to get size: %s\n",
323e7aab320SVedant Kumar              strerror(errno));
324e7aab320SVedant Kumar     return -1;
325e7aab320SVedant Kumar   }
326e7aab320SVedant Kumar   *ProfileFileSize = ftell(ProfileFile);
327e7aab320SVedant Kumar 
328e7aab320SVedant Kumar   /* Restore file offset.  */
329e7aab320SVedant Kumar   if (fseek(ProfileFile, 0L, SEEK_SET) == -1) {
330e7aab320SVedant Kumar     PROF_ERR("Unable to merge profile data, unable to rewind: %s\n",
331e7aab320SVedant Kumar              strerror(errno));
332e7aab320SVedant Kumar     return -1;
333e7aab320SVedant Kumar   }
334e7aab320SVedant Kumar 
335e7aab320SVedant Kumar   if (*ProfileFileSize > 0 &&
336e7aab320SVedant Kumar       *ProfileFileSize < sizeof(__llvm_profile_header)) {
337e7aab320SVedant Kumar     PROF_WARN("Unable to merge profile data: %s\n",
338e7aab320SVedant Kumar               "source profile file is too small.");
339e7aab320SVedant Kumar     return -1;
340e7aab320SVedant Kumar   }
341e7aab320SVedant Kumar   return 0;
342e7aab320SVedant Kumar }
343e7aab320SVedant Kumar 
344e7aab320SVedant Kumar /* mmap() \p ProfileFile for profile merging purposes, assuming that an
345e7aab320SVedant Kumar  * exclusive lock is held on the file and that \p ProfileFileSize is the
346e7aab320SVedant Kumar  * length of the file. Return the mmap'd buffer in the inout variable
347e7aab320SVedant Kumar  * \p ProfileBuffer. Returns -1 on failure. On success, the caller is
348e7aab320SVedant Kumar  * responsible for unmapping the mmap'd buffer in \p ProfileBuffer. */
mmapProfileForMerging(FILE * ProfileFile,uint64_t ProfileFileSize,char ** ProfileBuffer)349e7aab320SVedant Kumar static int mmapProfileForMerging(FILE *ProfileFile, uint64_t ProfileFileSize,
350e7aab320SVedant Kumar                                  char **ProfileBuffer) {
351e7aab320SVedant Kumar   *ProfileBuffer = mmap(NULL, ProfileFileSize, PROT_READ, MAP_SHARED | MAP_FILE,
352e7aab320SVedant Kumar                         fileno(ProfileFile), 0);
353e7aab320SVedant Kumar   if (*ProfileBuffer == MAP_FAILED) {
354e7aab320SVedant Kumar     PROF_ERR("Unable to merge profile data, mmap failed: %s\n",
355e7aab320SVedant Kumar              strerror(errno));
356e7aab320SVedant Kumar     return -1;
357e7aab320SVedant Kumar   }
358e7aab320SVedant Kumar 
359e7aab320SVedant Kumar   if (__llvm_profile_check_compatibility(*ProfileBuffer, ProfileFileSize)) {
360e7aab320SVedant Kumar     (void)munmap(*ProfileBuffer, ProfileFileSize);
361e7aab320SVedant Kumar     PROF_WARN("Unable to merge profile data: %s\n",
362e7aab320SVedant Kumar               "source profile file is not compatible.");
363e7aab320SVedant Kumar     return -1;
364e7aab320SVedant Kumar   }
365e7aab320SVedant Kumar   return 0;
366e7aab320SVedant Kumar }
367e7aab320SVedant Kumar 
368e2ce2e00SXinliang David Li /* Read profile data in \c ProfileFile and merge with in-memory
369e2ce2e00SXinliang David Li    profile counters. Returns -1 if there is fatal error, otheriwse
370f50cc3edSXinliang David Li    0 is returned. Returning 0 does not mean merge is actually
371f50cc3edSXinliang David Li    performed. If merge is actually done, *MergeDone is set to 1.
372e2ce2e00SXinliang David Li */
doProfileMerging(FILE * ProfileFile,int * MergeDone)373f50cc3edSXinliang David Li static int doProfileMerging(FILE *ProfileFile, int *MergeDone) {
374e2ce2e00SXinliang David Li   uint64_t ProfileFileSize;
375e2ce2e00SXinliang David Li   char *ProfileBuffer;
376e2ce2e00SXinliang David Li 
377e7aab320SVedant Kumar   /* Get the size of the profile on disk. */
378e7aab320SVedant Kumar   if (getProfileFileSizeForMerging(ProfileFile, &ProfileFileSize) == -1)
379e2ce2e00SXinliang David Li     return -1;
380e2ce2e00SXinliang David Li 
381e2ce2e00SXinliang David Li   /* Nothing to merge.  */
382e7aab320SVedant Kumar   if (!ProfileFileSize)
383e2ce2e00SXinliang David Li     return 0;
384e2ce2e00SXinliang David Li 
385e7aab320SVedant Kumar   /* mmap() the profile and check that it is compatible with the data in
386e7aab320SVedant Kumar    * the current image. */
387e7aab320SVedant Kumar   if (mmapProfileForMerging(ProfileFile, ProfileFileSize, &ProfileBuffer) == -1)
388e2ce2e00SXinliang David Li     return -1;
389e2ce2e00SXinliang David Li 
390e2ce2e00SXinliang David Li   /* Now start merging */
391189428c8SArthur Eubanks   if (__llvm_profile_merge_from_buffer(ProfileBuffer, ProfileFileSize)) {
392189428c8SArthur Eubanks     PROF_ERR("%s\n", "Invalid profile data to merge");
393189428c8SArthur Eubanks     (void)munmap(ProfileBuffer, ProfileFileSize);
394189428c8SArthur Eubanks     return -1;
395189428c8SArthur Eubanks   }
396e2ce2e00SXinliang David Li 
397189428c8SArthur Eubanks   // Truncate the file in case merging of value profile did not happen to
39895ab7582SRong Xu   // prevent from leaving garbage data at the end of the profile file.
399e29063b1SVitaly Buka   (void)COMPILER_RT_FTRUNCATE(ProfileFile,
400e29063b1SVitaly Buka                               __llvm_profile_get_size_for_buffer());
40195ab7582SRong Xu 
40295ab7582SRong Xu   (void)munmap(ProfileBuffer, ProfileFileSize);
403f50cc3edSXinliang David Li   *MergeDone = 1;
404f50cc3edSXinliang David Li 
405e2ce2e00SXinliang David Li   return 0;
406e2ce2e00SXinliang David Li }
407e2ce2e00SXinliang David Li 
408f2d94810SXinliang David Li /* Create the directory holding the file, if needed. */
createProfileDir(const char * Filename)409f2d94810SXinliang David Li static void createProfileDir(const char *Filename) {
410f2d94810SXinliang David Li   size_t Length = strlen(Filename);
411f2d94810SXinliang David Li   if (lprofFindFirstDirSeparator(Filename)) {
412f2d94810SXinliang David Li     char *Copy = (char *)COMPILER_RT_ALLOCA(Length + 1);
413f2d94810SXinliang David Li     strncpy(Copy, Filename, Length + 1);
414f2d94810SXinliang David Li     __llvm_profile_recursive_mkdir(Copy);
415f2d94810SXinliang David Li   }
416f2d94810SXinliang David Li }
417f2d94810SXinliang David Li 
418e2ce2e00SXinliang David Li /* Open the profile data for merging. It opens the file in r+b mode with
419e2ce2e00SXinliang David Li  * file locking.  If the file has content which is compatible with the
420e2ce2e00SXinliang David Li  * current process, it also reads in the profile data in the file and merge
421e2ce2e00SXinliang David Li  * it with in-memory counters. After the profile data is merged in memory,
422e2ce2e00SXinliang David Li  * the original profile data is truncated and gets ready for the profile
423e2ce2e00SXinliang David Li  * dumper. With profile merging enabled, each executable as well as any of
424e2ce2e00SXinliang David Li  * its instrumented shared libraries dump profile data into their own data file.
425e2ce2e00SXinliang David Li */
openFileForMerging(const char * ProfileFileName,int * MergeDone)426f50cc3edSXinliang David Li static FILE *openFileForMerging(const char *ProfileFileName, int *MergeDone) {
4276694b2b3SSajjad Mirza   FILE *ProfileFile = NULL;
428e2ce2e00SXinliang David Li   int rc;
429e2ce2e00SXinliang David Li 
4306694b2b3SSajjad Mirza   ProfileFile = getProfileFile();
4316694b2b3SSajjad Mirza   if (ProfileFile) {
4326694b2b3SSajjad Mirza     lprofLockFileHandle(ProfileFile);
4336694b2b3SSajjad Mirza   } else {
434f2d94810SXinliang David Li     createProfileDir(ProfileFileName);
435e2ce2e00SXinliang David Li     ProfileFile = lprofOpenFileEx(ProfileFileName);
4366694b2b3SSajjad Mirza   }
437e2ce2e00SXinliang David Li   if (!ProfileFile)
438e2ce2e00SXinliang David Li     return NULL;
439e2ce2e00SXinliang David Li 
440f50cc3edSXinliang David Li   rc = doProfileMerging(ProfileFile, MergeDone);
441f50cc3edSXinliang David Li   if (rc || (!*MergeDone && COMPILER_RT_FTRUNCATE(ProfileFile, 0L)) ||
442e2ce2e00SXinliang David Li       fseek(ProfileFile, 0L, SEEK_SET) == -1) {
443e2ce2e00SXinliang David Li     PROF_ERR("Profile Merging of file %s failed: %s\n", ProfileFileName,
444e2ce2e00SXinliang David Li              strerror(errno));
445e2ce2e00SXinliang David Li     fclose(ProfileFile);
446e2ce2e00SXinliang David Li     return NULL;
447e2ce2e00SXinliang David Li   }
448e2ce2e00SXinliang David Li   return ProfileFile;
449e2ce2e00SXinliang David Li }
450e2ce2e00SXinliang David Li 
getFileObject(const char * OutputName)4516694b2b3SSajjad Mirza static FILE *getFileObject(const char *OutputName) {
4526694b2b3SSajjad Mirza   FILE *File;
4536694b2b3SSajjad Mirza   File = getProfileFile();
4546694b2b3SSajjad Mirza   if (File != NULL) {
4556694b2b3SSajjad Mirza     return File;
4566694b2b3SSajjad Mirza   }
4576694b2b3SSajjad Mirza 
4586694b2b3SSajjad Mirza   return fopen(OutputName, "ab");
4596694b2b3SSajjad Mirza }
4606694b2b3SSajjad Mirza 
461315e49d2SXinliang David Li /* Write profile data to file \c OutputName.  */
writeFile(const char * OutputName)462315e49d2SXinliang David Li static int writeFile(const char *OutputName) {
463be0a5e17SDuncan P. N. Exon Smith   int RetVal;
464be0a5e17SDuncan P. N. Exon Smith   FILE *OutputFile;
46555e4d66fSDuncan P. N. Exon Smith 
466f50cc3edSXinliang David Li   int MergeDone = 0;
46795ab7582SRong Xu   VPMergeHook = &lprofMergeValueProfData;
4686694b2b3SSajjad Mirza   if (doMerging())
46905d44139SHans Wennborg     OutputFile = openFileForMerging(OutputName, &MergeDone);
4706694b2b3SSajjad Mirza   else
4716694b2b3SSajjad Mirza     OutputFile = getFileObject(OutputName);
472e2ce2e00SXinliang David Li 
473be0a5e17SDuncan P. N. Exon Smith   if (!OutputFile)
474be0a5e17SDuncan P. N. Exon Smith     return -1;
475be0a5e17SDuncan P. N. Exon Smith 
476315e49d2SXinliang David Li   FreeHook = &free;
477315e49d2SXinliang David Li   setupIOBuffer();
478967669f6SXinliang David Li   ProfDataWriter fileWriter;
479967669f6SXinliang David Li   initFileWriter(&fileWriter, OutputFile);
480f50cc3edSXinliang David Li   RetVal = lprofWriteData(&fileWriter, lprofGetVPDataReader(), MergeDone);
481be0a5e17SDuncan P. N. Exon Smith 
4826694b2b3SSajjad Mirza   if (OutputFile == getProfileFile()) {
4836694b2b3SSajjad Mirza     fflush(OutputFile);
4846694b2b3SSajjad Mirza     if (doMerging()) {
4856694b2b3SSajjad Mirza       lprofUnlockFileHandle(OutputFile);
4866694b2b3SSajjad Mirza     }
4876694b2b3SSajjad Mirza   } else {
488be0a5e17SDuncan P. N. Exon Smith     fclose(OutputFile);
4896694b2b3SSajjad Mirza   }
4906694b2b3SSajjad Mirza 
491be0a5e17SDuncan P. N. Exon Smith   return RetVal;
492be0a5e17SDuncan P. N. Exon Smith }
493be0a5e17SDuncan P. N. Exon Smith 
494e73ae9a1SManman Ren /* Write order data to file \c OutputName.  */
writeOrderFile(const char * OutputName)495e73ae9a1SManman Ren static int writeOrderFile(const char *OutputName) {
496e73ae9a1SManman Ren   int RetVal;
497e73ae9a1SManman Ren   FILE *OutputFile;
498e73ae9a1SManman Ren 
499e73ae9a1SManman Ren   OutputFile = fopen(OutputName, "w");
500e73ae9a1SManman Ren 
501e73ae9a1SManman Ren   if (!OutputFile) {
502e73ae9a1SManman Ren     PROF_WARN("can't open file with mode ab: %s\n", OutputName);
503e73ae9a1SManman Ren     return -1;
504e73ae9a1SManman Ren   }
505e73ae9a1SManman Ren 
506e73ae9a1SManman Ren   FreeHook = &free;
507e73ae9a1SManman Ren   setupIOBuffer();
508e73ae9a1SManman Ren   const uint32_t *DataBegin = __llvm_profile_begin_orderfile();
509e73ae9a1SManman Ren   RetVal = orderFileWriter(OutputFile, DataBegin);
510e73ae9a1SManman Ren 
511e73ae9a1SManman Ren   fclose(OutputFile);
512e73ae9a1SManman Ren   return RetVal;
513e73ae9a1SManman Ren }
514e73ae9a1SManman Ren 
515a49795d8SVedant Kumar #define LPROF_INIT_ONCE_ENV "__LLVM_PROFILE_RT_INIT_ONCE"
516a49795d8SVedant Kumar 
truncateCurrentFile(void)51755e4d66fSDuncan P. N. Exon Smith static void truncateCurrentFile(void) {
518c9c7a3e4SVasileios Kalintiris   const char *Filename;
519315e49d2SXinliang David Li   char *FilenameBuf;
520c9c7a3e4SVasileios Kalintiris   FILE *File;
521315e49d2SXinliang David Li   int Length;
522c9c7a3e4SVasileios Kalintiris 
523315e49d2SXinliang David Li   Length = getCurFilenameLength();
524315e49d2SXinliang David Li   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
52573053b22STeresa Johnson   Filename = getCurFilename(FilenameBuf, 0);
526315e49d2SXinliang David Li   if (!Filename)
52755e4d66fSDuncan P. N. Exon Smith     return;
52855e4d66fSDuncan P. N. Exon Smith 
529d889d1efSVedant Kumar   /* Only create the profile directory and truncate an existing profile once.
530d889d1efSVedant Kumar    * In continuous mode, this is necessary, as the profile is written-to by the
531d889d1efSVedant Kumar    * runtime initializer. */
532a49795d8SVedant Kumar   int initialized = getenv(LPROF_INIT_ONCE_ENV) != NULL;
533d889d1efSVedant Kumar   if (initialized)
534d889d1efSVedant Kumar     return;
535a49795d8SVedant Kumar #if defined(_WIN32)
536a49795d8SVedant Kumar   _putenv(LPROF_INIT_ONCE_ENV "=" LPROF_INIT_ONCE_ENV);
537a49795d8SVedant Kumar #else
538a49795d8SVedant Kumar   setenv(LPROF_INIT_ONCE_ENV, LPROF_INIT_ONCE_ENV, 1);
539a49795d8SVedant Kumar #endif
540d889d1efSVedant Kumar 
5412492b5a1SVedant Kumar   /* Create the profile dir (even if online merging is enabled), so that
5422492b5a1SVedant Kumar    * the profile file can be set up if continuous mode is enabled. */
543f2d94810SXinliang David Li   createProfileDir(Filename);
544f2d94810SXinliang David Li 
5452492b5a1SVedant Kumar   /* By pass file truncation to allow online raw profile merging. */
5462492b5a1SVedant Kumar   if (lprofCurFilename.MergePoolSize)
5472492b5a1SVedant Kumar     return;
5482492b5a1SVedant Kumar 
54955e4d66fSDuncan P. N. Exon Smith   /* Truncate the file.  Later we'll reopen and append. */
550c9c7a3e4SVasileios Kalintiris   File = fopen(Filename, "w");
55155e4d66fSDuncan P. N. Exon Smith   if (!File)
55255e4d66fSDuncan P. N. Exon Smith     return;
55355e4d66fSDuncan P. N. Exon Smith   fclose(File);
55455e4d66fSDuncan P. N. Exon Smith }
55555e4d66fSDuncan P. N. Exon Smith 
55654902e00SPetr Hosek /* Write a partial profile to \p Filename, which is required to be backed by
55754902e00SPetr Hosek  * the open file object \p File. */
writeProfileWithFileObject(const char * Filename,FILE * File)55854902e00SPetr Hosek static int writeProfileWithFileObject(const char *Filename, FILE *File) {
55954902e00SPetr Hosek   setProfileFile(File);
56054902e00SPetr Hosek   int rc = writeFile(Filename);
56154902e00SPetr Hosek   if (rc)
56254902e00SPetr Hosek     PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));
56354902e00SPetr Hosek   setProfileFile(NULL);
56454902e00SPetr Hosek   return rc;
565d3db13afSPetr Hosek }
56654902e00SPetr Hosek 
initializeProfileForContinuousMode(void)567d889d1efSVedant Kumar static void initializeProfileForContinuousMode(void) {
568d889d1efSVedant Kumar   if (!__llvm_profile_is_continuous_mode_enabled())
569d889d1efSVedant Kumar     return;
5708c4208d5SZequan Wu   if (!ContinuousModeSupported) {
5718c4208d5SZequan Wu     PROF_ERR("%s\n", "continuous mode is unsupported on this platform");
5728c4208d5SZequan Wu     return;
5738c4208d5SZequan Wu   }
5748c4208d5SZequan Wu   if (UseBiasVar && BiasAddr == BiasDefaultAddr) {
5758c4208d5SZequan Wu     PROF_ERR("%s\n", "__llvm_profile_counter_bias is undefined");
5768c4208d5SZequan Wu     return;
5778c4208d5SZequan Wu   }
578d889d1efSVedant Kumar 
5791b052451SZequan Wu   /* Get the sizes of counter section. */
580f2147375SEllis Hoag   uint64_t CountersSize = __llvm_profile_get_counters_size(
581f2147375SEllis Hoag       __llvm_profile_begin_counters(), __llvm_profile_end_counters());
582d889d1efSVedant Kumar 
583d889d1efSVedant Kumar   int Length = getCurFilenameLength();
584d889d1efSVedant Kumar   char *FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
585d889d1efSVedant Kumar   const char *Filename = getCurFilename(FilenameBuf, 0);
586d889d1efSVedant Kumar   if (!Filename)
587d889d1efSVedant Kumar     return;
5882492b5a1SVedant Kumar 
5892492b5a1SVedant Kumar   FILE *File = NULL;
5902129c4a8SZequan Wu   uint64_t CurrentFileOffset = 0;
5918c4208d5SZequan Wu   if (doMerging()) {
5922492b5a1SVedant Kumar     /* We are merging profiles. Map the counter section as shared memory into
5932492b5a1SVedant Kumar      * the profile, i.e. into each participating process. An increment in one
5942492b5a1SVedant Kumar      * process should be visible to every other process with the same counter
5952492b5a1SVedant Kumar      * section mapped. */
5962492b5a1SVedant Kumar     File = lprofOpenFileEx(Filename);
5972492b5a1SVedant Kumar     if (!File)
5982492b5a1SVedant Kumar       return;
5992492b5a1SVedant Kumar 
6008c4208d5SZequan Wu     uint64_t ProfileFileSize = 0;
6018c4208d5SZequan Wu     if (getProfileFileSizeForMerging(File, &ProfileFileSize) == -1) {
6028c4208d5SZequan Wu       lprofUnlockFileHandle(File);
6038c4208d5SZequan Wu       fclose(File);
6048c4208d5SZequan Wu       return;
6058c4208d5SZequan Wu     }
6062492b5a1SVedant Kumar     if (ProfileFileSize == 0) {
6072492b5a1SVedant Kumar       /* Grow the profile so that mmap() can succeed.  Leak the file handle, as
6082492b5a1SVedant Kumar        * the file should stay open. */
6098c4208d5SZequan Wu       if (writeProfileWithFileObject(Filename, File) != 0) {
6108c4208d5SZequan Wu         lprofUnlockFileHandle(File);
6118c4208d5SZequan Wu         fclose(File);
6128c4208d5SZequan Wu         return;
6138c4208d5SZequan Wu       }
6142492b5a1SVedant Kumar     } else {
6152492b5a1SVedant Kumar       /* The merged profile has a non-zero length. Check that it is compatible
6162492b5a1SVedant Kumar        * with the data in this process. */
6172492b5a1SVedant Kumar       char *ProfileBuffer;
6182129c4a8SZequan Wu       if (mmapProfileForMerging(File, ProfileFileSize, &ProfileBuffer) == -1) {
6198c4208d5SZequan Wu         lprofUnlockFileHandle(File);
6208c4208d5SZequan Wu         fclose(File);
6218c4208d5SZequan Wu         return;
6228c4208d5SZequan Wu       }
6232129c4a8SZequan Wu       (void)munmap(ProfileBuffer, ProfileFileSize);
6248c4208d5SZequan Wu     }
6258c4208d5SZequan Wu   } else {
6268c4208d5SZequan Wu     File = fopen(Filename, FileOpenMode);
6278c4208d5SZequan Wu     if (!File)
6288c4208d5SZequan Wu       return;
6298c4208d5SZequan Wu     /* Check that the offset within the file is page-aligned. */
6302129c4a8SZequan Wu     CurrentFileOffset = ftell(File);
6318c4208d5SZequan Wu     unsigned PageSize = getpagesize();
6328c4208d5SZequan Wu     if (CurrentFileOffset % PageSize != 0) {
6338c4208d5SZequan Wu       PROF_ERR("Continuous counter sync mode is enabled, but raw profile is not"
6348c4208d5SZequan Wu                "page-aligned. CurrentFileOffset = %" PRIu64 ", pagesz = %u.\n",
6358c4208d5SZequan Wu                (uint64_t)CurrentFileOffset, PageSize);
6368c4208d5SZequan Wu       return;
6378c4208d5SZequan Wu     }
6388c4208d5SZequan Wu     if (writeProfileWithFileObject(Filename, File) != 0) {
6398c4208d5SZequan Wu       fclose(File);
6408c4208d5SZequan Wu       return;
6412492b5a1SVedant Kumar     }
6422492b5a1SVedant Kumar   }
6432492b5a1SVedant Kumar 
6447014a101SVedant Kumar   /* mmap() the profile counters so long as there is at least one counter.
6457014a101SVedant Kumar    * If there aren't any counters, mmap() would fail with EINVAL. */
6461b052451SZequan Wu   if (CountersSize > 0)
6471b052451SZequan Wu     mmapForContinuousMode(CurrentFileOffset, File);
648ff427909SPetr Hosek 
6498c4208d5SZequan Wu   if (doMerging()) {
65054902e00SPetr Hosek     lprofUnlockFileHandle(File);
65154902e00SPetr Hosek     fclose(File);
65254902e00SPetr Hosek   }
65354902e00SPetr Hosek }
65454902e00SPetr Hosek 
655153e8b6cSXinliang David Li static const char *DefaultProfileName = "default.profraw";
resetFilenameToDefault(void)656315e49d2SXinliang David Li static void resetFilenameToDefault(void) {
65714c91c4eSXinliang David Li   if (lprofCurFilename.FilenamePat && lprofCurFilename.OwnsFilenamePat) {
65814c91c4eSXinliang David Li     free((void *)lprofCurFilename.FilenamePat);
65914c91c4eSXinliang David Li   }
6607f08d12bSXinliang David Li   memset(&lprofCurFilename, 0, sizeof(lprofCurFilename));
661153e8b6cSXinliang David Li   lprofCurFilename.FilenamePat = DefaultProfileName;
662153e8b6cSXinliang David Li   lprofCurFilename.PNS = PNS_default;
663315e49d2SXinliang David Li }
66455e4d66fSDuncan P. N. Exon Smith 
getMergePoolSize(const char * FilenamePat,int * I)665c5b94ea2SFangrui Song static unsigned getMergePoolSize(const char *FilenamePat, int *I) {
666c5b94ea2SFangrui Song   unsigned J = 0, Num = 0;
667c5b94ea2SFangrui Song   for (;; ++J) {
668c5b94ea2SFangrui Song     char C = FilenamePat[*I + J];
669c5b94ea2SFangrui Song     if (C == 'm') {
670c5b94ea2SFangrui Song       *I += J;
671c5b94ea2SFangrui Song       return Num ? Num : 1;
672c5b94ea2SFangrui Song     }
673c5b94ea2SFangrui Song     if (C < '0' || C > '9')
674c5b94ea2SFangrui Song       break;
675c5b94ea2SFangrui Song     Num = Num * 10 + C - '0';
676c5b94ea2SFangrui Song 
677c5b94ea2SFangrui Song     /* If FilenamePat[*I+J] is between '0' and '9', the next byte is guaranteed
678e2ce2e00SXinliang David Li      * to be in-bound as the string is null terminated. */
679c5b94ea2SFangrui Song   }
680c5b94ea2SFangrui Song   return 0;
681e2ce2e00SXinliang David Li }
6827f08d12bSXinliang David Li 
683a7d48261SVedant Kumar /* Assert that Idx does index past a string null terminator. Return the
684a7d48261SVedant Kumar  * result of the check. */
checkBounds(int Idx,int Strlen)685a7d48261SVedant Kumar static int checkBounds(int Idx, int Strlen) {
686a7d48261SVedant Kumar   assert(Idx <= Strlen && "Indexing past string null terminator");
687a7d48261SVedant Kumar   return Idx <= Strlen;
688a7d48261SVedant Kumar }
689a7d48261SVedant Kumar 
690e2ce2e00SXinliang David Li /* Parses the pattern string \p FilenamePat and stores the result to
691e2ce2e00SXinliang David Li  * lprofcurFilename structure. */
parseFilenamePattern(const char * FilenamePat,unsigned CopyFilenamePat)69214c91c4eSXinliang David Li static int parseFilenamePattern(const char *FilenamePat,
69314c91c4eSXinliang David Li                                 unsigned CopyFilenamePat) {
694315e49d2SXinliang David Li   int NumPids = 0, NumHosts = 0, I;
6957f08d12bSXinliang David Li   char *PidChars = &lprofCurFilename.PidChars[0];
6967f08d12bSXinliang David Li   char *Hostname = &lprofCurFilename.Hostname[0];
697e2ce2e00SXinliang David Li   int MergingEnabled = 0;
698a7d48261SVedant Kumar   int FilenamePatLen = strlen(FilenamePat);
699c9c7a3e4SVasileios Kalintiris 
70073053b22STeresa Johnson   /* Clean up cached prefix and filename.  */
701b061cdb0SXinliang David Li   if (lprofCurFilename.ProfilePathPrefix)
702b061cdb0SXinliang David Li     free((void *)lprofCurFilename.ProfilePathPrefix);
70373053b22STeresa Johnson 
70414c91c4eSXinliang David Li   if (lprofCurFilename.FilenamePat && lprofCurFilename.OwnsFilenamePat) {
70514c91c4eSXinliang David Li     free((void *)lprofCurFilename.FilenamePat);
70614c91c4eSXinliang David Li   }
70714c91c4eSXinliang David Li 
70863600c74SIgor Kudrin   memset(&lprofCurFilename, 0, sizeof(lprofCurFilename));
70963600c74SIgor Kudrin 
71014c91c4eSXinliang David Li   if (!CopyFilenamePat)
7117f08d12bSXinliang David Li     lprofCurFilename.FilenamePat = FilenamePat;
71214c91c4eSXinliang David Li   else {
71314c91c4eSXinliang David Li     lprofCurFilename.FilenamePat = strdup(FilenamePat);
71414c91c4eSXinliang David Li     lprofCurFilename.OwnsFilenamePat = 1;
71514c91c4eSXinliang David Li   }
716be0a5e17SDuncan P. N. Exon Smith   /* Check the filename for "%p", which indicates a pid-substitution. */
717a7d48261SVedant Kumar   for (I = 0; checkBounds(I, FilenamePatLen) && FilenamePat[I]; ++I) {
718315e49d2SXinliang David Li     if (FilenamePat[I] == '%') {
719a7d48261SVedant Kumar       ++I; /* Advance to the next character. */
720a7d48261SVedant Kumar       if (!checkBounds(I, FilenamePatLen))
721a7d48261SVedant Kumar         break;
722a7d48261SVedant Kumar       if (FilenamePat[I] == 'p') {
723be0a5e17SDuncan P. N. Exon Smith         if (!NumPids++) {
724d7c9336aSVedant Kumar           if (snprintf(PidChars, MAX_PID_SIZE, "%ld", (long)getpid()) <= 0) {
7259ee65acaSBob Haarman             PROF_WARN("Unable to get pid for filename pattern %s. Using the "
7269ee65acaSBob Haarman                       "default name.",
727315e49d2SXinliang David Li                       FilenamePat);
728be0a5e17SDuncan P. N. Exon Smith             return -1;
729be0a5e17SDuncan P. N. Exon Smith           }
730315e49d2SXinliang David Li         }
731315e49d2SXinliang David Li       } else if (FilenamePat[I] == 'h') {
732a06e8ca6SVedant Kumar         if (!NumHosts++)
733315e49d2SXinliang David Li           if (COMPILER_RT_GETHOSTNAME(Hostname, COMPILER_RT_MAX_HOSTLEN)) {
7349ee65acaSBob Haarman             PROF_WARN("Unable to get hostname for filename pattern %s. Using "
7359ee65acaSBob Haarman                       "the default name.",
736315e49d2SXinliang David Li                       FilenamePat);
737a06e8ca6SVedant Kumar             return -1;
738315e49d2SXinliang David Li           }
73962c37277SVedant Kumar       } else if (FilenamePat[I] == 't') {
74062c37277SVedant Kumar         lprofCurFilename.TmpDir = getenv("TMPDIR");
74162c37277SVedant Kumar         if (!lprofCurFilename.TmpDir) {
74262c37277SVedant Kumar           PROF_WARN("Unable to get the TMPDIR environment variable, referenced "
74362c37277SVedant Kumar                     "in %s. Using the default path.",
74462c37277SVedant Kumar                     FilenamePat);
74562c37277SVedant Kumar           return -1;
74662c37277SVedant Kumar         }
747d889d1efSVedant Kumar       } else if (FilenamePat[I] == 'c') {
748d889d1efSVedant Kumar         if (__llvm_profile_is_continuous_mode_enabled()) {
749d889d1efSVedant Kumar           PROF_WARN("%%c specifier can only be specified once in %s.\n",
750d889d1efSVedant Kumar                     FilenamePat);
751d889d1efSVedant Kumar           return -1;
752d889d1efSVedant Kumar         }
75354902e00SPetr Hosek #if defined(__APPLE__) || defined(__ELF__) || defined(_WIN32)
754896f797bSVedant Kumar         __llvm_profile_set_page_size(getpagesize());
755d889d1efSVedant Kumar         __llvm_profile_enable_continuous_mode();
75654902e00SPetr Hosek #else
75754902e00SPetr Hosek         PROF_WARN("%s", "Continous mode is currently only supported for Mach-O,"
75854902e00SPetr Hosek                         " ELF and COFF formats.");
75954902e00SPetr Hosek         return -1;
76054902e00SPetr Hosek #endif
761c5b94ea2SFangrui Song       } else {
762c5b94ea2SFangrui Song         unsigned MergePoolSize = getMergePoolSize(FilenamePat, &I);
763c5b94ea2SFangrui Song         if (!MergePoolSize)
764c5b94ea2SFangrui Song           continue;
765e2ce2e00SXinliang David Li         if (MergingEnabled) {
7668e2dd518SVedant Kumar           PROF_WARN("%%m specifier can only be specified once in %s.\n",
767e2ce2e00SXinliang David Li                     FilenamePat);
768e2ce2e00SXinliang David Li           return -1;
769e2ce2e00SXinliang David Li         }
770e2ce2e00SXinliang David Li         MergingEnabled = 1;
771c5b94ea2SFangrui Song         lprofCurFilename.MergePoolSize = MergePoolSize;
772a06e8ca6SVedant Kumar       }
773a06e8ca6SVedant Kumar     }
774a7d48261SVedant Kumar   }
775a06e8ca6SVedant Kumar 
7767f08d12bSXinliang David Li   lprofCurFilename.NumPids = NumPids;
7777f08d12bSXinliang David Li   lprofCurFilename.NumHosts = NumHosts;
77855e4d66fSDuncan P. N. Exon Smith   return 0;
77955e4d66fSDuncan P. N. Exon Smith }
78055e4d66fSDuncan P. N. Exon Smith 
parseAndSetFilename(const char * FilenamePat,ProfileNameSpecifier PNS,unsigned CopyFilenamePat)781153e8b6cSXinliang David Li static void parseAndSetFilename(const char *FilenamePat,
78214c91c4eSXinliang David Li                                 ProfileNameSpecifier PNS,
78314c91c4eSXinliang David Li                                 unsigned CopyFilenamePat) {
7847f08d12bSXinliang David Li 
785153e8b6cSXinliang David Li   const char *OldFilenamePat = lprofCurFilename.FilenamePat;
786153e8b6cSXinliang David Li   ProfileNameSpecifier OldPNS = lprofCurFilename.PNS;
787153e8b6cSXinliang David Li 
788d889d1efSVedant Kumar   /* The old profile name specifier takes precedence over the old one. */
789153e8b6cSXinliang David Li   if (PNS < OldPNS)
790153e8b6cSXinliang David Li     return;
791153e8b6cSXinliang David Li 
792153e8b6cSXinliang David Li   if (!FilenamePat)
793153e8b6cSXinliang David Li     FilenamePat = DefaultProfileName;
794153e8b6cSXinliang David Li 
795153e8b6cSXinliang David Li   if (OldFilenamePat && !strcmp(OldFilenamePat, FilenamePat)) {
796153e8b6cSXinliang David Li     lprofCurFilename.PNS = PNS;
797153e8b6cSXinliang David Li     return;
798153e8b6cSXinliang David Li   }
799153e8b6cSXinliang David Li 
800153e8b6cSXinliang David Li   /* When PNS >= OldPNS, the last one wins. */
80114c91c4eSXinliang David Li   if (!FilenamePat || parseFilenamePattern(FilenamePat, CopyFilenamePat))
8027f08d12bSXinliang David Li     resetFilenameToDefault();
803153e8b6cSXinliang David Li   lprofCurFilename.PNS = PNS;
8047f08d12bSXinliang David Li 
805153e8b6cSXinliang David Li   if (!OldFilenamePat) {
806e68df598SXinliang David Li     if (getenv("LLVM_PROFILE_VERBOSE"))
807153e8b6cSXinliang David Li       PROF_NOTE("Set profile file path to \"%s\" via %s.\n",
808153e8b6cSXinliang David Li                 lprofCurFilename.FilenamePat, getPNSStr(PNS));
809153e8b6cSXinliang David Li   } else {
810e68df598SXinliang David Li     if (getenv("LLVM_PROFILE_VERBOSE"))
811153e8b6cSXinliang David Li       PROF_NOTE("Override old profile path \"%s\" via %s to \"%s\" via %s.\n",
812153e8b6cSXinliang David Li                 OldFilenamePat, getPNSStr(OldPNS), lprofCurFilename.FilenamePat,
813153e8b6cSXinliang David Li                 getPNSStr(PNS));
814153e8b6cSXinliang David Li   }
8157f08d12bSXinliang David Li 
8167f08d12bSXinliang David Li   truncateCurrentFile();
81754902e00SPetr Hosek   if (__llvm_profile_is_continuous_mode_enabled())
818d889d1efSVedant Kumar     initializeProfileForContinuousMode();
8197f08d12bSXinliang David Li }
8207f08d12bSXinliang David Li 
821315e49d2SXinliang David Li /* Return buffer length that is required to store the current profile
822315e49d2SXinliang David Li  * filename with PID and hostname substitutions. */
823c5b94ea2SFangrui Song /* The length to hold uint64_t followed by 3 digits pool id including '_' */
824e2ce2e00SXinliang David Li #define SIGLEN 24
getCurFilenameLength(void)825*bdbfaf0cSAaron Ballman static int getCurFilenameLength(void) {
826e2ce2e00SXinliang David Li   int Len;
827315e49d2SXinliang David Li   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
828315e49d2SXinliang David Li     return 0;
829be0a5e17SDuncan P. N. Exon Smith 
830e2ce2e00SXinliang David Li   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
83162c37277SVedant Kumar         lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize))
832315e49d2SXinliang David Li     return strlen(lprofCurFilename.FilenamePat);
833315e49d2SXinliang David Li 
834e2ce2e00SXinliang David Li   Len = strlen(lprofCurFilename.FilenamePat) +
835315e49d2SXinliang David Li         lprofCurFilename.NumPids * (strlen(lprofCurFilename.PidChars) - 2) +
83662c37277SVedant Kumar         lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2) +
83762c37277SVedant Kumar         (lprofCurFilename.TmpDir ? (strlen(lprofCurFilename.TmpDir) - 1) : 0);
838e2ce2e00SXinliang David Li   if (lprofCurFilename.MergePoolSize)
839e2ce2e00SXinliang David Li     Len += SIGLEN;
840e2ce2e00SXinliang David Li   return Len;
841be0a5e17SDuncan P. N. Exon Smith }
842315e49d2SXinliang David Li 
843315e49d2SXinliang David Li /* Return the pointer to the current profile file name (after substituting
844315e49d2SXinliang David Li  * PIDs and Hostnames in filename pattern. \p FilenameBuf is the buffer
845315e49d2SXinliang David Li  * to store the resulting filename. If no substitution is needed, the
84673053b22STeresa Johnson  * current filename pattern string is directly returned, unless ForceUseBuf
84773053b22STeresa Johnson  * is enabled. */
getCurFilename(char * FilenameBuf,int ForceUseBuf)84873053b22STeresa Johnson static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
84962c37277SVedant Kumar   int I, J, PidLength, HostNameLength, TmpDirLength, FilenamePatLength;
850315e49d2SXinliang David Li   const char *FilenamePat = lprofCurFilename.FilenamePat;
851315e49d2SXinliang David Li 
852315e49d2SXinliang David Li   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
853315e49d2SXinliang David Li     return 0;
854315e49d2SXinliang David Li 
855e2ce2e00SXinliang David Li   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
85662c37277SVedant Kumar         lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize ||
857d889d1efSVedant Kumar         __llvm_profile_is_continuous_mode_enabled())) {
85873053b22STeresa Johnson     if (!ForceUseBuf)
859315e49d2SXinliang David Li       return lprofCurFilename.FilenamePat;
860315e49d2SXinliang David Li 
86173053b22STeresa Johnson     FilenamePatLength = strlen(lprofCurFilename.FilenamePat);
86273053b22STeresa Johnson     memcpy(FilenameBuf, lprofCurFilename.FilenamePat, FilenamePatLength);
86373053b22STeresa Johnson     FilenameBuf[FilenamePatLength] = '\0';
86473053b22STeresa Johnson     return FilenameBuf;
86573053b22STeresa Johnson   }
86673053b22STeresa Johnson 
867315e49d2SXinliang David Li   PidLength = strlen(lprofCurFilename.PidChars);
868315e49d2SXinliang David Li   HostNameLength = strlen(lprofCurFilename.Hostname);
86962c37277SVedant Kumar   TmpDirLength = lprofCurFilename.TmpDir ? strlen(lprofCurFilename.TmpDir) : 0;
870315e49d2SXinliang David Li   /* Construct the new filename. */
871315e49d2SXinliang David Li   for (I = 0, J = 0; FilenamePat[I]; ++I)
872315e49d2SXinliang David Li     if (FilenamePat[I] == '%') {
873315e49d2SXinliang David Li       if (FilenamePat[++I] == 'p') {
874315e49d2SXinliang David Li         memcpy(FilenameBuf + J, lprofCurFilename.PidChars, PidLength);
875315e49d2SXinliang David Li         J += PidLength;
876315e49d2SXinliang David Li       } else if (FilenamePat[I] == 'h') {
877315e49d2SXinliang David Li         memcpy(FilenameBuf + J, lprofCurFilename.Hostname, HostNameLength);
878a06e8ca6SVedant Kumar         J += HostNameLength;
87962c37277SVedant Kumar       } else if (FilenamePat[I] == 't') {
88062c37277SVedant Kumar         memcpy(FilenameBuf + J, lprofCurFilename.TmpDir, TmpDirLength);
88162c37277SVedant Kumar         FilenameBuf[J + TmpDirLength] = DIR_SEPARATOR;
88262c37277SVedant Kumar         J += TmpDirLength + 1;
883c5b94ea2SFangrui Song       } else {
884c5b94ea2SFangrui Song         if (!getMergePoolSize(FilenamePat, &I))
885c5b94ea2SFangrui Song           continue;
886c5b94ea2SFangrui Song         char LoadModuleSignature[SIGLEN + 1];
887e2ce2e00SXinliang David Li         int S;
888e2ce2e00SXinliang David Li         int ProfilePoolId = getpid() % lprofCurFilename.MergePoolSize;
889c5b94ea2SFangrui Song         S = snprintf(LoadModuleSignature, SIGLEN + 1, "%" PRIu64 "_%d",
890e2ce2e00SXinliang David Li                      lprofGetLoadModuleSignature(), ProfilePoolId);
891e2ce2e00SXinliang David Li         if (S == -1 || S > SIGLEN)
892e2ce2e00SXinliang David Li           S = SIGLEN;
893e2ce2e00SXinliang David Li         memcpy(FilenameBuf + J, LoadModuleSignature, S);
894e2ce2e00SXinliang David Li         J += S;
895a06e8ca6SVedant Kumar       }
896be0a5e17SDuncan P. N. Exon Smith       /* Drop any unknown substitutions. */
897be0a5e17SDuncan P. N. Exon Smith     } else
898315e49d2SXinliang David Li       FilenameBuf[J++] = FilenamePat[I];
899315e49d2SXinliang David Li   FilenameBuf[J] = 0;
900be0a5e17SDuncan P. N. Exon Smith 
901315e49d2SXinliang David Li   return FilenameBuf;
902be0a5e17SDuncan P. N. Exon Smith }
903be0a5e17SDuncan P. N. Exon Smith 
904315e49d2SXinliang David Li /* Returns the pointer to the environment variable
905315e49d2SXinliang David Li  * string. Returns null if the env var is not set. */
getFilenamePatFromEnv(void)906315e49d2SXinliang David Li static const char *getFilenamePatFromEnv(void) {
907d641b53fSEric Christopher   const char *Filename = getenv("LLVM_PROFILE_FILE");
908d641b53fSEric Christopher   if (!Filename || !Filename[0])
90951fe002eSXinliang David Li     return 0;
91051fe002eSXinliang David Li   return Filename;
911d641b53fSEric Christopher }
912d641b53fSEric Christopher 
913eaf238d4SXinliang David Li COMPILER_RT_VISIBILITY
__llvm_profile_get_path_prefix(void)914eaf238d4SXinliang David Li const char *__llvm_profile_get_path_prefix(void) {
915eaf238d4SXinliang David Li   int Length;
916eaf238d4SXinliang David Li   char *FilenameBuf, *Prefix;
917eaf238d4SXinliang David Li   const char *Filename, *PrefixEnd;
918eaf238d4SXinliang David Li 
919eaf238d4SXinliang David Li   if (lprofCurFilename.ProfilePathPrefix)
920eaf238d4SXinliang David Li     return lprofCurFilename.ProfilePathPrefix;
921eaf238d4SXinliang David Li 
922eaf238d4SXinliang David Li   Length = getCurFilenameLength();
923eaf238d4SXinliang David Li   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
92473053b22STeresa Johnson   Filename = getCurFilename(FilenameBuf, 0);
925eaf238d4SXinliang David Li   if (!Filename)
926eaf238d4SXinliang David Li     return "\0";
927eaf238d4SXinliang David Li 
928eaf238d4SXinliang David Li   PrefixEnd = lprofFindLastDirSeparator(Filename);
929eaf238d4SXinliang David Li   if (!PrefixEnd)
930eaf238d4SXinliang David Li     return "\0";
931eaf238d4SXinliang David Li 
932eaf238d4SXinliang David Li   Length = PrefixEnd - Filename + 1;
933eaf238d4SXinliang David Li   Prefix = (char *)malloc(Length + 1);
934eaf238d4SXinliang David Li   if (!Prefix) {
935eaf238d4SXinliang David Li     PROF_ERR("Failed to %s\n", "allocate memory.");
936eaf238d4SXinliang David Li     return "\0";
937eaf238d4SXinliang David Li   }
938eaf238d4SXinliang David Li   memcpy(Prefix, Filename, Length);
939eaf238d4SXinliang David Li   Prefix[Length] = '\0';
940eaf238d4SXinliang David Li   lprofCurFilename.ProfilePathPrefix = Prefix;
941eaf238d4SXinliang David Li   return Prefix;
942eaf238d4SXinliang David Li }
943eaf238d4SXinliang David Li 
94473053b22STeresa Johnson COMPILER_RT_VISIBILITY
__llvm_profile_get_filename(void)94573053b22STeresa Johnson const char *__llvm_profile_get_filename(void) {
94673053b22STeresa Johnson   int Length;
94773053b22STeresa Johnson   char *FilenameBuf;
94873053b22STeresa Johnson   const char *Filename;
94973053b22STeresa Johnson 
95073053b22STeresa Johnson   Length = getCurFilenameLength();
95173053b22STeresa Johnson   FilenameBuf = (char *)malloc(Length + 1);
95273053b22STeresa Johnson   if (!FilenameBuf) {
95373053b22STeresa Johnson     PROF_ERR("Failed to %s\n", "allocate memory.");
95473053b22STeresa Johnson     return "\0";
95573053b22STeresa Johnson   }
95673053b22STeresa Johnson   Filename = getCurFilename(FilenameBuf, 1);
95773053b22STeresa Johnson   if (!Filename)
95873053b22STeresa Johnson     return "\0";
95973053b22STeresa Johnson 
96073053b22STeresa Johnson   return FilenameBuf;
96173053b22STeresa Johnson }
96273053b22STeresa Johnson 
96332bddad3SPetr Hosek /* This API initializes the file handling, both user specified
96451fe002eSXinliang David Li  * profile path via -fprofile-instr-generate= and LLVM_PROFILE_FILE
96532bddad3SPetr Hosek  * environment variable can override this default value.
96632bddad3SPetr Hosek  */
967abfd553cSXinliang David Li COMPILER_RT_VISIBILITY
__llvm_profile_initialize_file(void)96855e4d66fSDuncan P. N. Exon Smith void __llvm_profile_initialize_file(void) {
969e953933aSXinliang David Li   const char *EnvFilenamePat;
9701c9320cdSXinliang David Li   const char *SelectedPat = NULL;
9711c9320cdSXinliang David Li   ProfileNameSpecifier PNS = PNS_unknown;
972e953933aSXinliang David Li   int hasCommandLineOverrider = (INSTR_PROF_PROFILE_NAME_VAR[0] != 0);
97355e4d66fSDuncan P. N. Exon Smith 
974e953933aSXinliang David Li   EnvFilenamePat = getFilenamePatFromEnv();
9751c9320cdSXinliang David Li   if (EnvFilenamePat) {
976c7c5303fSXinliang David Li     /* Pass CopyFilenamePat = 1, to ensure that the filename would be valid
977c7c5303fSXinliang David Li        at the  moment when __llvm_profile_write_file() gets executed. */
978c7c5303fSXinliang David Li     parseAndSetFilename(EnvFilenamePat, PNS_environment, 1);
979c7c5303fSXinliang David Li     return;
9801c9320cdSXinliang David Li   } else if (hasCommandLineOverrider) {
9811c9320cdSXinliang David Li     SelectedPat = INSTR_PROF_PROFILE_NAME_VAR;
9821c9320cdSXinliang David Li     PNS = PNS_command_line;
983533d4c90SXinliang David Li   } else {
9841c9320cdSXinliang David Li     SelectedPat = NULL;
9851c9320cdSXinliang David Li     PNS = PNS_default;
986533d4c90SXinliang David Li   }
987533d4c90SXinliang David Li 
9881c9320cdSXinliang David Li   parseAndSetFilename(SelectedPat, PNS, 0);
98955e4d66fSDuncan P. N. Exon Smith }
99055e4d66fSDuncan P. N. Exon Smith 
99132bddad3SPetr Hosek /* This method is invoked by the runtime initialization hook
99232bddad3SPetr Hosek  * InstrProfilingRuntime.o if it is linked in.
99332bddad3SPetr Hosek  */
99432bddad3SPetr Hosek COMPILER_RT_VISIBILITY
__llvm_profile_initialize(void)99532bddad3SPetr Hosek void __llvm_profile_initialize(void) {
99632bddad3SPetr Hosek   __llvm_profile_initialize_file();
99732bddad3SPetr Hosek   if (!__llvm_profile_is_continuous_mode_enabled())
99832bddad3SPetr Hosek     __llvm_profile_register_write_file_atexit();
99932bddad3SPetr Hosek }
100032bddad3SPetr Hosek 
100151fe002eSXinliang David Li /* This API is directly called by the user application code. It has the
100251fe002eSXinliang David Li  * highest precedence compared with LLVM_PROFILE_FILE environment variable
100341518945SXinliang David Li  * and command line option -fprofile-instr-generate=<profile_name>.
100451fe002eSXinliang David Li  */
1005abfd553cSXinliang David Li COMPILER_RT_VISIBILITY
__llvm_profile_set_filename(const char * FilenamePat)1006315e49d2SXinliang David Li void __llvm_profile_set_filename(const char *FilenamePat) {
1007d889d1efSVedant Kumar   if (__llvm_profile_is_continuous_mode_enabled())
1008d889d1efSVedant Kumar     return;
100914c91c4eSXinliang David Li   parseAndSetFilename(FilenamePat, PNS_runtime_api, 1);
1010d641b53fSEric Christopher }
1011d641b53fSEric Christopher 
1012315e49d2SXinliang David Li /* The public API for writing profile data into the file with name
1013315e49d2SXinliang David Li  * set by previous calls to __llvm_profile_set_filename or
1014315e49d2SXinliang David Li  * __llvm_profile_override_default_filename or
1015315e49d2SXinliang David Li  * __llvm_profile_initialize_file. */
1016abfd553cSXinliang David Li COMPILER_RT_VISIBILITY
__llvm_profile_write_file(void)101755e4d66fSDuncan P. N. Exon Smith int __llvm_profile_write_file(void) {
1018315e49d2SXinliang David Li   int rc, Length;
1019315e49d2SXinliang David Li   const char *Filename;
1020315e49d2SXinliang David Li   char *FilenameBuf;
1021cf1f6fb1SRong Xu   int PDeathSig = 0;
1022c9c7a3e4SVasileios Kalintiris 
1023d889d1efSVedant Kumar   if (lprofProfileDumped() || __llvm_profile_is_continuous_mode_enabled()) {
10246694b2b3SSajjad Mirza     PROF_NOTE("Profile data not written to file: %s.\n", "already written");
10253b2c002cSXinliang David Li     return 0;
10263b2c002cSXinliang David Li   }
10273b2c002cSXinliang David Li 
1028315e49d2SXinliang David Li   Length = getCurFilenameLength();
1029315e49d2SXinliang David Li   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
103073053b22STeresa Johnson   Filename = getCurFilename(FilenameBuf, 0);
1031315e49d2SXinliang David Li 
103255e4d66fSDuncan P. N. Exon Smith   /* Check the filename. */
1033315e49d2SXinliang David Li   if (!Filename) {
1034690c31f1SXinliang David Li     PROF_ERR("Failed to write file : %s\n", "Filename not set");
103555e4d66fSDuncan P. N. Exon Smith     return -1;
10369ea3064bSXinliang David Li   }
103755e4d66fSDuncan P. N. Exon Smith 
1038d85c32cdSXinliang David Li   /* Check if there is llvm/runtime version mismatch.  */
1039a692421aSXinliang David Li   if (GET_VERSION(__llvm_profile_get_version()) != INSTR_PROF_RAW_VERSION) {
1040690c31f1SXinliang David Li     PROF_ERR("Runtime and instrumentation version mismatch : "
1041a692421aSXinliang David Li              "expected %d, but get %d\n",
1042a692421aSXinliang David Li              INSTR_PROF_RAW_VERSION,
1043a692421aSXinliang David Li              (int)GET_VERSION(__llvm_profile_get_version()));
1044a692421aSXinliang David Li     return -1;
1045a692421aSXinliang David Li   }
1046a692421aSXinliang David Li 
1047cf1f6fb1SRong Xu   // Temporarily suspend getting SIGKILL when the parent exits.
1048cf1f6fb1SRong Xu   PDeathSig = lprofSuspendSigKill();
1049cf1f6fb1SRong Xu 
1050315e49d2SXinliang David Li   /* Write profile data to the file. */
1051315e49d2SXinliang David Li   rc = writeFile(Filename);
10529ea3064bSXinliang David Li   if (rc)
1053315e49d2SXinliang David Li     PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));
1054cf1f6fb1SRong Xu 
1055cf1f6fb1SRong Xu   // Restore SIGKILL.
1056cf1f6fb1SRong Xu   if (PDeathSig == 1)
1057cf1f6fb1SRong Xu     lprofRestoreSigKill();
1058cf1f6fb1SRong Xu 
105966fd5c91SJustin Bogner   return rc;
1060be0a5e17SDuncan P. N. Exon Smith }
1061be0a5e17SDuncan P. N. Exon Smith 
10623b2c002cSXinliang David Li COMPILER_RT_VISIBILITY
__llvm_profile_dump(void)10633b2c002cSXinliang David Li int __llvm_profile_dump(void) {
10643b2c002cSXinliang David Li   if (!doMerging())
10653b2c002cSXinliang David Li     PROF_WARN("Later invocation of __llvm_profile_dump can lead to clobbering "
106681291a0fSNico Weber               " of previously dumped profile data : %s. Either use %%m "
10673b2c002cSXinliang David Li               "in profile name or change profile name before dumping.\n",
10683b2c002cSXinliang David Li               "online profile merging is not on");
10693b2c002cSXinliang David Li   int rc = __llvm_profile_write_file();
1070ba1f4405SPetr Hosek   lprofSetProfileDumped(1);
10713b2c002cSXinliang David Li   return rc;
10723b2c002cSXinliang David Li }
10733b2c002cSXinliang David Li 
1074e73ae9a1SManman Ren /* Order file data will be saved in a file with suffx .order. */
1075e73ae9a1SManman Ren static const char *OrderFileSuffix = ".order";
1076e73ae9a1SManman Ren 
1077e73ae9a1SManman Ren COMPILER_RT_VISIBILITY
__llvm_orderfile_write_file(void)1078e73ae9a1SManman Ren int __llvm_orderfile_write_file(void) {
1079e73ae9a1SManman Ren   int rc, Length, LengthBeforeAppend, SuffixLength;
1080e73ae9a1SManman Ren   const char *Filename;
1081e73ae9a1SManman Ren   char *FilenameBuf;
1082e73ae9a1SManman Ren   int PDeathSig = 0;
1083e73ae9a1SManman Ren 
1084e73ae9a1SManman Ren   SuffixLength = strlen(OrderFileSuffix);
1085e73ae9a1SManman Ren   Length = getCurFilenameLength() + SuffixLength;
1086e73ae9a1SManman Ren   FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);
1087e73ae9a1SManman Ren   Filename = getCurFilename(FilenameBuf, 1);
1088e73ae9a1SManman Ren 
1089e73ae9a1SManman Ren   /* Check the filename. */
1090e73ae9a1SManman Ren   if (!Filename) {
1091e73ae9a1SManman Ren     PROF_ERR("Failed to write file : %s\n", "Filename not set");
1092e73ae9a1SManman Ren     return -1;
1093e73ae9a1SManman Ren   }
1094e73ae9a1SManman Ren 
1095e73ae9a1SManman Ren   /* Append order file suffix */
1096e73ae9a1SManman Ren   LengthBeforeAppend = strlen(Filename);
1097e73ae9a1SManman Ren   memcpy(FilenameBuf + LengthBeforeAppend, OrderFileSuffix, SuffixLength);
1098e73ae9a1SManman Ren   FilenameBuf[LengthBeforeAppend + SuffixLength] = '\0';
1099e73ae9a1SManman Ren 
1100e73ae9a1SManman Ren   /* Check if there is llvm/runtime version mismatch.  */
1101e73ae9a1SManman Ren   if (GET_VERSION(__llvm_profile_get_version()) != INSTR_PROF_RAW_VERSION) {
1102e73ae9a1SManman Ren     PROF_ERR("Runtime and instrumentation version mismatch : "
1103e73ae9a1SManman Ren              "expected %d, but get %d\n",
1104e73ae9a1SManman Ren              INSTR_PROF_RAW_VERSION,
1105e73ae9a1SManman Ren              (int)GET_VERSION(__llvm_profile_get_version()));
1106e73ae9a1SManman Ren     return -1;
1107e73ae9a1SManman Ren   }
1108e73ae9a1SManman Ren 
1109e73ae9a1SManman Ren   // Temporarily suspend getting SIGKILL when the parent exits.
1110e73ae9a1SManman Ren   PDeathSig = lprofSuspendSigKill();
1111e73ae9a1SManman Ren 
1112e73ae9a1SManman Ren   /* Write order data to the file. */
1113e73ae9a1SManman Ren   rc = writeOrderFile(Filename);
1114e73ae9a1SManman Ren   if (rc)
1115e73ae9a1SManman Ren     PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));
1116e73ae9a1SManman Ren 
1117e73ae9a1SManman Ren   // Restore SIGKILL.
1118e73ae9a1SManman Ren   if (PDeathSig == 1)
1119e73ae9a1SManman Ren     lprofRestoreSigKill();
1120e73ae9a1SManman Ren 
1121e73ae9a1SManman Ren   return rc;
1122e73ae9a1SManman Ren }
1123e73ae9a1SManman Ren 
1124e73ae9a1SManman Ren COMPILER_RT_VISIBILITY
__llvm_orderfile_dump(void)1125e73ae9a1SManman Ren int __llvm_orderfile_dump(void) {
1126e73ae9a1SManman Ren   int rc = __llvm_orderfile_write_file();
1127e73ae9a1SManman Ren   return rc;
1128e73ae9a1SManman Ren }
1129e73ae9a1SManman Ren 
writeFileWithoutReturn(void)11306fe18f4fSXinliang David Li static void writeFileWithoutReturn(void) { __llvm_profile_write_file(); }
1131be0a5e17SDuncan P. N. Exon Smith 
1132abfd553cSXinliang David Li COMPILER_RT_VISIBILITY
__llvm_profile_register_write_file_atexit(void)113355e4d66fSDuncan P. N. Exon Smith int __llvm_profile_register_write_file_atexit(void) {
1134be0a5e17SDuncan P. N. Exon Smith   static int HasBeenRegistered = 0;
1135be0a5e17SDuncan P. N. Exon Smith 
1136be0a5e17SDuncan P. N. Exon Smith   if (HasBeenRegistered)
1137be0a5e17SDuncan P. N. Exon Smith     return 0;
1138be0a5e17SDuncan P. N. Exon Smith 
11394617aa78SXinliang David Li   lprofSetupValueProfiler();
11404617aa78SXinliang David Li 
1141be0a5e17SDuncan P. N. Exon Smith   HasBeenRegistered = 1;
1142be0a5e17SDuncan P. N. Exon Smith   return atexit(writeFileWithoutReturn);
1143be0a5e17SDuncan P. N. Exon Smith }
114447e5fcbaSPetr Hosek 
__llvm_profile_set_file_object(FILE * File,int EnableMerge)11451b052451SZequan Wu COMPILER_RT_VISIBILITY int __llvm_profile_set_file_object(FILE *File,
11461b052451SZequan Wu                                                           int EnableMerge) {
11471b052451SZequan Wu   if (__llvm_profile_is_continuous_mode_enabled()) {
11481b052451SZequan Wu     if (!EnableMerge) {
11491b052451SZequan Wu       PROF_WARN("__llvm_profile_set_file_object(fd=%d) not supported in "
11501b052451SZequan Wu                 "continuous sync mode when merging is disabled\n",
11511b052451SZequan Wu                 fileno(File));
11521b052451SZequan Wu       return 1;
11531b052451SZequan Wu     }
1154ab694cd8SZequan Wu     if (lprofLockFileHandle(File) != 0) {
1155ab694cd8SZequan Wu       PROF_WARN("Data may be corrupted during profile merging : %s\n",
1156ab694cd8SZequan Wu                 "Fail to obtain file lock due to system limit.");
1157ab694cd8SZequan Wu     }
11581b052451SZequan Wu     uint64_t ProfileFileSize = 0;
11591b052451SZequan Wu     if (getProfileFileSizeForMerging(File, &ProfileFileSize) == -1) {
11601b052451SZequan Wu       lprofUnlockFileHandle(File);
11611b052451SZequan Wu       return 1;
11621b052451SZequan Wu     }
11631b052451SZequan Wu     if (ProfileFileSize == 0) {
11641b052451SZequan Wu       FreeHook = &free;
11651b052451SZequan Wu       setupIOBuffer();
11661b052451SZequan Wu       ProfDataWriter fileWriter;
11671b052451SZequan Wu       initFileWriter(&fileWriter, File);
11681b052451SZequan Wu       if (lprofWriteData(&fileWriter, 0, 0)) {
11691b052451SZequan Wu         lprofUnlockFileHandle(File);
11701b052451SZequan Wu         PROF_ERR("Failed to write file \"%d\": %s\n", fileno(File),
11711b052451SZequan Wu                  strerror(errno));
11721b052451SZequan Wu         return 1;
11731b052451SZequan Wu       }
11744e8efff5SZequan Wu       fflush(File);
11751b052451SZequan Wu     } else {
11761b052451SZequan Wu       /* The merged profile has a non-zero length. Check that it is compatible
11771b052451SZequan Wu        * with the data in this process. */
11781b052451SZequan Wu       char *ProfileBuffer;
11791b052451SZequan Wu       if (mmapProfileForMerging(File, ProfileFileSize, &ProfileBuffer) == -1) {
11801b052451SZequan Wu         lprofUnlockFileHandle(File);
11811b052451SZequan Wu         return 1;
11821b052451SZequan Wu       }
11831b052451SZequan Wu       (void)munmap(ProfileBuffer, ProfileFileSize);
11841b052451SZequan Wu     }
11851b052451SZequan Wu     mmapForContinuousMode(0, File);
11861b052451SZequan Wu     lprofUnlockFileHandle(File);
11871b052451SZequan Wu   } else {
11881b052451SZequan Wu     setProfileFile(File);
11891b052451SZequan Wu     setProfileMergeRequested(EnableMerge);
11901b052451SZequan Wu   }
11911b052451SZequan Wu   return 0;
11921b052451SZequan Wu }
11931b052451SZequan Wu 
119447e5fcbaSPetr Hosek #endif
1195