Bug Summary

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