InstrProfilingFile.c 39 KB

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