Skip to content

[profile] Add %b LLVM_PROFILE_FILE option for binary ID #123963

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 6, 2025

Conversation

ArtSin
Copy link
Contributor

@ArtSin ArtSin commented Jan 22, 2025

Add support for expanding %b in LLVM_PROFILE_FILE to the binary ID (build ID). It can be used with %m to avoid its signature collisions.

This is supported on all platforms where writing binary IDs into profiles is implemented, as the __llvm_write_binary_ids function is used.

Fixes #51560.

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added clang Clang issues not falling into any other category compiler-rt PGO Profile Guided Optimizations labels Jan 22, 2025
@llvmbot
Copy link
Member

llvmbot commented Jan 22, 2025

@llvm/pr-subscribers-clang

Author: Sinkevich Artem (ArtSin)

Changes

Add support for expanding %b in LLVM_PROFILE_FILE to the binary ID (build ID). It can be used with %m to avoid its signature collisions.

This is supported on all platforms where writing binary IDs into profiles is implemented, as the __llvm_write_binary_ids function is used.

Fixes #51560.


Full diff: https://github.com/llvm/llvm-project/pull/123963.diff

4 Files Affected:

  • (modified) clang/docs/SourceBasedCodeCoverage.rst (+5)
  • (modified) clang/docs/UsersManual.rst (+3-2)
  • (modified) compiler-rt/lib/profile/InstrProfilingFile.c (+52-5)
  • (added) compiler-rt/test/profile/Linux/binary-id-path.c (+37)
diff --git a/clang/docs/SourceBasedCodeCoverage.rst b/clang/docs/SourceBasedCodeCoverage.rst
index 73910e134a5891..49bce3b72b45aa 100644
--- a/clang/docs/SourceBasedCodeCoverage.rst
+++ b/clang/docs/SourceBasedCodeCoverage.rst
@@ -94,6 +94,11 @@ directory structure will be created.  Additionally, the following special
   not specified (i.e the pattern is "%m"), it's assumed that ``N = 1``. The
   merge pool specifier can only occur once per filename pattern.
 
+* "%b" expands out to the binary ID (build ID). It can be used with "%Nm" to
+  avoid binary signature collisions. To use it, the program should be compiled
+  with the build ID linker option (``--build-id`` for GNU ld or LLD). Linux,
+  Windows and AIX are supported.
+
 * "%c" expands out to nothing, but enables a mode in which profile counter
   updates are continuously synced to a file. This means that if the
   instrumented program crashes, or is killed by a signal, perfect coverage
diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 260e84910c6f78..bc0ce3f3ccad07 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -2880,7 +2880,8 @@ instrumentation:
    environment variable to specify an alternate file. If non-default file name
    is specified by both the environment variable and the command line option,
    the environment variable takes precedence. The file name pattern specified
-   can include different modifiers: ``%p``, ``%h``, ``%m``, ``%t``, and ``%c``.
+   can include different modifiers: ``%p``, ``%h``, ``%m``, ``%b``, ``%t``, and
+   ``%c``.
 
    Any instance of ``%p`` in that file name will be replaced by the process
    ID, so that you can easily distinguish the profile output from multiple
@@ -2917,7 +2918,7 @@ instrumentation:
      $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
 
    See `this <SourceBasedCodeCoverage.html#running-the-instrumented-program>`_ section
-   about the ``%t``, and ``%c`` modifiers.
+   about the ``%b``, ``%t``, and ``%c`` modifiers.
 
 3. Combine profiles from multiple runs and convert the "raw" profile format to
    the input expected by clang. Use the ``merge`` command of the
