Path: blob/main/contrib/llvm-project/compiler-rt/lib/profile/InstrProfilingFile.c
35233 views
/*===- InstrProfilingFile.c - Write instrumentation to a file -------------===*\1|*2|* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3|* See https://llvm.org/LICENSE.txt for license information.4|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5|*6\*===----------------------------------------------------------------------===*/78#if !defined(__Fuchsia__)910#include <assert.h>11#include <errno.h>12#include <stdio.h>13#include <stdlib.h>14#include <string.h>15#ifdef _MSC_VER16/* For _alloca. */17#include <malloc.h>18#endif19#if defined(_WIN32)20#include "WindowsMMap.h"21/* For _chsize_s */22#include <io.h>23#include <process.h>24#else25#include <sys/file.h>26#include <sys/mman.h>27#include <unistd.h>28#if defined(__linux__)29#include <sys/types.h>30#endif31#endif3233#include "InstrProfiling.h"34#include "InstrProfilingInternal.h"35#include "InstrProfilingPort.h"36#include "InstrProfilingUtil.h"3738/* From where is profile name specified.39* The order the enumerators define their40* precedence. Re-order them may lead to41* runtime behavior change. */42typedef enum ProfileNameSpecifier {43PNS_unknown = 0,44PNS_default,45PNS_command_line,46PNS_environment,47PNS_runtime_api48} ProfileNameSpecifier;4950static const char *getPNSStr(ProfileNameSpecifier PNS) {51switch (PNS) {52case PNS_default:53return "default setting";54case PNS_command_line:55return "command line";56case PNS_environment:57return "environment variable";58case PNS_runtime_api:59return "runtime API";60default:61return "Unknown";62}63}6465#define MAX_PID_SIZE 1666/* Data structure holding the result of parsed filename pattern. */67typedef struct lprofFilename {68/* File name string possibly with %p or %h specifiers. */69const char *FilenamePat;70/* A flag indicating if FilenamePat's memory is allocated71* by runtime. */72unsigned OwnsFilenamePat;73const char *ProfilePathPrefix;74char PidChars[MAX_PID_SIZE];75char *TmpDir;76char Hostname[COMPILER_RT_MAX_HOSTLEN];77unsigned NumPids;78unsigned NumHosts;79/* When in-process merging is enabled, this parameter specifies80* the total number of profile data files shared by all the processes81* spawned from the same binary. By default the value is 1. If merging82* is not enabled, its value should be 0. This parameter is specified83* by the %[0-9]m specifier. For instance %2m enables merging using84* 2 profile data files. %1m is equivalent to %m. Also %m specifier85* can only appear once at the end of the name pattern. */86unsigned MergePoolSize;87ProfileNameSpecifier PNS;88} lprofFilename;8990static lprofFilename lprofCurFilename = {0, 0, 0, {0}, NULL,91{0}, 0, 0, 0, PNS_unknown};9293static int ProfileMergeRequested = 0;94static int getProfileFileSizeForMerging(FILE *ProfileFile,95uint64_t *ProfileFileSize);9697#if defined(__APPLE__)98static const int ContinuousModeSupported = 1;99static const int UseBiasVar = 0;100static const char *FileOpenMode = "a+b";101static void *BiasAddr = NULL;102static void *BiasDefaultAddr = NULL;103static int mmapForContinuousMode(uint64_t CurrentFileOffset, FILE *File) {104/* Get the sizes of various profile data sections. Taken from105* __llvm_profile_get_size_for_buffer(). */106const __llvm_profile_data *DataBegin = __llvm_profile_begin_data();107const __llvm_profile_data *DataEnd = __llvm_profile_end_data();108const char *CountersBegin = __llvm_profile_begin_counters();109const char *CountersEnd = __llvm_profile_end_counters();110const char *BitmapBegin = __llvm_profile_begin_bitmap();111const char *BitmapEnd = __llvm_profile_end_bitmap();112const char *NamesBegin = __llvm_profile_begin_names();113const char *NamesEnd = __llvm_profile_end_names();114const uint64_t NamesSize = (NamesEnd - NamesBegin) * sizeof(char);115uint64_t DataSize = __llvm_profile_get_data_size(DataBegin, DataEnd);116uint64_t CountersSize =117__llvm_profile_get_counters_size(CountersBegin, CountersEnd);118uint64_t NumBitmapBytes =119__llvm_profile_get_num_bitmap_bytes(BitmapBegin, BitmapEnd);120121/* Check that the counter, bitmap, and data sections in this image are122* page-aligned. */123unsigned PageSize = getpagesize();124if ((intptr_t)CountersBegin % PageSize != 0) {125PROF_ERR("Counters section not page-aligned (start = %p, pagesz = %u).\n",126CountersBegin, PageSize);127return 1;128}129if ((intptr_t)BitmapBegin % PageSize != 0) {130PROF_ERR("Bitmap section not page-aligned (start = %p, pagesz = %u).\n",131BitmapBegin, PageSize);132return 1;133}134if ((intptr_t)DataBegin % PageSize != 0) {135PROF_ERR("Data section not page-aligned (start = %p, pagesz = %u).\n",136DataBegin, PageSize);137return 1;138}139140int Fileno = fileno(File);141/* Determine how much padding is needed before/after the counters and142* after the names. */143uint64_t PaddingBytesBeforeCounters, PaddingBytesAfterCounters,144PaddingBytesAfterNames, PaddingBytesAfterBitmapBytes,145PaddingBytesAfterVTable, PaddingBytesAfterVNames;146__llvm_profile_get_padding_sizes_for_counters(147DataSize, CountersSize, NumBitmapBytes, NamesSize, /*VTableSize=*/0,148/*VNameSize=*/0, &PaddingBytesBeforeCounters, &PaddingBytesAfterCounters,149&PaddingBytesAfterBitmapBytes, &PaddingBytesAfterNames,150&PaddingBytesAfterVTable, &PaddingBytesAfterVNames);151152uint64_t PageAlignedCountersLength = CountersSize + PaddingBytesAfterCounters;153uint64_t FileOffsetToCounters = CurrentFileOffset +154sizeof(__llvm_profile_header) + DataSize +155PaddingBytesBeforeCounters;156void *CounterMmap = mmap((void *)CountersBegin, PageAlignedCountersLength,157PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED,158Fileno, FileOffsetToCounters);159if (CounterMmap != CountersBegin) {160PROF_ERR(161"Continuous counter sync mode is enabled, but mmap() failed (%s).\n"162" - CountersBegin: %p\n"163" - PageAlignedCountersLength: %" PRIu64 "\n"164" - Fileno: %d\n"165" - FileOffsetToCounters: %" PRIu64 "\n",166strerror(errno), CountersBegin, PageAlignedCountersLength, Fileno,167FileOffsetToCounters);168return 1;169}170171/* Also mmap MCDC bitmap bytes. If there aren't any bitmap bytes, mmap()172* will fail with EINVAL. */173if (NumBitmapBytes == 0)174return 0;175176uint64_t PageAlignedBitmapLength =177NumBitmapBytes + PaddingBytesAfterBitmapBytes;178uint64_t FileOffsetToBitmap =179FileOffsetToCounters + CountersSize + PaddingBytesAfterCounters;180void *BitmapMmap =181mmap((void *)BitmapBegin, PageAlignedBitmapLength, PROT_READ | PROT_WRITE,182MAP_FIXED | MAP_SHARED, Fileno, FileOffsetToBitmap);183if (BitmapMmap != BitmapBegin) {184PROF_ERR(185"Continuous counter sync mode is enabled, but mmap() failed (%s).\n"186" - BitmapBegin: %p\n"187" - PageAlignedBitmapLength: %" PRIu64 "\n"188" - Fileno: %d\n"189" - FileOffsetToBitmap: %" PRIu64 "\n",190strerror(errno), BitmapBegin, PageAlignedBitmapLength, Fileno,191FileOffsetToBitmap);192return 1;193}194return 0;195}196#elif defined(__ELF__) || defined(_WIN32)197198#define INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR \199INSTR_PROF_CONCAT(INSTR_PROF_PROFILE_COUNTER_BIAS_VAR, _default)200COMPILER_RT_VISIBILITY intptr_t INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR = 0;201202/* This variable is a weak external reference which could be used to detect203* whether or not the compiler defined this symbol. */204#if defined(_MSC_VER)205COMPILER_RT_VISIBILITY extern intptr_t INSTR_PROF_PROFILE_COUNTER_BIAS_VAR;206#if defined(_M_IX86) || defined(__i386__)207#define WIN_SYM_PREFIX "_"208#else209#define WIN_SYM_PREFIX210#endif211#pragma comment( \212linker, "/alternatename:" WIN_SYM_PREFIX INSTR_PROF_QUOTE( \213INSTR_PROF_PROFILE_COUNTER_BIAS_VAR) "=" WIN_SYM_PREFIX \214INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR))215#else216COMPILER_RT_VISIBILITY extern intptr_t INSTR_PROF_PROFILE_COUNTER_BIAS_VAR217__attribute__((weak, alias(INSTR_PROF_QUOTE(218INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR))));219#endif220static const int ContinuousModeSupported = 1;221static const int UseBiasVar = 1;222/* TODO: If there are two DSOs, the second DSO initilization will truncate the223* first profile file. */224static const char *FileOpenMode = "w+b";225/* This symbol is defined by the compiler when runtime counter relocation is226* used and runtime provides a weak alias so we can check if it's defined. */227static void *BiasAddr = &INSTR_PROF_PROFILE_COUNTER_BIAS_VAR;228static void *BiasDefaultAddr = &INSTR_PROF_PROFILE_COUNTER_BIAS_DEFAULT_VAR;229static int mmapForContinuousMode(uint64_t CurrentFileOffset, FILE *File) {230/* Get the sizes of various profile data sections. Taken from231* __llvm_profile_get_size_for_buffer(). */232const __llvm_profile_data *DataBegin = __llvm_profile_begin_data();233const __llvm_profile_data *DataEnd = __llvm_profile_end_data();234const char *CountersBegin = __llvm_profile_begin_counters();235const char *CountersEnd = __llvm_profile_end_counters();236const char *BitmapBegin = __llvm_profile_begin_bitmap();237const char *BitmapEnd = __llvm_profile_end_bitmap();238uint64_t DataSize = __llvm_profile_get_data_size(DataBegin, DataEnd);239/* Get the file size. */240uint64_t FileSize = 0;241if (getProfileFileSizeForMerging(File, &FileSize))242return 1;243244int Fileno = fileno(File);245uint64_t FileOffsetToCounters =246sizeof(__llvm_profile_header) + __llvm_write_binary_ids(NULL) + DataSize;247248/* Map the profile. */249char *Profile = (char *)mmap(NULL, FileSize, PROT_READ | PROT_WRITE,250MAP_SHARED, Fileno, 0);251if (Profile == MAP_FAILED) {252PROF_ERR("Unable to mmap profile: %s\n", strerror(errno));253return 1;254}255/* Update the profile fields based on the current mapping. */256INSTR_PROF_PROFILE_COUNTER_BIAS_VAR =257(intptr_t)Profile - (uintptr_t)CountersBegin + FileOffsetToCounters;258259/* Return the memory allocated for counters to OS. */260lprofReleaseMemoryPagesToOS((uintptr_t)CountersBegin, (uintptr_t)CountersEnd);261262/* BIAS MODE not supported yet for Bitmap (MCDC). */263264/* Return the memory allocated for counters to OS. */265lprofReleaseMemoryPagesToOS((uintptr_t)BitmapBegin, (uintptr_t)BitmapEnd);266return 0;267}268#else269static const int ContinuousModeSupported = 0;270static const int UseBiasVar = 0;271static const char *FileOpenMode = "a+b";272static void *BiasAddr = NULL;273static void *BiasDefaultAddr = NULL;274static int mmapForContinuousMode(uint64_t CurrentFileOffset, FILE *File) {275return 0;276}277#endif278279static int isProfileMergeRequested(void) { return ProfileMergeRequested; }280static void setProfileMergeRequested(int EnableMerge) {281ProfileMergeRequested = EnableMerge;282}283284static FILE *ProfileFile = NULL;285static FILE *getProfileFile(void) { return ProfileFile; }286static void setProfileFile(FILE *File) { ProfileFile = File; }287288static int getCurFilenameLength(void);289static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf);290static unsigned doMerging(void) {291return lprofCurFilename.MergePoolSize || isProfileMergeRequested();292}293294/* Return 1 if there is an error, otherwise return 0. */295static uint32_t fileWriter(ProfDataWriter *This, ProfDataIOVec *IOVecs,296uint32_t NumIOVecs) {297uint32_t I;298FILE *File = (FILE *)This->WriterCtx;299char Zeroes[sizeof(uint64_t)] = {0};300for (I = 0; I < NumIOVecs; I++) {301if (IOVecs[I].Data) {302if (fwrite(IOVecs[I].Data, IOVecs[I].ElmSize, IOVecs[I].NumElm, File) !=303IOVecs[I].NumElm)304return 1;305} else if (IOVecs[I].UseZeroPadding) {306size_t BytesToWrite = IOVecs[I].ElmSize * IOVecs[I].NumElm;307while (BytesToWrite > 0) {308size_t PartialWriteLen =309(sizeof(uint64_t) > BytesToWrite) ? BytesToWrite : sizeof(uint64_t);310if (fwrite(Zeroes, sizeof(uint8_t), PartialWriteLen, File) !=311PartialWriteLen) {312return 1;313}314BytesToWrite -= PartialWriteLen;315}316} else {317if (fseek(File, IOVecs[I].ElmSize * IOVecs[I].NumElm, SEEK_CUR) == -1)318return 1;319}320}321return 0;322}323324/* TODO: make buffer size controllable by an internal option, and compiler can pass the size325to runtime via a variable. */326static uint32_t orderFileWriter(FILE *File, const uint32_t *DataStart) {327if (fwrite(DataStart, sizeof(uint32_t), INSTR_ORDER_FILE_BUFFER_SIZE, File) !=328INSTR_ORDER_FILE_BUFFER_SIZE)329return 1;330return 0;331}332333static void initFileWriter(ProfDataWriter *This, FILE *File) {334This->Write = fileWriter;335This->WriterCtx = File;336}337338COMPILER_RT_VISIBILITY ProfBufferIO *339lprofCreateBufferIOInternal(void *File, uint32_t BufferSz) {340FreeHook = &free;341DynamicBufferIOBuffer = (uint8_t *)calloc(1, BufferSz);342VPBufferSize = BufferSz;343ProfDataWriter *fileWriter =344(ProfDataWriter *)calloc(1, sizeof(ProfDataWriter));345initFileWriter(fileWriter, File);346ProfBufferIO *IO = lprofCreateBufferIO(fileWriter);347IO->OwnFileWriter = 1;348return IO;349}350351static void setupIOBuffer(void) {352const char *BufferSzStr = 0;353BufferSzStr = getenv("LLVM_VP_BUFFER_SIZE");354if (BufferSzStr && BufferSzStr[0]) {355VPBufferSize = atoi(BufferSzStr);356DynamicBufferIOBuffer = (uint8_t *)calloc(VPBufferSize, 1);357}358}359360/* Get the size of the profile file. If there are any errors, print the361* message under the assumption that the profile is being read for merging362* purposes, and return -1. Otherwise return the file size in the inout param363* \p ProfileFileSize. */364static int getProfileFileSizeForMerging(FILE *ProfileFile,365uint64_t *ProfileFileSize) {366if (fseek(ProfileFile, 0L, SEEK_END) == -1) {367PROF_ERR("Unable to merge profile data, unable to get size: %s\n",368strerror(errno));369return -1;370}371*ProfileFileSize = ftell(ProfileFile);372373/* Restore file offset. */374if (fseek(ProfileFile, 0L, SEEK_SET) == -1) {375PROF_ERR("Unable to merge profile data, unable to rewind: %s\n",376strerror(errno));377return -1;378}379380if (*ProfileFileSize > 0 &&381*ProfileFileSize < sizeof(__llvm_profile_header)) {382PROF_WARN("Unable to merge profile data: %s\n",383"source profile file is too small.");384return -1;385}386return 0;387}388389/* mmap() \p ProfileFile for profile merging purposes, assuming that an390* exclusive lock is held on the file and that \p ProfileFileSize is the391* length of the file. Return the mmap'd buffer in the inout variable392* \p ProfileBuffer. Returns -1 on failure. On success, the caller is393* responsible for unmapping the mmap'd buffer in \p ProfileBuffer. */394static int mmapProfileForMerging(FILE *ProfileFile, uint64_t ProfileFileSize,395char **ProfileBuffer) {396*ProfileBuffer = mmap(NULL, ProfileFileSize, PROT_READ, MAP_SHARED | MAP_FILE,397fileno(ProfileFile), 0);398if (*ProfileBuffer == MAP_FAILED) {399PROF_ERR("Unable to merge profile data, mmap failed: %s\n",400strerror(errno));401return -1;402}403404if (__llvm_profile_check_compatibility(*ProfileBuffer, ProfileFileSize)) {405(void)munmap(*ProfileBuffer, ProfileFileSize);406PROF_WARN("Unable to merge profile data: %s\n",407"source profile file is not compatible.");408return -1;409}410return 0;411}412413/* Read profile data in \c ProfileFile and merge with in-memory414profile counters. Returns -1 if there is fatal error, otheriwse4150 is returned. Returning 0 does not mean merge is actually416performed. If merge is actually done, *MergeDone is set to 1.417*/418static int doProfileMerging(FILE *ProfileFile, int *MergeDone) {419uint64_t ProfileFileSize;420char *ProfileBuffer;421422/* Get the size of the profile on disk. */423if (getProfileFileSizeForMerging(ProfileFile, &ProfileFileSize) == -1)424return -1;425426/* Nothing to merge. */427if (!ProfileFileSize)428return 0;429430/* mmap() the profile and check that it is compatible with the data in431* the current image. */432if (mmapProfileForMerging(ProfileFile, ProfileFileSize, &ProfileBuffer) == -1)433return -1;434435/* Now start merging */436if (__llvm_profile_merge_from_buffer(ProfileBuffer, ProfileFileSize)) {437PROF_ERR("%s\n", "Invalid profile data to merge");438(void)munmap(ProfileBuffer, ProfileFileSize);439return -1;440}441442// Truncate the file in case merging of value profile did not happen to443// prevent from leaving garbage data at the end of the profile file.444(void)COMPILER_RT_FTRUNCATE(ProfileFile,445__llvm_profile_get_size_for_buffer());446447(void)munmap(ProfileBuffer, ProfileFileSize);448*MergeDone = 1;449450return 0;451}452453/* Create the directory holding the file, if needed. */454static void createProfileDir(const char *Filename) {455size_t Length = strlen(Filename);456if (lprofFindFirstDirSeparator(Filename)) {457char *Copy = (char *)COMPILER_RT_ALLOCA(Length + 1);458strncpy(Copy, Filename, Length + 1);459__llvm_profile_recursive_mkdir(Copy);460}461}462463/* Open the profile data for merging. It opens the file in r+b mode with464* file locking. If the file has content which is compatible with the465* current process, it also reads in the profile data in the file and merge466* it with in-memory counters. After the profile data is merged in memory,467* the original profile data is truncated and gets ready for the profile468* dumper. With profile merging enabled, each executable as well as any of469* its instrumented shared libraries dump profile data into their own data file.470*/471static FILE *openFileForMerging(const char *ProfileFileName, int *MergeDone) {472FILE *ProfileFile = getProfileFile();473int rc;474// initializeProfileForContinuousMode will lock the profile, but if475// ProfileFile is set by user via __llvm_profile_set_file_object, it's assumed476// unlocked at this point.477if (ProfileFile && !__llvm_profile_is_continuous_mode_enabled()) {478lprofLockFileHandle(ProfileFile);479}480if (!ProfileFile) {481createProfileDir(ProfileFileName);482ProfileFile = lprofOpenFileEx(ProfileFileName);483}484if (!ProfileFile)485return NULL;486487rc = doProfileMerging(ProfileFile, MergeDone);488if (rc || (!*MergeDone && COMPILER_RT_FTRUNCATE(ProfileFile, 0L)) ||489fseek(ProfileFile, 0L, SEEK_SET) == -1) {490PROF_ERR("Profile Merging of file %s failed: %s\n", ProfileFileName,491strerror(errno));492fclose(ProfileFile);493return NULL;494}495return ProfileFile;496}497498static FILE *getFileObject(const char *OutputName) {499FILE *File;500File = getProfileFile();501if (File != NULL) {502return File;503}504505return fopen(OutputName, "ab");506}507508/* Write profile data to file \c OutputName. */509static int writeFile(const char *OutputName) {510int RetVal;511FILE *OutputFile;512513int MergeDone = 0;514VPMergeHook = &lprofMergeValueProfData;515if (doMerging())516OutputFile = openFileForMerging(OutputName, &MergeDone);517else518OutputFile = getFileObject(OutputName);519520if (!OutputFile)521return -1;522523FreeHook = &free;524setupIOBuffer();525ProfDataWriter fileWriter;526initFileWriter(&fileWriter, OutputFile);527RetVal = lprofWriteData(&fileWriter, lprofGetVPDataReader(), MergeDone);528529if (OutputFile == getProfileFile()) {530fflush(OutputFile);531if (doMerging() && !__llvm_profile_is_continuous_mode_enabled()) {532lprofUnlockFileHandle(OutputFile);533}534} else {535fclose(OutputFile);536}537538return RetVal;539}540541/* Write order data to file \c OutputName. */542static int writeOrderFile(const char *OutputName) {543int RetVal;544FILE *OutputFile;545546OutputFile = fopen(OutputName, "w");547548if (!OutputFile) {549PROF_WARN("can't open file with mode ab: %s\n", OutputName);550return -1;551}552553FreeHook = &free;554setupIOBuffer();555const uint32_t *DataBegin = __llvm_profile_begin_orderfile();556RetVal = orderFileWriter(OutputFile, DataBegin);557558fclose(OutputFile);559return RetVal;560}561562#define LPROF_INIT_ONCE_ENV "__LLVM_PROFILE_RT_INIT_ONCE"563564static void truncateCurrentFile(void) {565const char *Filename;566char *FilenameBuf;567FILE *File;568int Length;569570Length = getCurFilenameLength();571FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);572Filename = getCurFilename(FilenameBuf, 0);573if (!Filename)574return;575576/* Only create the profile directory and truncate an existing profile once.577* In continuous mode, this is necessary, as the profile is written-to by the578* runtime initializer. */579int initialized = getenv(LPROF_INIT_ONCE_ENV) != NULL;580if (initialized)581return;582#if defined(_WIN32)583_putenv(LPROF_INIT_ONCE_ENV "=" LPROF_INIT_ONCE_ENV);584#else585setenv(LPROF_INIT_ONCE_ENV, LPROF_INIT_ONCE_ENV, 1);586#endif587588/* Create the profile dir (even if online merging is enabled), so that589* the profile file can be set up if continuous mode is enabled. */590createProfileDir(Filename);591592/* By pass file truncation to allow online raw profile merging. */593if (lprofCurFilename.MergePoolSize)594return;595596/* Truncate the file. Later we'll reopen and append. */597File = fopen(Filename, "w");598if (!File)599return;600fclose(File);601}602603/* Write a partial profile to \p Filename, which is required to be backed by604* the open file object \p File. */605static int writeProfileWithFileObject(const char *Filename, FILE *File) {606setProfileFile(File);607int rc = writeFile(Filename);608if (rc)609PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));610setProfileFile(NULL);611return rc;612}613614static void initializeProfileForContinuousMode(void) {615if (!__llvm_profile_is_continuous_mode_enabled())616return;617if (!ContinuousModeSupported) {618PROF_ERR("%s\n", "continuous mode is unsupported on this platform");619return;620}621if (UseBiasVar && BiasAddr == BiasDefaultAddr) {622PROF_ERR("%s\n", "__llvm_profile_counter_bias is undefined");623return;624}625626/* Get the sizes of counter section. */627uint64_t CountersSize = __llvm_profile_get_counters_size(628__llvm_profile_begin_counters(), __llvm_profile_end_counters());629630int Length = getCurFilenameLength();631char *FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);632const char *Filename = getCurFilename(FilenameBuf, 0);633if (!Filename)634return;635636FILE *File = NULL;637uint64_t CurrentFileOffset = 0;638if (doMerging()) {639/* We are merging profiles. Map the counter section as shared memory into640* the profile, i.e. into each participating process. An increment in one641* process should be visible to every other process with the same counter642* section mapped. */643File = lprofOpenFileEx(Filename);644if (!File)645return;646647uint64_t ProfileFileSize = 0;648if (getProfileFileSizeForMerging(File, &ProfileFileSize) == -1) {649lprofUnlockFileHandle(File);650fclose(File);651return;652}653if (ProfileFileSize == 0) {654/* Grow the profile so that mmap() can succeed. Leak the file handle, as655* the file should stay open. */656if (writeProfileWithFileObject(Filename, File) != 0) {657lprofUnlockFileHandle(File);658fclose(File);659return;660}661} else {662/* The merged profile has a non-zero length. Check that it is compatible663* with the data in this process. */664char *ProfileBuffer;665if (mmapProfileForMerging(File, ProfileFileSize, &ProfileBuffer) == -1) {666lprofUnlockFileHandle(File);667fclose(File);668return;669}670(void)munmap(ProfileBuffer, ProfileFileSize);671}672} else {673File = fopen(Filename, FileOpenMode);674if (!File)675return;676/* Check that the offset within the file is page-aligned. */677CurrentFileOffset = ftell(File);678unsigned PageSize = getpagesize();679if (CurrentFileOffset % PageSize != 0) {680PROF_ERR("Continuous counter sync mode is enabled, but raw profile is not"681"page-aligned. CurrentFileOffset = %" PRIu64 ", pagesz = %u.\n",682(uint64_t)CurrentFileOffset, PageSize);683fclose(File);684return;685}686if (writeProfileWithFileObject(Filename, File) != 0) {687fclose(File);688return;689}690}691692/* mmap() the profile counters so long as there is at least one counter.693* If there aren't any counters, mmap() would fail with EINVAL. */694if (CountersSize > 0)695mmapForContinuousMode(CurrentFileOffset, File);696697if (doMerging()) {698lprofUnlockFileHandle(File);699}700if (File != NULL) {701fclose(File);702}703}704705static const char *DefaultProfileName = "default.profraw";706static void resetFilenameToDefault(void) {707if (lprofCurFilename.FilenamePat && lprofCurFilename.OwnsFilenamePat) {708#ifdef __GNUC__709#pragma GCC diagnostic push710#pragma GCC diagnostic ignored "-Wcast-qual"711#elif defined(__clang__)712#pragma clang diagnostic push713#pragma clang diagnostic ignored "-Wcast-qual"714#endif715free((void *)lprofCurFilename.FilenamePat);716#ifdef __GNUC__717#pragma GCC diagnostic pop718#elif defined(__clang__)719#pragma clang diagnostic pop720#endif721}722memset(&lprofCurFilename, 0, sizeof(lprofCurFilename));723lprofCurFilename.FilenamePat = DefaultProfileName;724lprofCurFilename.PNS = PNS_default;725}726727static unsigned getMergePoolSize(const char *FilenamePat, int *I) {728unsigned J = 0, Num = 0;729for (;; ++J) {730char C = FilenamePat[*I + J];731if (C == 'm') {732*I += J;733return Num ? Num : 1;734}735if (C < '0' || C > '9')736break;737Num = Num * 10 + C - '0';738739/* If FilenamePat[*I+J] is between '0' and '9', the next byte is guaranteed740* to be in-bound as the string is null terminated. */741}742return 0;743}744745/* Assert that Idx does index past a string null terminator. Return the746* result of the check. */747static int checkBounds(int Idx, int Strlen) {748assert(Idx <= Strlen && "Indexing past string null terminator");749return Idx <= Strlen;750}751752/* Parses the pattern string \p FilenamePat and stores the result to753* lprofcurFilename structure. */754static int parseFilenamePattern(const char *FilenamePat,755unsigned CopyFilenamePat) {756int NumPids = 0, NumHosts = 0, I;757char *PidChars = &lprofCurFilename.PidChars[0];758char *Hostname = &lprofCurFilename.Hostname[0];759int MergingEnabled = 0;760int FilenamePatLen = strlen(FilenamePat);761762#ifdef __GNUC__763#pragma GCC diagnostic push764#pragma GCC diagnostic ignored "-Wcast-qual"765#elif defined(__clang__)766#pragma clang diagnostic push767#pragma clang diagnostic ignored "-Wcast-qual"768#endif769/* Clean up cached prefix and filename. */770if (lprofCurFilename.ProfilePathPrefix)771free((void *)lprofCurFilename.ProfilePathPrefix);772773if (lprofCurFilename.FilenamePat && lprofCurFilename.OwnsFilenamePat) {774free((void *)lprofCurFilename.FilenamePat);775}776#ifdef __GNUC__777#pragma GCC diagnostic pop778#elif defined(__clang__)779#pragma clang diagnostic pop780#endif781782memset(&lprofCurFilename, 0, sizeof(lprofCurFilename));783784if (!CopyFilenamePat)785lprofCurFilename.FilenamePat = FilenamePat;786else {787lprofCurFilename.FilenamePat = strdup(FilenamePat);788lprofCurFilename.OwnsFilenamePat = 1;789}790/* Check the filename for "%p", which indicates a pid-substitution. */791for (I = 0; checkBounds(I, FilenamePatLen) && FilenamePat[I]; ++I) {792if (FilenamePat[I] == '%') {793++I; /* Advance to the next character. */794if (!checkBounds(I, FilenamePatLen))795break;796if (FilenamePat[I] == 'p') {797if (!NumPids++) {798if (snprintf(PidChars, MAX_PID_SIZE, "%ld", (long)getpid()) <= 0) {799PROF_WARN("Unable to get pid for filename pattern %s. Using the "800"default name.",801FilenamePat);802return -1;803}804}805} else if (FilenamePat[I] == 'h') {806if (!NumHosts++)807if (COMPILER_RT_GETHOSTNAME(Hostname, COMPILER_RT_MAX_HOSTLEN)) {808PROF_WARN("Unable to get hostname for filename pattern %s. Using "809"the default name.",810FilenamePat);811return -1;812}813} else if (FilenamePat[I] == 't') {814lprofCurFilename.TmpDir = getenv("TMPDIR");815if (!lprofCurFilename.TmpDir) {816PROF_WARN("Unable to get the TMPDIR environment variable, referenced "817"in %s. Using the default path.",818FilenamePat);819return -1;820}821} else if (FilenamePat[I] == 'c') {822if (__llvm_profile_is_continuous_mode_enabled()) {823PROF_WARN("%%c specifier can only be specified once in %s.\n",824FilenamePat);825__llvm_profile_disable_continuous_mode();826return -1;827}828#if defined(__APPLE__) || defined(__ELF__) || defined(_WIN32)829__llvm_profile_set_page_size(getpagesize());830__llvm_profile_enable_continuous_mode();831#else832PROF_WARN("%s", "Continous mode is currently only supported for Mach-O,"833" ELF and COFF formats.");834return -1;835#endif836} else {837unsigned MergePoolSize = getMergePoolSize(FilenamePat, &I);838if (!MergePoolSize)839continue;840if (MergingEnabled) {841PROF_WARN("%%m specifier can only be specified once in %s.\n",842FilenamePat);843return -1;844}845MergingEnabled = 1;846lprofCurFilename.MergePoolSize = MergePoolSize;847}848}849}850851lprofCurFilename.NumPids = NumPids;852lprofCurFilename.NumHosts = NumHosts;853return 0;854}855856static void parseAndSetFilename(const char *FilenamePat,857ProfileNameSpecifier PNS,858unsigned CopyFilenamePat) {859860const char *OldFilenamePat = lprofCurFilename.FilenamePat;861ProfileNameSpecifier OldPNS = lprofCurFilename.PNS;862863/* The old profile name specifier takes precedence over the old one. */864if (PNS < OldPNS)865return;866867if (!FilenamePat)868FilenamePat = DefaultProfileName;869870if (OldFilenamePat && !strcmp(OldFilenamePat, FilenamePat)) {871lprofCurFilename.PNS = PNS;872return;873}874875/* When PNS >= OldPNS, the last one wins. */876if (!FilenamePat || parseFilenamePattern(FilenamePat, CopyFilenamePat))877resetFilenameToDefault();878lprofCurFilename.PNS = PNS;879880if (!OldFilenamePat) {881if (getenv("LLVM_PROFILE_VERBOSE"))882PROF_NOTE("Set profile file path to \"%s\" via %s.\n",883lprofCurFilename.FilenamePat, getPNSStr(PNS));884} else {885if (getenv("LLVM_PROFILE_VERBOSE"))886PROF_NOTE("Override old profile path \"%s\" via %s to \"%s\" via %s.\n",887OldFilenamePat, getPNSStr(OldPNS), lprofCurFilename.FilenamePat,888getPNSStr(PNS));889}890891truncateCurrentFile();892if (__llvm_profile_is_continuous_mode_enabled())893initializeProfileForContinuousMode();894}895896/* Return buffer length that is required to store the current profile897* filename with PID and hostname substitutions. */898/* The length to hold uint64_t followed by 3 digits pool id including '_' */899#define SIGLEN 24900static int getCurFilenameLength(void) {901int Len;902if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])903return 0;904905if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||906lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize))907return strlen(lprofCurFilename.FilenamePat);908909Len = strlen(lprofCurFilename.FilenamePat) +910lprofCurFilename.NumPids * (strlen(lprofCurFilename.PidChars) - 2) +911lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2) +912(lprofCurFilename.TmpDir ? (strlen(lprofCurFilename.TmpDir) - 1) : 0);913if (lprofCurFilename.MergePoolSize)914Len += SIGLEN;915return Len;916}917918/* Return the pointer to the current profile file name (after substituting919* PIDs and Hostnames in filename pattern. \p FilenameBuf is the buffer920* to store the resulting filename. If no substitution is needed, the921* current filename pattern string is directly returned, unless ForceUseBuf922* is enabled. */923static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {924int I, J, PidLength, HostNameLength, TmpDirLength, FilenamePatLength;925const char *FilenamePat = lprofCurFilename.FilenamePat;926927if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])928return 0;929930if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||931lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize ||932__llvm_profile_is_continuous_mode_enabled())) {933if (!ForceUseBuf)934return lprofCurFilename.FilenamePat;935936FilenamePatLength = strlen(lprofCurFilename.FilenamePat);937memcpy(FilenameBuf, lprofCurFilename.FilenamePat, FilenamePatLength);938FilenameBuf[FilenamePatLength] = '\0';939return FilenameBuf;940}941942PidLength = strlen(lprofCurFilename.PidChars);943HostNameLength = strlen(lprofCurFilename.Hostname);944TmpDirLength = lprofCurFilename.TmpDir ? strlen(lprofCurFilename.TmpDir) : 0;945/* Construct the new filename. */946for (I = 0, J = 0; FilenamePat[I]; ++I)947if (FilenamePat[I] == '%') {948if (FilenamePat[++I] == 'p') {949memcpy(FilenameBuf + J, lprofCurFilename.PidChars, PidLength);950J += PidLength;951} else if (FilenamePat[I] == 'h') {952memcpy(FilenameBuf + J, lprofCurFilename.Hostname, HostNameLength);953J += HostNameLength;954} else if (FilenamePat[I] == 't') {955memcpy(FilenameBuf + J, lprofCurFilename.TmpDir, TmpDirLength);956FilenameBuf[J + TmpDirLength] = DIR_SEPARATOR;957J += TmpDirLength + 1;958} else {959if (!getMergePoolSize(FilenamePat, &I))960continue;961char LoadModuleSignature[SIGLEN + 1];962int S;963int ProfilePoolId = getpid() % lprofCurFilename.MergePoolSize;964S = snprintf(LoadModuleSignature, SIGLEN + 1, "%" PRIu64 "_%d",965lprofGetLoadModuleSignature(), ProfilePoolId);966if (S == -1 || S > SIGLEN)967S = SIGLEN;968memcpy(FilenameBuf + J, LoadModuleSignature, S);969J += S;970}971/* Drop any unknown substitutions. */972} else973FilenameBuf[J++] = FilenamePat[I];974FilenameBuf[J] = 0;975976return FilenameBuf;977}978979/* Returns the pointer to the environment variable980* string. Returns null if the env var is not set. */981static const char *getFilenamePatFromEnv(void) {982const char *Filename = getenv("LLVM_PROFILE_FILE");983if (!Filename || !Filename[0])984return 0;985return Filename;986}987988COMPILER_RT_VISIBILITY989const char *__llvm_profile_get_path_prefix(void) {990int Length;991char *FilenameBuf, *Prefix;992const char *Filename, *PrefixEnd;993994if (lprofCurFilename.ProfilePathPrefix)995return lprofCurFilename.ProfilePathPrefix;996997Length = getCurFilenameLength();998FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);999Filename = getCurFilename(FilenameBuf, 0);1000if (!Filename)1001return "\0";10021003PrefixEnd = lprofFindLastDirSeparator(Filename);1004if (!PrefixEnd)1005return "\0";10061007Length = PrefixEnd - Filename + 1;1008Prefix = (char *)malloc(Length + 1);1009if (!Prefix) {1010PROF_ERR("Failed to %s\n", "allocate memory.");1011return "\0";1012}1013memcpy(Prefix, Filename, Length);1014Prefix[Length] = '\0';1015lprofCurFilename.ProfilePathPrefix = Prefix;1016return Prefix;1017}10181019COMPILER_RT_VISIBILITY1020const char *__llvm_profile_get_filename(void) {1021int Length;1022char *FilenameBuf;1023const char *Filename;10241025Length = getCurFilenameLength();1026FilenameBuf = (char *)malloc(Length + 1);1027if (!FilenameBuf) {1028PROF_ERR("Failed to %s\n", "allocate memory.");1029return "\0";1030}1031Filename = getCurFilename(FilenameBuf, 1);1032if (!Filename)1033return "\0";10341035return FilenameBuf;1036}10371038/* This API initializes the file handling, both user specified1039* profile path via -fprofile-instr-generate= and LLVM_PROFILE_FILE1040* environment variable can override this default value.1041*/1042COMPILER_RT_VISIBILITY1043void __llvm_profile_initialize_file(void) {1044const char *EnvFilenamePat;1045const char *SelectedPat = NULL;1046ProfileNameSpecifier PNS = PNS_unknown;1047int hasCommandLineOverrider = (INSTR_PROF_PROFILE_NAME_VAR[0] != 0);10481049EnvFilenamePat = getFilenamePatFromEnv();1050if (EnvFilenamePat) {1051/* Pass CopyFilenamePat = 1, to ensure that the filename would be valid1052at the moment when __llvm_profile_write_file() gets executed. */1053parseAndSetFilename(EnvFilenamePat, PNS_environment, 1);1054return;1055} else if (hasCommandLineOverrider) {1056SelectedPat = INSTR_PROF_PROFILE_NAME_VAR;1057PNS = PNS_command_line;1058} else {1059SelectedPat = NULL;1060PNS = PNS_default;1061}10621063parseAndSetFilename(SelectedPat, PNS, 0);1064}10651066/* This method is invoked by the runtime initialization hook1067* InstrProfilingRuntime.o if it is linked in.1068*/1069COMPILER_RT_VISIBILITY1070void __llvm_profile_initialize(void) {1071__llvm_profile_initialize_file();1072if (!__llvm_profile_is_continuous_mode_enabled())1073__llvm_profile_register_write_file_atexit();1074}10751076/* This API is directly called by the user application code. It has the1077* highest precedence compared with LLVM_PROFILE_FILE environment variable1078* and command line option -fprofile-instr-generate=<profile_name>.1079*/1080COMPILER_RT_VISIBILITY1081void __llvm_profile_set_filename(const char *FilenamePat) {1082if (__llvm_profile_is_continuous_mode_enabled())1083return;1084parseAndSetFilename(FilenamePat, PNS_runtime_api, 1);1085}10861087/* The public API for writing profile data into the file with name1088* set by previous calls to __llvm_profile_set_filename or1089* __llvm_profile_override_default_filename or1090* __llvm_profile_initialize_file. */1091COMPILER_RT_VISIBILITY1092int __llvm_profile_write_file(void) {1093int rc, Length;1094const char *Filename;1095char *FilenameBuf;10961097// Temporarily suspend getting SIGKILL when the parent exits.1098int PDeathSig = lprofSuspendSigKill();10991100if (lprofProfileDumped() || __llvm_profile_is_continuous_mode_enabled()) {1101PROF_NOTE("Profile data not written to file: %s.\n", "already written");1102if (PDeathSig == 1)1103lprofRestoreSigKill();1104return 0;1105}11061107Length = getCurFilenameLength();1108FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);1109Filename = getCurFilename(FilenameBuf, 0);11101111/* Check the filename. */1112if (!Filename) {1113PROF_ERR("Failed to write file : %s\n", "Filename not set");1114if (PDeathSig == 1)1115lprofRestoreSigKill();1116return -1;1117}11181119/* Check if there is llvm/runtime version mismatch. */1120if (GET_VERSION(__llvm_profile_get_version()) != INSTR_PROF_RAW_VERSION) {1121PROF_ERR("Runtime and instrumentation version mismatch : "1122"expected %d, but get %d\n",1123INSTR_PROF_RAW_VERSION,1124(int)GET_VERSION(__llvm_profile_get_version()));1125if (PDeathSig == 1)1126lprofRestoreSigKill();1127return -1;1128}11291130/* Write profile data to the file. */1131rc = writeFile(Filename);1132if (rc)1133PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));11341135// Restore SIGKILL.1136if (PDeathSig == 1)1137lprofRestoreSigKill();11381139return rc;1140}11411142COMPILER_RT_VISIBILITY1143int __llvm_profile_dump(void) {1144if (!doMerging())1145PROF_WARN("Later invocation of __llvm_profile_dump can lead to clobbering "1146" of previously dumped profile data : %s. Either use %%m "1147"in profile name or change profile name before dumping.\n",1148"online profile merging is not on");1149int rc = __llvm_profile_write_file();1150lprofSetProfileDumped(1);1151return rc;1152}11531154/* Order file data will be saved in a file with suffx .order. */1155static const char *OrderFileSuffix = ".order";11561157COMPILER_RT_VISIBILITY1158int __llvm_orderfile_write_file(void) {1159int rc, Length, LengthBeforeAppend, SuffixLength;1160const char *Filename;1161char *FilenameBuf;11621163// Temporarily suspend getting SIGKILL when the parent exits.1164int PDeathSig = lprofSuspendSigKill();11651166SuffixLength = strlen(OrderFileSuffix);1167Length = getCurFilenameLength() + SuffixLength;1168FilenameBuf = (char *)COMPILER_RT_ALLOCA(Length + 1);1169Filename = getCurFilename(FilenameBuf, 1);11701171/* Check the filename. */1172if (!Filename) {1173PROF_ERR("Failed to write file : %s\n", "Filename not set");1174if (PDeathSig == 1)1175lprofRestoreSigKill();1176return -1;1177}11781179/* Append order file suffix */1180LengthBeforeAppend = strlen(Filename);1181memcpy(FilenameBuf + LengthBeforeAppend, OrderFileSuffix, SuffixLength);1182FilenameBuf[LengthBeforeAppend + SuffixLength] = '\0';11831184/* Check if there is llvm/runtime version mismatch. */1185if (GET_VERSION(__llvm_profile_get_version()) != INSTR_PROF_RAW_VERSION) {1186PROF_ERR("Runtime and instrumentation version mismatch : "1187"expected %d, but get %d\n",1188INSTR_PROF_RAW_VERSION,1189(int)GET_VERSION(__llvm_profile_get_version()));1190if (PDeathSig == 1)1191lprofRestoreSigKill();1192return -1;1193}11941195/* Write order data to the file. */1196rc = writeOrderFile(Filename);1197if (rc)1198PROF_ERR("Failed to write file \"%s\": %s\n", Filename, strerror(errno));11991200// Restore SIGKILL.1201if (PDeathSig == 1)1202lprofRestoreSigKill();12031204return rc;1205}12061207COMPILER_RT_VISIBILITY1208int __llvm_orderfile_dump(void) {1209int rc = __llvm_orderfile_write_file();1210return rc;1211}12121213static void writeFileWithoutReturn(void) { __llvm_profile_write_file(); }12141215COMPILER_RT_VISIBILITY1216int __llvm_profile_register_write_file_atexit(void) {1217static int HasBeenRegistered = 0;12181219if (HasBeenRegistered)1220return 0;12211222lprofSetupValueProfiler();12231224HasBeenRegistered = 1;1225return atexit(writeFileWithoutReturn);1226}12271228COMPILER_RT_VISIBILITY int __llvm_profile_set_file_object(FILE *File,1229int EnableMerge) {1230if (__llvm_profile_is_continuous_mode_enabled()) {1231if (!EnableMerge) {1232PROF_WARN("__llvm_profile_set_file_object(fd=%d) not supported in "1233"continuous sync mode when merging is disabled\n",1234fileno(File));1235return 1;1236}1237if (lprofLockFileHandle(File) != 0) {1238PROF_WARN("Data may be corrupted during profile merging : %s\n",1239"Fail to obtain file lock due to system limit.");1240}1241uint64_t ProfileFileSize = 0;1242if (getProfileFileSizeForMerging(File, &ProfileFileSize) == -1) {1243lprofUnlockFileHandle(File);1244return 1;1245}1246if (ProfileFileSize == 0) {1247FreeHook = &free;1248setupIOBuffer();1249ProfDataWriter fileWriter;1250initFileWriter(&fileWriter, File);1251if (lprofWriteData(&fileWriter, 0, 0)) {1252lprofUnlockFileHandle(File);1253PROF_ERR("Failed to write file \"%d\": %s\n", fileno(File),1254strerror(errno));1255return 1;1256}1257fflush(File);1258} else {1259/* The merged profile has a non-zero length. Check that it is compatible1260* with the data in this process. */1261char *ProfileBuffer;1262if (mmapProfileForMerging(File, ProfileFileSize, &ProfileBuffer) == -1) {1263lprofUnlockFileHandle(File);1264return 1;1265}1266(void)munmap(ProfileBuffer, ProfileFileSize);1267}1268mmapForContinuousMode(0, File);1269lprofUnlockFileHandle(File);1270} else {1271setProfileFile(File);1272setProfileMergeRequested(EnableMerge);1273}1274return 0;1275}12761277#endif127812791280