Bug Summary

File:compiler-rt/lib/profile/InstrProfilingFile.c
Warning:line 943, column 9
Null pointer passed to 2nd parameter expecting 'nonnull'

Annotated Source Code

Press '?' to see keyboard shortcuts

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