diff --git a/compiler-rt/lib/profile/InstrProfilingFile.c b/compiler-rt/lib/profile/InstrProfilingFile.c
index bad4cc71801ec4..01fd314e577f76 100644
--- a/compiler-rt/lib/profile/InstrProfilingFile.c
+++ b/compiler-rt/lib/profile/InstrProfilingFile.c
@@ -77,6 +77,7 @@ typedef struct lprofFilename {
   char Hostname[COMPILER_RT_MAX_HOSTLEN];
   unsigned NumPids;
   unsigned NumHosts;
+  unsigned NumBinaryIds;
   /* When in-process merging is enabled, this parameter specifies
    * the total number of profile data files shared by all the processes
    * spawned from the same binary. By default the value is 1. If merging
@@ -88,8 +89,8 @@ typedef struct lprofFilename {
   ProfileNameSpecifier PNS;
 } lprofFilename;
 
-static lprofFilename lprofCurFilename = {0,   0, 0, {0}, NULL,
-                                         {0}, 0, 0, 0,   PNS_unknown};
+static lprofFilename lprofCurFilename = {0, 0, 0, {0}, NULL,       {0},
+                                         0, 0, 0, 0,   PNS_unknown};
 
 static int ProfileMergeRequested = 0;
 static int getProfileFileSizeForMerging(FILE *ProfileFile,
@@ -790,7 +791,7 @@ static int checkBounds(int Idx, int Strlen) {
  * lprofcurFilename structure. */
 static int parseFilenamePattern(const char *FilenamePat,
                                 unsigned CopyFilenamePat) {
-  int NumPids = 0, NumHosts = 0, I;
+  int NumPids = 0, NumHosts = 0, NumBinaryIds = 0, I;
   char *PidChars = &lprofCurFilename.PidChars[0];
   char *Hostname = &lprofCurFilename.Hostname[0];
   int MergingEnabled = 0;
@@ -855,6 +856,15 @@ static int parseFilenamePattern(const char *FilenamePat,
                     FilenamePat);
           return -1;
         }
+      } else if (FilenamePat[I] == 'b') {
+        if (!NumBinaryIds++) {
+          if (__llvm_write_binary_ids(NULL) <= 0) {
+            PROF_WARN("Unable to get binary ID for filename pattern %s. Using "
+                      "the default name.",
+                      FilenamePat);
+            return -1;
+          }
+        }
       } else if (FilenamePat[I] == 'c') {
         if (__llvm_profile_is_continuous_mode_enabled()) {
           PROF_WARN("%%c specifier can only be specified once in %s.\n",
@@ -887,6 +897,7 @@ static int parseFilenamePattern(const char *FilenamePat,
 
   lprofCurFilename.NumPids = NumPids;
   lprofCurFilename.NumHosts = NumHosts;
+  lprofCurFilename.NumBinaryIds = NumBinaryIds;
   return 0;
 }
 
@@ -934,24 +945,53 @@ static void parseAndSetFilename(const char *FilenamePat,
  * filename with PID and hostname substitutions. */
 /* The length to hold uint64_t followed by 3 digits pool id including '_' */
 #define SIGLEN 24
+/* The length to hold 160-bit hash in hexadecimal form */
+#define BINARY_ID_LEN 40
 static int getCurFilenameLength(void) {
   int Len;
   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
     return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-        lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize))
+        lprofCurFilename.NumBinaryIds || lprofCurFilename.TmpDir ||
+        lprofCurFilename.MergePoolSize))
     return strlen(lprofCurFilename.FilenamePat);
 
   Len = strlen(lprofCurFilename.FilenamePat) +
         lprofCurFilename.NumPids * (strlen(lprofCurFilename.PidChars) - 2) +
         lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2) +
+        lprofCurFilename.NumBinaryIds * BINARY_ID_LEN +
         (lprofCurFilename.TmpDir ? (strlen(lprofCurFilename.TmpDir) - 1) : 0);
   if (lprofCurFilename.MergePoolSize)
     Len += SIGLEN;
   return Len;
 }
 
