Insert NOBITS sections (.bss), ignore empty sections
[centaur.git] / src / model / reladd.c
index 782d245375de4064a65c42779249227ac62d49dd..482804c08da5783849cf6799e2392e2635a83c0f 100644 (file)
 #include <assert.h>
 #include <stdlib.h>
+#include <string.h>
 #include <sys/types.h>
-#include <libelf/gelf.h>
 #include <libelfu/libelfu.h>
 
-typedef enum Destsegment {
-  DS_UNKNOWN,
-  DS_TEXT,
-  DS_DATA,
-} Destsegment;
 
-
-static Destsegment destsegment(ElfuScn *ms)
+static int appendData(ElfuScn *ms, void *buf, size_t len)
 {
-  if (!(ms->shdr.sh_flags & SHF_ALLOC)) {
-    return DS_UNKNOWN;
-  }
+  void *newbuf;
+
+  assert(ms);
+  assert(ms->shdr.sh_type != SHT_NOBITS);
+  assert(ms->data.d_buf);
 
-  if (!(ms->shdr.sh_flags & SHF_WRITE)
-      && (ms->shdr.sh_flags & SHF_EXECINSTR)) {
-    return DS_TEXT;
-  } else if ((ms->shdr.sh_flags & SHF_WRITE)
-             && !(ms->shdr.sh_flags & SHF_EXECINSTR)) {
-    return DS_DATA;
+  newbuf = realloc(ms->data.d_buf, ms->shdr.sh_size + len);
+  if (!newbuf) {
+    ELFU_WARN("appendData: malloc() failed for newbuf.\n");
+    return 1;
   }
 
-  return DS_UNKNOWN;
-}
+  ms->data.d_buf = newbuf;
+  memcpy(newbuf + ms->shdr.sh_size, buf, len);
+  ms->shdr.sh_size += len;
+  ms->data.d_size += len;
+  assert(ms->shdr.sh_size == ms->data.d_size);
 
+  return 0;
+}
 
 
-static ElfuScn* insertSection(ElfuElf *me, ElfuElf *mrel, ElfuScn *ms)
+static ElfuScn* insertSection(ElfuElf *me, ElfuElf *mrel, ElfuScn *oldscn)
 {
-  ElfuPhdr *mp;
-  ElfuPhdr *first = NULL;
-  ElfuPhdr *last = NULL;
   ElfuScn *newscn = NULL;
-  ElfuPhdr *injAnchor;
-  int searchForCode = 0;
-
-  switch (destsegment(ms)) {
-    case DS_TEXT:
-      searchForCode = 1;
-    case DS_DATA:
-      newscn = elfu_mCloneScn(ms);
-      if (!newscn) {
-        return NULL;
+  GElf_Addr injAddr;
+  GElf_Off injOffset;
+  ElfuPhdr *injPhdr;
+
+  if (oldscn->shdr.sh_flags & SHF_ALLOC) {
+    newscn = elfu_mCloneScn(oldscn);
+    if (!newscn) {
+      return NULL;
+    }
+
+    if (newscn->shdr.sh_type == SHT_NOBITS) {
+      /* Expand this to SHT_PROGBITS, then insert as such. */
+
+      assert(!newscn->data.d_buf);
+
+      newscn->data.d_buf = malloc(newscn->shdr.sh_size);
+      if (!newscn->data.d_buf) {
+        goto ERROR;
       }
+      newscn->data.d_size = newscn->shdr.sh_size;
+      newscn->shdr.sh_type = SHT_PROGBITS;
+    }
 
-      /* Find first and last LOAD PHDRs. */
-      CIRCLEQ_FOREACH(mp, &me->phdrList, elem) {
-        if (mp->phdr.p_type != PT_LOAD) {
-          continue;
-        }
+    injAddr = elfu_mLayoutGetSpaceInPhdr(me,
+                                         newscn->shdr.sh_size,
+                                         newscn->shdr.sh_addralign,
+                                         newscn->shdr.sh_flags & SHF_WRITE,
+                                         newscn->shdr.sh_flags & SHF_EXECINSTR,
+                                         &injPhdr);
 
-        if (!first || mp->phdr.p_vaddr < first->phdr.p_vaddr) {
-          first = mp;
-        }
-        if (!last || mp->phdr.p_vaddr > last->phdr.p_vaddr) {
-          /* No need to check p_memsz as segments may not overlap in memory. */
-          last = mp;
+    if (!injPhdr) {
+      ELFU_WARN("insertSection: Could not find a place to insert section.\n");
+      goto ERROR;
+    }
+
+    ELFU_INFO("Inserting %s at address 0x%jx...\n",
+              elfu_mScnName(mrel, oldscn),
+              injAddr);
+
+    injOffset = injAddr - injPhdr->phdr.p_vaddr + injPhdr->phdr.p_offset;
+
+    newscn->shdr.sh_addr = injAddr;
+    newscn->shdr.sh_offset = injOffset;
+
+    if (CIRCLEQ_EMPTY(&injPhdr->childScnList)
+        || CIRCLEQ_LAST(&injPhdr->childScnList)->shdr.sh_offset < injOffset) {
+      CIRCLEQ_INSERT_TAIL(&injPhdr->childScnList, newscn, elemChildScn);
+    } else {
+      ElfuScn *ms;
+      CIRCLEQ_FOREACH(ms, &injPhdr->childScnList, elemChildScn) {
+        if (injOffset < ms->shdr.sh_offset) {
+          CIRCLEQ_INSERT_BEFORE(&injPhdr->childScnList, ms, newscn, elemChildScn);
+          break;
         }
       }
+    }
 
-      if (searchForCode) {
-        if ((first->phdr.p_flags & PF_X) && !(first->phdr.p_flags & PF_W)) {
-          injAnchor = first;
-        } else if ((last->phdr.p_flags & PF_X) && !(last->phdr.p_flags & PF_W)) {
-          injAnchor = last;
-        } else {
-          injAnchor = NULL;
-        }
-      } else {
-        if ((first->phdr.p_flags & PF_W) && !(first->phdr.p_flags & PF_X)) {
-          injAnchor = first;
-        } else if ((last->phdr.p_flags & PF_W) && !(last->phdr.p_flags & PF_X)) {
-          injAnchor = last;
-        } else {
-          injAnchor = NULL;
-        }
+
+    /* Inject name */
+    if (me->shstrtab) {
+      char *newname;
+      size_t newnamelen;
+
+      newnamelen = strlen("reladd") + 1;
+      if (elfu_mScnName(mrel, oldscn)) {
+        newnamelen += strlen(elfu_mScnName(mrel, oldscn));
       }
 
-      if (!injAnchor) {
-        ELFU_WARN("insertSection: Could not find injection anchor.\n"
-                  "               It has to be the first or last segment in the memory image.\n");
+      newname = malloc(newnamelen);
+      strcpy(newname, "reladd");
+      strcat(newname, elfu_mScnName(mrel, oldscn));
+
+      if (!newname) {
+        ELFU_WARN("insertSection: malloc() failed for newname. Leaving section name empty.\n");
+        newscn->shdr.sh_name = 0;
       } else {
-        GElf_Off injOffset;
-
-        /* If the anchor is first or last, insert before or after */
-        if (injAnchor == first) {
-          /* Find first section and inject before it */
-          ElfuScn *firstScn = elfu_mScnFirstInSegment(me, injAnchor);
-          if (!firstScn) {
-            ELFU_WARN("insertSection: mScnFirstInSegment failed.\n");
-
-            // TODO: Error handling
-          } else {
-            injOffset = firstScn->shdr.sh_offset;
-
-            /* Make space */
-            elfu_mInsertSpaceBefore(me, injOffset, ms->shdr.sh_size);
-
-            /* Update memory offset */
-            newscn->shdr.sh_addr = injAnchor->phdr.p_vaddr;
-
-            /* Insert into chain of sections */
-            elfu_mInsertScnInChainBefore(me, firstScn, newscn);
-          }
-        } else {
-          /* Find last section and inject after it */
-          ElfuScn *lastScn = elfu_mScnLastInSegment(me, injAnchor);
-          if (!lastScn) {
-            ELFU_WARN("insertSection: mScnLastInSegment failed.\n");
-
-            // TODO: Error handling
-          } else {
-            injOffset = lastScn->shdr.sh_offset + elfu_gScnSizeFile(&lastScn->shdr);
-
-            /* Expand NOBITS sections at injection site, if any. */
-            elfu_mExpandNobits(me, injOffset);
-
-            /* Recalculate injOffset in case we expanded a NOBITS section */
-            lastScn = elfu_mScnLastInSegment(me, injAnchor);
-            injOffset = lastScn->shdr.sh_offset + elfu_gScnSizeFile(&lastScn->shdr);
-
-            /* Make space */
-            elfu_mInsertSpaceAfter(me, injOffset, ms->shdr.sh_size);
-
-            /* Update memory offset */
-            newscn->shdr.sh_addr = injAnchor->phdr.p_vaddr + (injOffset - injAnchor->phdr.p_offset);
-
-            /* Insert into chain of sections */
-            elfu_mInsertScnInChainAfter(me, lastScn, newscn);
-          }
+        size_t offset = me->shstrtab->shdr.sh_size;
+
+        if (!appendData(me->shstrtab, newname, newnamelen)) {
+          newscn->shdr.sh_name = offset;
         }
 
-        /* Update file offset in new section BEFORE we do anything else */
-        newscn->shdr.sh_offset = injOffset;
+        free(newname);
+      }
+    }
 
-        /* Inject name */
-        // TODO
-        newscn->shdr.sh_name = 0;
+    return newscn;
+  } else {
+      ELFU_WARN("insertSection: Skipping non-memory section %s (type %d flags %jd).\n",
+                elfu_mScnName(mrel, oldscn),
+                oldscn->shdr.sh_type,
+                oldscn->shdr.sh_flags);
+      goto ERROR;
+  }
 
-        // TODO: Relocate
+  ERROR:
+  if (newscn) {
+    // TODO: Destroy newscn
+  }
+  return NULL;
+}
 
-        return newscn;
+
+static void* subScnAdd1(ElfuElf *mrel, ElfuScn *ms, void *aux1, void *aux2)
+{
+  (void)aux2;
+  ElfuElf *me = (ElfuElf*)aux1;
+
+  ElfuScn *newscn;
+
+  switch(ms->shdr.sh_type) {
+    case SHT_PROGBITS: /* 1 */
+    case SHT_NOBITS: /* 8 */
+      /* Ignore empty sections */
+      if (ms->shdr.sh_size == 0) {
+        break;
+      }
+
+      /* Find a place where it belongs and shove it in. */
+      newscn = insertSection(me, mrel, ms);
+      if (!newscn) {
+        ELFU_WARN("mReladd: Could not insert section %s (type %d), skipping.\n",
+                  elfu_mScnName(mrel, ms),
+                  ms->shdr.sh_type);
       }
       break;
+  }
 
-    case DS_UNKNOWN:
-      ELFU_WARN("insertSection: Don't know where to insert ' %s with flags %jd (type %d).\n",
-                elfu_mScnName(mrel, ms),
-                ms->shdr.sh_flags,
-                ms->shdr.sh_type);
+  return NULL;
+}
+
+
+static void* subScnAdd2(ElfuElf *mrel, ElfuScn *ms, void *aux1, void *aux2)
+{
+  (void)aux2;
+  ElfuElf *me = (ElfuElf*)aux1;
+  (void)me;
+
+  switch(ms->shdr.sh_type) {
+    case SHT_NULL: /* 0 */
+    case SHT_PROGBITS: /* 1 */
+    case SHT_NOBITS: /* 8 */
+      break;
+
+
+    case SHT_REL: /* 9 */
+      /* Relocate. */
+      elfu_mRelocate32(me, elfu_mScnByOldscn(me, ms->infoptr), ms);
+      break;
+
+    case SHT_RELA: /* 4 */
+      // TODO: Needs a parser
+      //elfu_mRelocate(elfu_mScnByOldscn(me, ms->infoptr), ms);
+
+    case SHT_SYMTAB: /* 2 */
+      /* Merge with the existing table. Take care of string tables also. */
+
+    case SHT_STRTAB: /* 3 */
+      /* May have to be merged with the existing string table for
+       * the symbol table. */
+
+    /* The next section types either do not occur in .o files, or are
+     * not strictly necessary to process here. */
+    case SHT_NOTE: /* 7 */
+    case SHT_HASH: /* 5 */
+    case SHT_DYNAMIC: /* 6 */
+    case SHT_SHLIB: /* 10 */
+    case SHT_DYNSYM: /* 11 */
+    case SHT_INIT_ARRAY: /* 14 */
+    case SHT_FINI_ARRAY: /* 15 */
+    case SHT_PREINIT_ARRAY: /* 16 */
+    case SHT_GROUP: /* 17 */
+    case SHT_SYMTAB_SHNDX: /* 18 */
+    case SHT_NUM: /* 19 */
     default:
-      ELFU_WARN("insertSection: Skipping section %s with flags %jd (type %d).\n",
+      ELFU_WARN("mReladd: Skipping section %s (type %d).\n",
                 elfu_mScnName(mrel, ms),
-                ms->shdr.sh_flags,
                 ms->shdr.sh_type);
-      return NULL;
   }
 
-  if (newscn) {
-    // TODO: Destroy newscn
-  }
   return NULL;
 }
 
 
-
 void elfu_mReladd(ElfuElf *me, ElfuElf *mrel)
 {
-  ElfuScn *ms;
-
   assert(me);
   assert(mrel);
 
-
   /* For each section in object file, guess how to insert it */
-  CIRCLEQ_FOREACH(ms, &mrel->scnList, elem) {
-    ElfuScn *newscn;
-
-    switch(ms->shdr.sh_type) {
-      case SHT_NULL: /* 0 */
-        continue;
-
-      case SHT_PROGBITS: /* 1 */
-        /* Find a place where it belongs and shove it in. */
-        newscn = insertSection(me, mrel, ms);
-        if (!newscn) {
-          ELFU_WARN("mReladd: Could not insert section %s (type %d), skipping.\n",
-                    elfu_mScnName(mrel, ms),
-                    ms->shdr.sh_type);
-        }
-        break;
+  elfu_mScnForall(mrel, subScnAdd1, me, NULL);
 
-      case SHT_SYMTAB: /* 2 */
-      case SHT_DYNSYM: /* 11 */
-        /* Merge with the existing table. Take care of string tables also. */
-
-      case SHT_STRTAB: /* 3 */
-        /* May have to be merged with the existing string table for
-         * the symbol table. */
-
-      case SHT_RELA: /* 4 */
-      case SHT_REL: /* 9 */
-        /* Possibly append this in memory to the section model
-         * that it describes. */
-
-      case SHT_NOBITS: /* 8 */
-        /* Expand this to SHT_PROGBITS, then insert as such. */
-
-      case SHT_HASH: /* 5 */
-      case SHT_DYNAMIC: /* 6 */
-      case SHT_SHLIB: /* 10 */
-      case SHT_SYMTAB_SHNDX: /* 18 */
-
-      /* Don't care about the next ones yet. I've never seen
-       * them and they can be implemented when necessary. */
-      case SHT_NOTE: /* 7 */
-      case SHT_INIT_ARRAY: /* 14 */
-      case SHT_FINI_ARRAY: /* 15 */
-      case SHT_PREINIT_ARRAY: /* 16 */
-      case SHT_GROUP: /* 17 */
-      case SHT_NUM: /* 19 */
-      default:
-        ELFU_WARN("mReladd: Skipping section %s (type %d).\n",
-                  elfu_mScnName(mrel, ms),
-                  ms->shdr.sh_type);
-    }
-  }
+  /* Do relocations and other stuff */
+  elfu_mScnForall(mrel, subScnAdd2, me, NULL);
+
+  /* Re-layout to accommodate new contents */
+  elfu_mLayoutAuto(me);
 }