@@ -194,33 +194,41 @@ static int WriteBinaryIds(ProfDataWriter *Writer, const ElfW(Nhdr) * Note,
194194 */
195195COMPILER_RT_VISIBILITY int __llvm_write_binary_ids (ProfDataWriter * Writer ) {
196196 extern const ElfW (Ehdr ) __ehdr_start __attribute__((visibility ("hidden" )));
197- extern ElfW (Dyn ) _DYNAMIC [] __attribute__((weak , visibility ("hidden" )));
198-
199197 const ElfW (Ehdr ) * ElfHeader = & __ehdr_start ;
200198 const ElfW (Phdr ) * ProgramHeader =
201199 (const ElfW (Phdr ) * )((uintptr_t )ElfHeader + ElfHeader -> e_phoff );
202200
203- /* Compute the added base address in case of position-independent code. */
204- uintptr_t Base = 0 ;
205- for (uint32_t I = 0 ; I < ElfHeader -> e_phnum ; I ++ ) {
206- if (ProgramHeader [I ].p_type == PT_PHDR )
207- Base = (uintptr_t )ProgramHeader - ProgramHeader [I ].p_vaddr ;
208- if (ProgramHeader [I ].p_type == PT_DYNAMIC && _DYNAMIC )
209- Base = (uintptr_t )_DYNAMIC - ProgramHeader [I ].p_vaddr ;
210- }
211-
212201 int TotalBinaryIdsSize = 0 ;
202+ uint32_t I ;
213203 /* Iterate through entries in the program header. */
214- for (uint32_t I = 0 ; I < ElfHeader -> e_phnum ; I ++ ) {
204+ for (I = 0 ; I < ElfHeader -> e_phnum ; I ++ ) {
215205 /* Look for the notes segment in program header entries. */
216206 if (ProgramHeader [I ].p_type != PT_NOTE )
217207 continue ;
218208
219209 /* There can be multiple notes segment, and examine each of them. */
220- const ElfW (Nhdr ) * Note =
221- (const ElfW (Nhdr ) * )(Base + ProgramHeader [I ].p_vaddr );
222- const ElfW (Nhdr ) * NotesEnd =
223- (const ElfW (Nhdr ) * )((const char * )(Note ) + ProgramHeader [I ].p_memsz );
210+ const ElfW (Nhdr ) * Note ;
211+ const ElfW (Nhdr ) * NotesEnd ;
212+ /*
213+ * When examining notes in file, use p_offset, which is the offset within
214+ * the elf file, to find the start of notes.
215+ */
216+ if (ProgramHeader [I ].p_memsz == 0 ||
217+ ProgramHeader [I ].p_memsz == ProgramHeader [I ].p_filesz ) {
218+ Note = (const ElfW (Nhdr ) * )((uintptr_t )ElfHeader +
219+ ProgramHeader [I ].p_offset );
220+ NotesEnd = (const ElfW (Nhdr ) * )((const char * )(Note ) +
221+ ProgramHeader [I ].p_filesz );
222+ } else {
223+ /*
224+ * When examining notes in memory, use p_vaddr, which is the address of
225+ * section after loaded to memory, to find the start of notes.
226+ */
227+ Note =
228+ (const ElfW (Nhdr ) * )((uintptr_t )ElfHeader + ProgramHeader [I ].p_vaddr );
229+ NotesEnd =
230+ (const ElfW (Nhdr ) * )((const char * )(Note ) + ProgramHeader [I ].p_memsz );
231+ }
224232
225233 int BinaryIdsSize = WriteBinaryIds (Writer , Note , NotesEnd );
226234 if (TotalBinaryIdsSize == -1 )
0 commit comments