+typedef struct lprofBinaryIdsBuffer {
+  char String[BINARY_ID_LEN + 1];
+  int Length;
+} lprofBinaryIdsBuffer;
+
+/* Reads binary ID length and then its data, writes it into lprofBinaryIdsBuffer
+ * in hexadecimal form. */
+static uint32_t binaryIdsStringWriter(ProfDataWriter *This,
+                                      ProfDataIOVec *IOVecs,
+                                      uint32_t NumIOVecs) {
+  if (NumIOVecs < 2 || IOVecs[0].ElmSize != sizeof(uint64_t))
+    return -1;
+  uint64_t BinaryIdLen = *(const uint64_t *)IOVecs[0].Data;
+  if (IOVecs[1].ElmSize != sizeof(uint8_t) || IOVecs[1].NumElm != BinaryIdLen)
+    return -1;
+  const uint8_t *BinaryIdData = (const uint8_t *)IOVecs[1].Data;
+  lprofBinaryIdsBuffer *Data = (lprofBinaryIdsBuffer *)This->WriterCtx;
+  for (uint64_t I = 0; I < BinaryIdLen; I++) {
+    Data->Length +=
+        snprintf(Data->String + Data->Length, BINARY_ID_LEN + 1 - Data->Length,
+                 "%02hhx", BinaryIdData[I]);
+  }
+  return 0;
+}
+
 /* Return the pointer to the current profile file name (after substituting
  * PIDs and Hostnames in filename pattern. \p FilenameBuf is the buffer
  * to store the resulting filename. If no substitution is needed, the
@@ -965,7 +1005,8 @@ static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
     return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-        lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize ||
+        lprofCurFilename.NumBinaryIds || lprofCurFilename.TmpDir ||
+        lprofCurFilename.MergePoolSize ||
         __llvm_profile_is_continuous_mode_enabled())) {
     if (!ForceUseBuf)
       return lprofCurFilename.FilenamePat;
@@ -992,6 +1033,12 @@ static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
         memcpy(FilenameBuf + J, lprofCurFilename.TmpDir, TmpDirLength);
         FilenameBuf[J + TmpDirLength] = DIR_SEPARATOR;
         J += TmpDirLength + 1;
+      } else if (FilenamePat[I] == 'b') {
+        lprofBinaryIdsBuffer Data = {{0}, 0};
+        ProfDataWriter Writer = {binaryIdsStringWriter, &Data};
+        __llvm_write_binary_ids(&Writer);
+        memcpy(FilenameBuf + J, Data.String, Data.Length);
+        J += Data.Length;
       } else {
         if (!getMergePoolSize(FilenamePat, &I))
           continue;
diff --git a/compiler-rt/test/profile/Linux/binary-id-path.c b/compiler-rt/test/profile/Linux/binary-id-path.c
new file mode 100644
index 00000000000000..7dce409d2e8f91
--- /dev/null
+++ b/compiler-rt/test/profile/Linux/binary-id-path.c
@@ -0,0 +1,37 @@
+// REQUIRES: linux
+// RUN: split-file %s %t.dir
+// RUN: %clang_profgen -Wl,--build-id=sha1 -o %t.dir/foo %t.dir/foo.c
+// RUN: %clang_profgen -Wl,--build-id=sha1 -o %t.dir/bar %t.dir/bar.c
+
+// Check that foo and bar have the same signatures.
+// RUN: rm -rf %t.profdir
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.profraw %run %t.dir/foo
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.profraw %run %t.dir/bar 2>&1 | FileCheck %s --check-prefix=MERGE-ERROR
+
+// Check that foo and bar have different binary IDs.
+// RUN: rm -rf %t.profdir %t.profdata
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/foo
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/bar
+// RUN: llvm-profdata merge -o %t.profdata %t.profdir
+// RUN: llvm-profdata show %t.profdata | FileCheck %s --check-prefix=BINARY-ID
+
+// Check fallback to the default name if binary ID is missing.
+// RUN: %clang_profgen -Wl,--build-id=none -o %t.dir/foo %t.dir/foo.c
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/foo 2>&1 | FileCheck %s --check-prefix=MISSING
+
+// MERGE-ERROR: LLVM Profile Error: Profile Merging of file {{.*}}.profraw failed: File exists
+
+// BINARY-ID: Instrumentation level: Front-end
+// BINARY-ID-NEXT: Total functions: 3
+// BINARY-ID-NEXT: Maximum function count: 2
+// BINARY-ID-NEXT: Maximum internal block count: 0
+
+// MISSING: Unable to get binary ID for filename pattern {{.*}}.profraw. Using the default name.
+
+//--- foo.c
+int main(void) { return 0; }
+void foo(void) {}
+
+//--- bar.c
+int main(void) { return 0; }
+void bar(int *a) { *a += 10; }

@llvmbot
Copy link
Member

llvmbot commented Jan 22, 2025

@llvm/pr-subscribers-pgo

Author: Sinkevich Artem (ArtSin)

Changes

Add support for expanding %b in LLVM_PROFILE_FILE to the binary ID (build ID). It can be used with %m to avoid its signature collisions.

This is supported on all platforms where writing binary IDs into profiles is implemented, as the __llvm_write_binary_ids function is used.

Fixes #51560.


Full diff: https://github.com/llvm/llvm-project/pull/123963.diff

4 Files Affected:

  • (modified) clang/docs/SourceBasedCodeCoverage.rst (+5)
  • (modified) clang/docs/UsersManual.rst (+3-2)
  • (modified) compiler-rt/lib/profile/InstrProfilingFile.c (+52-5)
  • (added) compiler-rt/test/profile/Linux/binary-id-path.c (+37)
diff --git a/clang/docs/SourceBasedCodeCoverage.rst b/clang/docs/SourceBasedCodeCoverage.rst
index 73910e134a5891..49bce3b72b45aa 100644
--- a/clang/docs/SourceBasedCodeCoverage.rst
+++ b/clang/docs/SourceBasedCodeCoverage.rst
@@ -94,6 +94,11 @@ directory structure will be created.  Additionally, the following special
   not specified (i.e the pattern is "%m"), it's assumed that ``N = 1``. The
   merge pool specifier can only occur once per filename pattern.
 
+* "%b" expands out to the binary ID (build ID). It can be used with "%Nm" to
+  avoid binary signature collisions. To use it, the program should be compiled
+  with the build ID linker option (``--build-id`` for GNU ld or LLD). Linux,
+  Windows and AIX are supported.
+
 * "%c" expands out to nothing, but enables a mode in which profile counter
   updates are continuously synced to a file. This means that if the
   instrumented program crashes, or is killed by a signal, perfect coverage
diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 260e84910c6f78..bc0ce3f3ccad07 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -2880,7 +2880,8 @@ instrumentation:
    environment variable to specify an alternate file. If non-default file name
    is specified by both the environment variable and the command line option,
    the environment variable takes precedence. The file name pattern specified
-   can include different modifiers: ``%p``, ``%h``, ``%m``, ``%t``, and ``%c``.
+   can include different modifiers: ``%p``, ``%h``, ``%m``, ``%b``, ``%t``, and
+   ``%c``.
 
    Any instance of ``%p`` in that file name will be replaced by the process
    ID, so that you can easily distinguish the profile output from multiple
@@ -2917,7 +2918,7 @@ instrumentation:
      $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
 
    See `this <SourceBasedCodeCoverage.html#running-the-instrumented-program>`_ section
-   about the ``%t``, and ``%c`` modifiers.
+   about the ``%b``, ``%t``, and ``%c`` modifiers.
 
 3. Combine profiles from multiple runs and convert the "raw" profile format to
    the input expected by clang. Use the ``merge`` command of the
diff --git a/compiler-rt/lib/profile/InstrProfilingFile.c b/compiler-rt/lib/profile/InstrProfilingFile.c
index bad4cc71801ec4..01fd314e577f76 100644
--- a/compiler-rt/lib/profile/InstrProfilingFile.c
+++ b/compiler-rt/lib/profile/InstrProfilingFile.c
@@ -77,6 +77,7 @@ typedef struct lprofFilename {
   char Hostname[COMPILER_RT_MAX_HOSTLEN];
   unsigned NumPids;
   unsigned NumHosts;
+  unsigned NumBinaryIds;
   /* When in-process merging is enabled, this parameter specifies
    * the total number of profile data files shared by all the processes
    * spawned from the same binary. By default the value is 1. If merging
@@ -88,8 +89,8 @@ typedef struct lprofFilename {
   ProfileNameSpecifier PNS;
 } lprofFilename;
 
-static lprofFilename lprofCurFilename = {0,   0, 0, {0}, NULL,
-                                         {0}, 0, 0, 0,   PNS_unknown};
+static lprofFilename lprofCurFilename = {0, 0, 0, {0}, NULL,       {0},
+                                         0, 0, 0, 0,   PNS_unknown};
 
 static int ProfileMergeRequested = 0;
 static int getProfileFileSizeForMerging(FILE *ProfileFile,
@@ -790,7 +791,7 @@ static int checkBounds(int Idx, int Strlen) {
  * lprofcurFilename structure. */
 static int parseFilenamePattern(const char *FilenamePat,
                                 unsigned CopyFilenamePat) {
-  int NumPids = 0, NumHosts = 0, I;
+  int NumPids = 0, NumHosts = 0, NumBinaryIds = 0, I;
   char *PidChars = &lprofCurFilename.PidChars[0];
   char *Hostname = &lprofCurFilename.Hostname[0];
   int MergingEnabled = 0;
@@ -855,6 +856,15 @@ static int parseFilenamePattern(const char *FilenamePat,
                     FilenamePat);
           return -1;
         }
