Skip to contentSkip to conversation

target/s390x/arch_dump: Simplify memory allocation in s390x_write_elf64_notes()

PATCH New Thomas Huth 1 participant 1 message Feb 15, 2023

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 target/s390x/arch_dump: Simplify memory allocation in s390x_write_elf64_notes()

We are not on a hot path here, so there is no real need for the logic here with the split heap and stack space allocation. Simplify it by always allocating memory from the heap.

---
v2:
- Added the missing "prev_size = note_size" (thanks, Janosch!)
- Use g_free+g_malloc instead of g_realloc to avoid copying old contents

 target/s390x/arch_dump.c | 20 +++++++-------------
 1 file changed, 7 insertions(+), 13 deletions(-)
target/s390x/arch_dump.c +7 -13
index a7c44ba49d..cb98f4894d 100644
@@ -227,25 +227,25 @@ static int s390x_write_elf64_notes(const char *note_name,
                                        DumpState *s,
                                        const NoteFuncDesc *funcs)
 {
-    Note note, *notep;
+    g_autofree Note *notep = NULL;
     const NoteFuncDesc *nf;
-    int note_size, content_size;
+    int note_size, prev_size = 0, content_size;
     int ret = -1;
 
-    assert(strlen(note_name) < sizeof(note.name));
+    assert(strlen(note_name) < sizeof(notep->name));
 
     for (nf = funcs; nf->note_contents_func; nf++) {
-        notep = &note;
         if (nf->pvonly && !s390_is_pv()) {
             continue;
         }
 
         content_size = nf->note_size_func ? nf->note_size_func() : nf->contents_size;
-        note_size = sizeof(note) - sizeof(notep->contents) + content_size;
+        note_size = sizeof(Note) - sizeof(notep->contents) + content_size;
 
-        /* Notes with dynamic sizes need to allocate a note */
-        if (nf->note_size_func) {
+        if (prev_size < note_size) {
+            g_free(notep);
             notep = g_malloc(note_size);
+            prev_size = note_size;
         }
 
         memset(notep, 0, note_size);
@@ -258,15 +258,9 @@ static int s390x_write_elf64_notes(const char *note_name,
         /* Get contents and write them out */
         (*nf->note_contents_func)(notep, cpu, id);
         ret = f(notep, note_size, s);
-
-        if (nf->note_size_func) {
-            g_free(notep);
-        }
-
         if (ret < 0) {
             return -1;
         }
-
     }
 
     return 0;
Signature · 1 line
2.31.1