Skip to contentSkip to conversation

x86: ELF note handling

PATCH New Jan Beulich 1 participant 4 messages Jul 7

lore
Share & tools
lore
#0 lore raw

v2 cover x86: ELF note handling

This v2 submission primarily serves as a reminder that the sole original patch (now patch 2 in this series) is still pending. As there was no feedback in almost a year, I further did the other change that was mentioned there (patch 3 here). In the course of doing so, I further found it desirable to do some up front tidying - patch 1.

1: x86/mkelf32: tidy what is written out
2: ELF: correct .note.* alignment handling
3: x86/mkelf32: re-write ELF notes

Jan

#1 lore raw

PATCH v2 1/3 x86/mkelf32: tidy what is written out

First, replace an open-coded literal number by an expression.

Then adjust tail padding: Don't write up to 4 bytes (and at least one), but truly only pad to the next 4-byte boundary. And pad with zeroes, not with whatever is left in buffer[].

Finally drop the explicit nul character in out_shstrtab_extra[] - the one which is being appended anyway will do fine.

---
v2: New.

xen/arch/x86/boot/mkelf32.c +13 -5
@@ -68,7 +68,7 @@ static Elf32_Phdr note_phdr = {
 
 static uint8_t out_shstrtab[] = "\0.text\0.shstrtab";
 /* If num_phdrs >= 2, we need to tack the .note. */
-static uint8_t out_shstrtab_extra[] = ".note\0";
+static uint8_t out_shstrtab_extra[] = ".note";
 
 static Elf32_Shdr out_shdr[] = {
     { 0 },
@@ -97,11 +97,11 @@ static Elf32_Shdr out_shdr[] = {
 };
 
 /*
- * The 17 points to the '.note' in the out_shstrtab and out_shstrtab_extra
+ * .sh_name points to the '.note' in the out_shstrtab and out_shstrtab_extra
  * laid out in the file.
  */
 static Elf32_Shdr out_shdr_note = {
-      17,                                    /* sh_name */
+      sizeof(out_shstrtab),                  /* sh_name */
       SHT_NOTE,                              /* sh_type */
       0,                                     /* sh_flags */
       DYNAMICALLY_FILLED,                    /* sh_addr */
@@ -468,13 +468,21 @@ int main(int argc, char **argv)
         do_write(outfd, out_shstrtab, sizeof(out_shstrtab));
         /* Our .note */
         do_write(outfd, out_shstrtab_extra, sizeof(out_shstrtab_extra));
-        do_write(outfd, buffer, 4-((sizeof(out_shstrtab)+sizeof(out_shstrtab_extra)+dat_siz)&3));
+        bytes = sizeof(out_shstrtab) + sizeof(out_shstrtab_extra) + dat_siz;
     }
     else
     {
         do_write(outfd, out_shstrtab, sizeof(out_shstrtab));
-        do_write(outfd, buffer, 4-((sizeof(out_shstrtab)+dat_siz)&3));
+        bytes = sizeof(out_shstrtab) + dat_siz;
     }
+
+    /* Pad to a multiple of 4 bytes, whatever that's good for. */
+    if ( bytes & 3 )
+    {
+        memset(buffer, 0, 4);
+        do_write(outfd, buffer, 4 - (bytes & 3));
+    }
+
     close(infd);
     close(outfd);
 
#2 lore raw

PATCH v2 2/3 ELF: correct .note.* alignment handling

In reply to Jan Beulich

The present uniform 4-byte alignment hasn't been right for, I think, a very long time (albeit not forever). As per e.g. [1], 8-byte alignment is required in 64-bit ELF containers (and assembler-generated .note.gnu.property, for example, is 8-byte aligned, while - oddly - linker-generated .note.gnu.build-id is only 4-byte aligned [2]). Sadly libelf is also affected, and hence going strictly by the spec would break kernels also getting it wrong (e.g. Linux). Apply the same heuristic as GNU readelf does: If section alignment is 4 or less, assume only 4-byte padding.

[1] https://refspecs.linuxfoundation.org/elf/gabi4+/ch5.pheader.html#note_section
[2] https://sourceware.org/bugzilla/show_bug.cgi?id=33259

---
Arguably the spec text is ambiguous as to the width of namesz, descsz, and type: They could well be meant to be 8-byte quantities in 64-bit ELF as per "each entry is an array of 8-byte words". Yet with everyone using 4-byte fields, that's the de-facto standard now anyway.

xen/arch/x86/include/asm/asm_defns.h +3 -3
@@ -398,14 +398,14 @@ static always_inline void stac(void)
 
 #define ELFNOTE(name, type, desc)           \
     .pushsection .note.name, "a", @note   ; \
-    .p2align 2                            ; \
+    .balign BYTES_PER_LONG                ; \
     .long 2f - 1f       /* namesz */      ; \
     .long 4f - 3f       /* descsz */      ; \
     .long type          /* type   */      ; \
 1:  .asciz #name        /* name   */      ; \
-2:  .p2align 2                            ; \
+2:  .balign BYTES_PER_LONG                ; \
 3:  desc                /* desc   */      ; \
-4:  .p2align 2                            ; \
+4:  .balign BYTES_PER_LONG                ; \
     .popsection
 
 #define ASM_CONSTANT(name, value)                \
xen/common/libelf/libelf-dominfo.c +13 -0
@@ -583,6 +583,8 @@ elf_errorstatus elf_xen_parse(struct elf
     count = elf_phdr_count(elf);
     for ( i = 0; i < count; i++ )
     {
+        unsigned orig_align = elf->note_align;
+
         phdr = elf_phdr_by_index(elf, i);
         if ( !elf_access_ok(elf, ELF_HANDLE_PTRVAL(phdr), 1) )
             /* input has an insane program header count field */
@@ -597,10 +599,15 @@ elf_errorstatus elf_xen_parse(struct elf
         if (elf_uval(elf, phdr, p_offset) == 0)
              continue;
 
+        elf->note_align = elf_uval(elf, phdr, p_align);
+
         more_notes = elf_xen_parse_notes(elf, parms,
                                  elf_segment_start(elf, phdr),
                                  elf_segment_end(elf, phdr),
                                  &total_note_count);
+
+        elf->note_align = orig_align;
+
         if ( more_notes == ELF_NOTE_INVALID )
             return -1;
 
@@ -616,6 +623,8 @@ elf_errorstatus elf_xen_parse(struct elf
         count = elf_shdr_count(elf);
         for ( i = 1; i < count; i++ )
         {
+            unsigned orig_align = elf->note_align;
+
             shdr = elf_shdr_by_index(elf, i);
             if ( !elf_access_ok(elf, ELF_HANDLE_PTRVAL(shdr), 1) )
                 /* input has an insane section header count field */
@@ -624,11 +633,15 @@ elf_errorstatus elf_xen_parse(struct elf
             if ( elf_uval(elf, shdr, sh_type) != SHT_NOTE )
                 continue;
 
+            elf->note_align = elf_uval(elf, shdr, sh_addralign);
+
             more_notes = elf_xen_parse_notes(elf, parms,
                                      elf_section_start(elf, shdr),
                                      elf_section_end(elf, shdr),
                                      &total_note_count);
 
+            elf->note_align = orig_align;
+
             if ( more_notes == ELF_NOTE_INVALID )
                 return -1;
 
xen/common/libelf/libelf-loader.c +3 -0
@@ -72,6 +72,9 @@ elf_errorstatus elf_init(struct elf_bina
         return -1;
     }
 
+    /* Record default note alignment, as per EI_CLASS. */
+    elf->note_align = elf_64bit(elf) ? 8 : 4;
+
     /* Find section string table. */
     section = elf_uval(elf, elf->ehdr, e_shstrndx);
     shdr = elf_shdr_by_index(elf, section);
xen/common/libelf/libelf-tools.c +20 -8
@@ -288,6 +288,20 @@ ELF_HANDLE_DECL(elf_sym) elf_sym_by_inde
     return sym;
 }
 
+/*
+ * Notes are special: Formally for a long time the spec has demanded that
+ * 64-bit ELF would have 8-byte padding at respective places.  However, many
+ * producers were never updated, so apply a heuristic GNU readelf also applies:
+ * Take section (or segment) alignment into consideration.  When alignment is 4
+ * or less, assume only 4-byte padding.
+ */
+static unsigned elf_note_round_up(const struct elf_binary *elf, unsigned pos)
+{
+    unsigned align = elf_32bit(elf) || elf->note_align <= 4 ? 4 : 8;
+
+    return (pos + align - 1) & ~(align - 1);
+}
+
 const char *elf_note_name(struct elf_binary *elf, ELF_HANDLE_DECL(elf_note) note)
 {
     return elf_strval(elf, ELF_HANDLE_PTRVAL(note) + elf_size(elf, note));
@@ -295,9 +309,9 @@ const char *elf_note_name(struct elf_bin
 
 elf_ptrval elf_note_desc(struct elf_binary *elf, ELF_HANDLE_DECL(elf_note) note)
 {
-    unsigned namesz = (elf_uval(elf, note, namesz) + 3) & ~3;
-
-    return ELF_HANDLE_PTRVAL(note) + elf_size(elf, note) + namesz;
+    return ELF_HANDLE_PTRVAL(note) +
+           elf_note_round_up(elf,
+                             elf_size(elf, note) + elf_uval(elf, note, namesz));
 }
 
 uint64_t elf_note_numeric(struct elf_binary *elf, ELF_HANDLE_DECL(elf_note) note)
@@ -339,11 +353,9 @@ uint64_t elf_note_numeric_array(struct e
 
 ELF_HANDLE_DECL(elf_note) elf_note_next(struct elf_binary *elf, ELF_HANDLE_DECL(elf_note) note)
 {
-    unsigned namesz = (elf_uval(elf, note, namesz) + 3) & ~3;
-    unsigned descsz = (elf_uval(elf, note, descsz) + 3) & ~3;
-
-    elf_ptrval ptrval = ELF_HANDLE_PTRVAL(note)
-        + elf_size(elf, note) + namesz + descsz;
+    elf_ptrval ptrval =
+        elf_note_desc(elf, note) +
+        elf_note_round_up(elf, elf_uval(elf, note, descsz));
 
     if ( ( ptrval <= ELF_HANDLE_PTRVAL(note) || /* wrapped or stuck */
            !elf_access_ok(elf, ELF_HANDLE_PTRVAL(note), 1) ) )
xen/include/xen/elf.h +1 -1
@@ -29,7 +29,7 @@
 
 #include <xen/elfstructs.h>
 
-#define ELFNOTE_ALIGN(_n_) (((_n_)+3)&~3)
+#define ELFNOTE_ALIGN(_n_) ROUNDUP(_n_, BYTES_PER_LONG)
 #define ELFNOTE_NAME(_n_) ((char*)(_n_) + sizeof(*(_n_)))
 #define ELFNOTE_DESC(_n_) (ELFNOTE_NAME(_n_) + ELFNOTE_ALIGN((_n_)->namesz))
 #define ELFNOTE_NEXT(_n_) ((Elf_Note *)(ELFNOTE_DESC(_n_) + ELFNOTE_ALIGN((_n_)->descsz)))
xen/include/xen/libelf.h +6 -0
@@ -181,6 +181,12 @@ struct elf_binary {
     char class;
     char data;
 
+    /*
+     * Note alignment is defaulted from EI_CLASS, but overridden by
+     * segment / section alignment.
+     */
+    unsigned note_align;
+
     ELF_HANDLE_DECL(elf_ehdr) ehdr;
     elf_ptrval sec_strtab;
     ELF_HANDLE_DECL(elf_shdr) sym_tab;
#3 lore raw

PATCH v2 3/3 x86/mkelf32: re-write ELF notes

In reply to Jan Beulich

64-bit ELF notes generally (sadly with exceptions) are padded to 8-byte boundaries, whereas 32-bit ELF notes are padded to 4-byte ones. The excess padding makes it impossible for tools like objdump to properly deal with these notes.

---
Is there a need to further generalize or tighten anything?
---
v2: New.

xen/arch/x86/boot/mkelf32.c +95 -5
@@ -8,6 +8,7 @@
  */
 
 #include <errno.h>
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -256,6 +257,8 @@ int main(int argc, char **argv)
     char       buffer[1024] = {};
     int        bytes, todo, i = 1;
     int        num_phdrs = 1;
+    void      *notes32 = NULL;
+    unsigned int note_sz32 = 0;
 
     Elf32_Ehdr in32_ehdr;
 
@@ -359,8 +362,6 @@ int main(int argc, char **argv)
         do_read(infd, &in64_phdr, sizeof(in64_phdr));
         endianadjust_phdr64(&in64_phdr);
 
-        (void)lseek(infd, offset, SEEK_SET);
-
         note_sz = in64_phdr.p_memsz;
         note_base = in64_phdr.p_vaddr - note_base;
 
@@ -373,6 +374,84 @@ int main(int argc, char **argv)
                     offset, offset + dat_siz);
             return 1;
         }
+
+        note_sz32 = note_sz;
+
+        /* Convert 8-byte padded notes to 4-byte padded ones. */
+        if ( in64_phdr.p_align == 8 )
+        {
+            Elf64_Note *notes64 = malloc(note_sz);
+
+            notes32 = malloc(note_sz);
+            if ( notes64 && notes32 )
+            {
+                unsigned int left = note_sz;
+                void *ptr32 = notes32;
+
+                lseek(infd, in64_phdr.p_offset, SEEK_SET);
+                do_read(infd, notes64, note_sz);
+
+                for ( bool start = true; left > sizeof(*notes64); )
+                {
+                    unsigned int size;
+
+                    if ( start && !notes64->namesz )
+                    {
+                        /* Padding. */
+                        notes64 = (void *)(&notes64->namesz + 1);
+                        left -= sizeof(notes64->namesz);
+                        start = false;
+                        continue;
+                    }
+
+                    /*
+                     * The note descriptor may start at either the next 4- or
+                     * 8-byte boundary.  See e.g.
+                     * https://sourceware.org/bugzilla/show_bug.cgi?id=33259.
+                     * For the notes we have actively in use at the time of
+                     * writing, rounding to the next 4-byte boundary is enough
+                     * (and in fact is already excessive: "GNU" and "Xen" as
+                     * note names both satisfy the 8-byte alignment without
+                     * extra effort).
+                     *
+                     * The similar ->descsz aspect is covered by the check
+                     * above.
+                     */
+                    size = ROUNDUP(sizeof(*notes64) + notes64->namesz, 4) +
+                           ROUNDUP(notes64->descsz, 4);
+                    if ( left < size )
+                    {
+                        fprintf(stderr,
+                                "Warning: ELF note overrunning segment (%u bytes left, %u bytes claimed)\n",
+                                left, size);
+                        left = 0;
+                        break;
+                    }
+
+                    /* Leverage Elf{32,64}_Note actually having same layout. */
+                    memcpy(ptr32, notes64, size);
+
+                    notes64 = (void *)notes64 + size;
+                    ptr32 += size;
+                    left -= size;
+                    start = true;
+                }
+
+                if ( left )
+                    fprintf(stderr, "Warning: %u trailing bytes of ELF notes\n",
+                            left);
+
+                note_sz32 = ptr32 - notes32;
+                memset(ptr32, 0, note_sz - note_sz32);
+            }
+            else
+                fprintf(stderr,
+                        "Warning: Not enough memory to re-write %"PRIu32" bytes of ELF notes\n",
+                        note_sz);
+        }
+
+        (void)lseek(infd, offset, SEEK_SET);
+
         /* Gets us the absolute offset within the .text section. */
         offset = in64_phdr.p_offset - offset;
     }
@@ -405,8 +484,8 @@ int main(int argc, char **argv)
         /* Fill out the PT_NOTE program header. */
         note_phdr.p_vaddr   = note_base;
         note_phdr.p_paddr   = note_base;
-        note_phdr.p_filesz  = note_sz;
-        note_phdr.p_memsz   = note_sz;
+        note_phdr.p_filesz  = note_sz32;
+        note_phdr.p_memsz   = note_sz32;
         note_phdr.p_offset  = RAW_OFFSET + offset;
 
         /* Tack on the .note\0 */
@@ -415,7 +494,7 @@ int main(int argc, char **argv)
         out_shdr[2].sh_offset += sizeof(out_shdr_note);
 
         /* Fill out the .note section. */
-        out_shdr_note.sh_size = note_sz;
+        out_shdr_note.sh_size = note_sz32;
         out_shdr_note.sh_addr = note_base;
         out_shdr_note.sh_offset = RAW_OFFSET + offset;
     }
@@ -483,6 +562,17 @@ int main(int argc, char **argv)
         do_write(outfd, buffer, 4 - (bytes & 3));
     }
 
+    if ( notes32 )
+    {
+        lseek(outfd, note_phdr.p_offset, SEEK_SET);
+
+        /*
+         * While we use note_sz32 above, overwrite the full original contents,
+         * to not leave confusing rubbish there.
+         */
+        do_write(outfd, notes32, note_sz);
+    }
+
     close(infd);
     close(outfd);