+      } else if (FilenamePat[I] == 'b') {
+        if (!NumBinaryIds++) {
+          if (__llvm_write_binary_ids(NULL) <= 0) {
+            PROF_WARN("Unable to get binary ID for filename pattern %s. Using "
+                      "the default name.",
+                      FilenamePat);
+            return -1;
+          }
+        }
       } else if (FilenamePat[I] == 'c') {
         if (__llvm_profile_is_continuous_mode_enabled()) {
           PROF_WARN("%%c specifier can only be specified once in %s.\n",
@@ -887,6 +897,7 @@ static int parseFilenamePattern(const char *FilenamePat,
 
   lprofCurFilename.NumPids = NumPids;
   lprofCurFilename.NumHosts = NumHosts;
+  lprofCurFilename.NumBinaryIds = NumBinaryIds;
   return 0;
 }
 
@@ -934,24 +945,53 @@ static void parseAndSetFilename(const char *FilenamePat,
  * filename with PID and hostname substitutions. */
 /* The length to hold uint64_t followed by 3 digits pool id including '_' */
 #define SIGLEN 24
+/* The length to hold 160-bit hash in hexadecimal form */
+#define BINARY_ID_LEN 40
 static int getCurFilenameLength(void) {
   int Len;
   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
     return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-        lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize))
+        lprofCurFilename.NumBinaryIds || lprofCurFilename.TmpDir ||
+        lprofCurFilename.MergePoolSize))
     return strlen(lprofCurFilename.FilenamePat);
 
   Len = strlen(lprofCurFilename.FilenamePat) +
         lprofCurFilename.NumPids * (strlen(lprofCurFilename.PidChars) - 2) +
         lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2) +
