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