+        lprofCurFilename.NumBinaryIds * BINARY_ID_LEN +
         (lprofCurFilename.TmpDir ? (strlen(lprofCurFilename.TmpDir) - 1) : 0);
   if (lprofCurFilename.MergePoolSize)
     Len += SIGLEN;
   return Len;
 }
 
+typedef struct lprofBinaryIdsBuffer {
+  char String[BINARY_ID_LEN + 1];
+  int Length;
+} lprofBinaryIdsBuffer;
+
+/* Reads binary ID length and then its data, writes it into lprofBinaryIdsBuffer
+ * in hexadecimal form. */
+static uint32_t binaryIdsStringWriter(ProfDataWriter *This,
+                                      ProfDataIOVec *IOVecs,
+                                      uint32_t NumIOVecs) {
+  if (NumIOVecs < 2 || IOVecs[0].ElmSize != sizeof(uint64_t))
+    return -1;
+  uint64_t BinaryIdLen = *(const uint64_t *)IOVecs[0].Data;
+  if (IOVecs[1].ElmSize != sizeof(uint8_t) || IOVecs[1].NumElm != BinaryIdLen)
+    return -1;
+  const uint8_t *BinaryIdData = (const uint8_t *)IOVecs[1].Data;
+  lprofBinaryIdsBuffer *Data = (lprofBinaryIdsBuffer *)This->WriterCtx;
+  for (uint64_t I = 0; I < BinaryIdLen; I++) {
+    Data->Length +=
+        snprintf(Data->String + Data->Length, BINARY_ID_LEN + 1 - Data->Length,
+                 "%02hhx", BinaryIdData[I]);
+  }
+  return 0;
+}
+
 /* Return the pointer to the current profile file name (after substituting
  * PIDs and Hostnames in filename pattern. \p FilenameBuf is the buffer
  * to store the resulting filename. If no substitution is needed, the
@@ -965,7 +1005,8 @@ static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
     return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-        lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize ||
+        lprofCurFilename.NumBinaryIds || lprofCurFilename.TmpDir ||
+        lprofCurFilename.MergePoolSize ||
         __llvm_profile_is_continuous_mode_enabled())) {
     if (!ForceUseBuf)
       return lprofCurFilename.FilenamePat;
@@ -992,6 +1033,12 @@ static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
         memcpy(FilenameBuf + J, lprofCurFilename.TmpDir, TmpDirLength);
         FilenameBuf[J + TmpDirLength] = DIR_SEPARATOR;
         J += TmpDirLength + 1;
+      } else if (FilenamePat[I] == 'b') {
+        lprofBinaryIdsBuffer Data = {{0}, 0};
+        ProfDataWriter Writer = {binaryIdsStringWriter, &Data};
+        __llvm_write_binary_ids(&Writer);
+        memcpy(FilenameBuf + J, Data.String, Data.Length);
+        J += Data.Length;
       } else {
         if (!getMergePoolSize(FilenamePat, &I))
           continue;
diff --git a/compiler-rt/test/profile/Linux/binary-id-path.c b/compiler-rt/test/profile/Linux/binary-id-path.c
new file mode 100644
index 00000000000000..7dce409d2e8f91
--- /dev/null
+++ b/compiler-rt/test/profile/Linux/binary-id-path.c
@@ -0,0 +1,37 @@
+// REQUIRES: linux
+// RUN: split-file %s %t.dir
+// RUN: %clang_profgen -Wl,--build-id=sha1 -o %t.dir/foo %t.dir/foo.c
+// RUN: %clang_profgen -Wl,--build-id=sha1 -o %t.dir/bar %t.dir/bar.c
+
+// Check that foo and bar have the same signatures.
+// RUN: rm -rf %t.profdir
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.profraw %run %t.dir/foo
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.profraw %run %t.dir/bar 2>&1 | FileCheck %s --check-prefix=MERGE-ERROR
+
+// Check that foo and bar have different binary IDs.
+// RUN: rm -rf %t.profdir %t.profdata
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/foo
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/bar
+// RUN: llvm-profdata merge -o %t.profdata %t.profdir
+// RUN: llvm-profdata show %t.profdata | FileCheck %s --check-prefix=BINARY-ID
+
+// Check fallback to the default name if binary ID is missing.
+// RUN: %clang_profgen -Wl,--build-id=none -o %t.dir/foo %t.dir/foo.c
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/foo 2>&1 | FileCheck %s --check-prefix=MISSING
+
+// MERGE-ERROR: LLVM Profile Error: Profile Merging of file {{.*}}.profraw failed: File exists
+
+// BINARY-ID: Instrumentation level: Front-end
+// BINARY-ID-NEXT: Total functions: 3
+// BINARY-ID-NEXT: Maximum function count: 2
+// BINARY-ID-NEXT: Maximum internal block count: 0
+
+// MISSING: Unable to get binary ID for filename pattern {{.*}}.profraw. Using the default name.
+
+//--- foo.c
+int main(void) { return 0; }
+void foo(void) {}
+
+//--- bar.c
+int main(void) { return 0; }
+void bar(int *a) { *a += 10; }

@ArtSin ArtSin force-pushed the add-binary-id-llvm_profile_file branch from cd11146 to e7f3e39 Compare January 23, 2025 05:50
@ArtSin
Copy link
Contributor Author

ArtSin commented Feb 3, 2025

PTAL @ZequanWu @david-xl

@@ -855,6 +856,15 @@ static int parseFilenamePattern(const char *FilenamePat,
FilenamePat);
return -1;
}
} else if (FilenamePat[I] == 'b') {
if (!NumBinaryIds++) {
if (__llvm_write_binary_ids(NULL) <= 0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a code comment to indicate it reads the size of the binary ids.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/foo
// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/bar
// RUN: llvm-profdata merge -o %t.profdata %t.profdir
// RUN: llvm-profdata show %t.profdata | FileCheck %s --check-prefix=BINARY-ID
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check the binary ids after merging?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added check for 2 binary IDs in merged profdata

@ArtSin ArtSin force-pushed the add-binary-id-llvm_profile_file branch from e7f3e39 to 462b70c Compare February 4, 2025 12:28
@ArtSin ArtSin requested a review from david-xl February 5, 2025 07:50
@@ -2917,7 +2918,7 @@ instrumentation:
$ LLVM_PROFILE_FILE="code-%m.profraw" ./code

See `this <SourceBasedCodeCoverage.html#running-the-instrumented-program>`_ section
about the ``%t``, and ``%c`` modifiers.
about the ``%b``, ``%t``, and ``%c`` modifiers.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

better add an %b use example here too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@ArtSin ArtSin force-pushed the add-binary-id-llvm_profile_file branch from 462b70c to 1d1b66d Compare February 5, 2025 11:15
@ArtSin ArtSin requested a review from david-xl February 5, 2025 11:16
@@ -2916,6 +2917,12 @@ instrumentation:

$ LLVM_PROFILE_FILE="code-%m.profraw" ./code

Although rare, binary signatures used by the ``%m`` specifier can have
collisions. In this case, the ``%b`` specifier, which expands to the binary
ID (build ID), can be added. To use it, the program should be compiled with
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
ID (build ID), can be added. To use it, the program should be compiled with
ID (build ID in ELF and COFF), can be added. To use it, the program should be compiled with

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@ArtSin ArtSin force-pushed the add-binary-id-llvm_profile_file branch from 1d1b66d to 3ebeb7b Compare February 6, 2025 09:58
Although rare, binary signatures used by the ``%m`` specifier can have
collisions. In this case, the ``%b`` specifier, which expands to the binary
ID (build ID in ELF and COFF), can be added. To use it, the program should be
compiled with the build ID linker option (``--build-id`` for GNU ld or LLD).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

--build-id for GNU ld or LLD

Also /build-id for lld-link on windows.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added

Add support for expanding `%b` in `LLVM_PROFILE_FILE` to the binary ID
(build ID). It can be used with `%m` to avoid its signature collisions.

This is supported on all platforms where writing binary IDs into profiles
is implemented, as the `__llvm_write_binary_ids` function is used.

Fixes llvm#51560.
@ArtSin ArtSin force-pushed the add-binary-id-llvm_profile_file branch from 3ebeb7b to d14f781 Compare February 6, 2025 19:40
@ArtSin ArtSin requested a review from ZequanWu February 6, 2025 19:41
@ArtSin
Copy link
Contributor Author

ArtSin commented Feb 6, 2025

@ZequanWu can you please merge this?

@ZequanWu ZequanWu merged commit da05341 into llvm:main Feb 6, 2025
5 of 6 checks passed
Copy link

github-actions bot commented Feb 6, 2025

@ArtSin Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@dyung
Copy link
Collaborator

dyung commented Feb 6, 2025

@ArtSin the test you added seems to be failing on at least one build bot https://lab.llvm.org/buildbot/#/builders/174/builds/12664.

Can you take a look and revert if you need time to investigate?

@ZequanWu
Copy link
Contributor

ZequanWu commented Feb 6, 2025

That should be fixed by 8d925a1.

@ArtSin ArtSin deleted the add-binary-id-llvm_profile_file branch February 7, 2025 06:45
@nataraj-hates-MS-for-stealing-github

Hi! I see this patch is already merged, but sine the most testing work is already done, I will still write my report here.

I am original reporter of #51560.
@ArtSin asked me to test the patch.

TL;TR: %b solves my problem, but %p still breaks everything, and I guess that is another bug.

I met problem with coverage while building coverage while running PostgreSQL tests. Tried %p and %m in all combinations in LLVM_PROFILE_FILE and it failed for me with various errors.

How dif I test: I built two branches of llvm: main from https://github.com/llvm/llvm-project.git (f3c4b58) and add-binary-id-llvm_profile_file from https://github.com/ArtSin/llvm-project.git (will refer is as fixed)

I've configured them with command

cmake -S llvm -B build -G "Unix Makefiles" -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra" -DCMAKE_BUILD_TYPE=Debug -DLLVM_ENABLE_RUNTIMES="compiler-rt"  -DLLVM_RUNTIME_TARGETS="x86_64-unknown-linux-gnu"  -DLLVM_BUILTIN_TARGETS="x86_64-unknown-linux-gnu"

and then make -j10 and sudo make install.

Then I've cloned PostgreSQL git clone git://git.postgresql.org/git/postgresql.git -b REL_17_STABLE, configured them with

CC=/usr/local/bin/clang LD=/usr/local/bin/clang CXX=/usr/local/bin/clang++ CFLAGS="-fprofile-instr-generate -fcoverage-mapping -Wl,--build-id " ./configure --enable-debug --enable-cassert --enable-tap-tests

Using main and fiexd clangs. And build them using make -j10 world-bin

Then I tried running tests for both builds using make check-world command with various LLVM_PROFILE_FILE values

main branch

  • running tests with only %m in LLVM_PROFILE_FILE ends with a lot of errors while running tests like :
LLVM Profile Warning: Unable to merge profile data: source profile file is not compatible.                                                                                                                       
LLVM Profile Error: Profile Merging of file /home/nataraj/dev/clang/postgres-clang-main/../profile-clang-main-no-p/15781143787294967941_0.profraw failed: File exists                                            
LLVM Profile Error: Failed to write file "/home/nataraj/dev/clang/postgres-clang-main/../profile-clang-main-no-p/15781143787294967941_0.profraw": File exists

this tests fails.

  • running with both %m and %p in LLVM_PROFILE_FILE creates a lot of files in profile directory (9Gb) and when you try to merge them, you will get:
warning: ../profile-clang-main/167104_786791946722153948_0_.profraw: invalid instrumentation profile data (file header is corrupt)                                                                                
warning: ../profile-clang-main/147831_786791946722153948_0_.profraw: invalid instrumentation profile data (file header is corrupt)                                                                                
warning: ../profile-clang-main/147887_786791946722153948_0_.profraw: invalid instrumentation profile data (file header is corrupt)                                                                                
error: no profile can be merged  

fixed branch

  • If you run tests with %m and %b in LLVM_PROFILE_FILE you will get quite small profile dir (7Mb), this raw profile files will be successfully merged, and you will be able to create html-coverage files from it, with coverage that looks like it was really created while running tests. So the patch works. Hooray!!!!

  • But if have %p to the in LLVM_PROFILE_FILE (with %m and %b or without them) in fixed branch you will still get 9Gb profile directory that can't be merged:

/usr/local/bin/llvm-profdata merge -output=../merged-clang-fix-p-4-cpu.profdata --input-files=`pwd`/../profile-clang-fix-p-4-cpu.list
warning: /home/nataraj/dev/clang/postgres-clang-fix/../profile-clang-fix-p-4-cpu/15196_786791946722153948_0_43a62d1842c2c30141d2cd5140b00e7064205c3d.profraw: invalid instrumentation profile data (file header is corrupt)
warning: /home/nataraj/dev/clang/postgres-clang-fix/../profile-clang-fix-p-4-cpu/34197_786791946722153948_0_43a62d1842c2c30141d2cd5140b00e7064205c3d.profraw: invalid instrumentation profile data (file header is corrupt)
warning: /home/nataraj/dev/clang/postgres-clang-fix/../profile-clang-fix-p-4-cpu/15252_786791946722153948_0_43a62d1842c2c30141d2cd5140b00e7064205c3d.profraw: invalid instrumentation profile data (file header is corrupt)
error: no profile can be merged

Tested it on VMs with (10,4,2 and 1 CPUs) So I can guess problems with %p is not caused by a collision, and should be solved later I guess.

@nataraj-hates-MS-for-stealing-github

Reported %p problem in #126242 issue. In order it will not be lost and forgotten...

Icohedron pushed a commit to Icohedron/llvm-project that referenced this pull request Feb 11, 2025
)

Add support for expanding `%b` in `LLVM_PROFILE_FILE` to the binary ID
(build ID). It can be used with `%m` to avoid its signature collisions.

This is supported on all platforms where writing binary IDs into
profiles is implemented, as the `__llvm_write_binary_ids` function is
used.

Fixes llvm#51560.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang Clang issues not falling into any other category compiler-rt PGO Profile Guided Optimizations
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Binary signature collision for different modules when collecting instrumentation profile
7 participants