Squashed 'third_party/elfutils/' content from commit 555e15e

Change-Id: I61cde98949e47e5c8c09c33260de17f30921be79
git-subtree-dir: third_party/elfutils
git-subtree-split: 555e15ebe8bf1eb33d00747173cfc80cc65648a4
diff --git a/libdwelf/ChangeLog b/libdwelf/ChangeLog
new file mode 100644
index 0000000..a332655
--- /dev/null
+++ b/libdwelf/ChangeLog
@@ -0,0 +1,59 @@
+2015-10-11  Akihiko Odaki  <akihiko.odaki.4i@stu.hosei.ac.jp>
+
+	* dwelf_strtab.c: Remove sys/param.h include.
+	(MIN): Remove definition.
+
+2016-07-08  Mark Wielaard  <mjw@redhat.com>
+
+	* Makefile.am (libdwelf_a_SOURCES): Add dwelf_strtab.c.
+	* dwelf_strtab.c: New file.
+	* libdwelf.h (Dwelf_Strtab): New typedef.
+	(Dwelf_Strent): Likewise.
+	(dwelf_strtab_init): New function.
+	(dwelf_strtab_add): Likewise.
+	(dwelf_strtab_add_len): Likewise.
+	(dwelf_strtab_finalize): Likewise.
+	(dwelf_strent_off): Likewise.
+	(dwelf_strent_str): Likewise.
+	(dwelf_strtab_free): Likewise.
+
+2015-10-28  Mark Wielaard  <mjw@redhat.com>
+
+	* Makefile.am (libdwelf_a_SOURCES): Add
+	dwelf_scn_gnu_compressed_size.c.
+	* dwelf_scn_gnu_compressed_size.c: Likewise.
+	* libdwelf.h (dwelf_scn_gnu_compressed_size): New declaration.
+
+2015-10-14  Chih-Hung Hsieh  <chh@google.com>
+
+	* dwelf_elf_gnu_build_id.c (find_elf_build_id): Move nested function
+	'check_notes' to file scope.
+
+2014-11-14  Mark Wielaard  <mjw@redhat.com>
+
+	* dwelf_elf_gnu_debuglink.c (dwelf_elf_gnu_debuglink): Check d_buf
+	is not NULL.
+
+2014-04-30  Mark Wielaard  <mjw@redhat.com>
+
+	* Makefile.am (AM_CPPFLAGS): Add libdwfl and libebl include dirs.
+	(libdwelf_a_SOURCES): Add dwelf_elf_gnu_build_id.c
+	* dwelf_elf_gnu_build_id.c: New file. Moved libdwfl function
+	__libdwfl_find_elf_build_id here.
+	* libdwelf.h (dwelf_elf_gnu_build_id): Declare new function.
+	* libdwelfP.h (dwelf_elf_gnu_build_id): Add internal declaration.
+
+2014-04-24  Florian Weimer  <fweimer@redhat.com>
+
+	* dwelf_dwarf_gnu_debugaltlink.c: New file.
+	* Makefile.am (libdwelf_a_SOURCES): Add it.
+	* libdwelf.h (dwelf_dwarf_gnu_debugaltlink): Declare new function.
+	* libdwelfP.h (dwelf_dwarf_gnu_debugaltlink): Add internal
+	declaration.
+
+2014-04-11  Mark Wielaard  <mjw@redhat.com>
+
+	* Makefile.am: New file.
+	* libdwelf.h: Likewise.
+	* libdwelfP.h: Likewise.
+	* dwelf_elf_gnu_debuglink.c: Likewise.
diff --git a/libdwelf/Makefile.am b/libdwelf/Makefile.am
new file mode 100644
index 0000000..7ca767a
--- /dev/null
+++ b/libdwelf/Makefile.am
@@ -0,0 +1,56 @@
+## Makefile.am for libdwelf library subdirectory in elfutils.
+##
+## Process this file with automake to create Makefile.in
+##
+## Copyright (C) 2014, 2015 Red Hat, Inc.
+## This file is part of elfutils.
+##
+## This file is free software; you can redistribute it and/or modify
+## it under the terms of either
+##
+##   * the GNU Lesser General Public License as published by the Free
+##     Software Foundation; either version 3 of the License, or (at
+##     your option) any later version
+##
+## or
+##
+##   * the GNU General Public License as published by the Free
+##     Software Foundation; either version 2 of the License, or (at
+##     your option) any later version
+##
+## or both in parallel, as here.
+##
+## elfutils is distributed in the hope that it will be useful, but
+## WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+## General Public License for more details.
+##
+## You should have received copies of the GNU General Public License and
+## the GNU Lesser General Public License along with this program.  If
+## not, see <http://www.gnu.org/licenses/>.
+##
+include $(top_srcdir)/config/eu.am
+AM_CPPFLAGS += -I$(srcdir)/../libelf -I$(srcdir)/../libdw \
+	       -I$(srcdir)/../libdwfl -I$(srcdir)/../libebl
+VERSION = 1
+
+noinst_LIBRARIES = libdwelf.a libdwelf_pic.a
+
+pkginclude_HEADERS = libdwelf.h
+noinst_HEADERS = libdwelfP.h
+
+libdwelf_a_SOURCES = dwelf_elf_gnu_debuglink.c dwelf_dwarf_gnu_debugaltlink.c \
+		     dwelf_elf_gnu_build_id.c dwelf_scn_gnu_compressed_size.c \
+		     dwelf_strtab.c
+
+libdwelf = $(libdw)
+
+libdw = ../libdw/libdw.so
+libelf = ../libelf/libelf.so
+libebl = ../libebl/libebl.a
+libeu = ../lib/libeu.a
+
+libdwelf_pic_a_SOURCES =
+am_libdwelf_pic_a_OBJECTS = $(libdwelf_a_SOURCES:.c=.os)
+
+CLEANFILES += $(am_libdwelf_pic_a_OBJECTS)
diff --git a/libdwelf/dwelf_dwarf_gnu_debugaltlink.c b/libdwelf/dwelf_dwarf_gnu_debugaltlink.c
new file mode 100644
index 0000000..b8285d0
--- /dev/null
+++ b/libdwelf/dwelf_dwarf_gnu_debugaltlink.c
@@ -0,0 +1,62 @@
+/* Returns the file name and build ID stored in the .gnu_altdebuglink if found.
+   Copyright (C) 2014 Red Hat, Inc.
+   This file is part of elfutils.
+
+   This file is free software; you can redistribute it and/or modify
+   it under the terms of either
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at
+       your option) any later version
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at
+       your option) any later version
+
+   or both in parallel, as here.
+
+   elfutils is distributed in the hope that it will be useful, but
+   WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see <http://www.gnu.org/licenses/>.  */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "libdwelfP.h"
+
+ssize_t
+dwelf_dwarf_gnu_debugaltlink (Dwarf *dwarf,
+			      const char **name_p,
+			      const void **build_idp)
+{
+  Elf_Data *data = dwarf->sectiondata[IDX_gnu_debugaltlink];
+  if (data == NULL)
+    {
+      return 0;
+    }
+
+  const void *ptr = memchr (data->d_buf, '\0', data->d_size);
+  if (ptr == NULL)
+    {
+      __libdw_seterrno (DWARF_E_INVALID_ELF);
+      return -1;
+    }
+  size_t build_id_len = data->d_size - (ptr - data->d_buf + 1);
+  if (build_id_len == 0 || (size_t) (ssize_t) build_id_len != build_id_len)
+    {
+      __libdw_seterrno (DWARF_E_INVALID_ELF);
+      return -1;
+    }
+  *name_p = data->d_buf;
+  *build_idp = ptr + 1;
+  return build_id_len;
+}
+INTDEF(dwelf_dwarf_gnu_debugaltlink)
diff --git a/libdwelf/dwelf_elf_gnu_build_id.c b/libdwelf/dwelf_elf_gnu_build_id.c
new file mode 100644
index 0000000..8c78c70
--- /dev/null
+++ b/libdwelf/dwelf_elf_gnu_build_id.c
@@ -0,0 +1,156 @@
+/* Returns the build id if found in a NT_GNU_BUILD_ID note.
+   Copyright (C) 2014 Red Hat, Inc.
+   This file is part of elfutils.
+
+   This file is free software; you can redistribute it and/or modify
+   it under the terms of either
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at
+       your option) any later version
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at
+       your option) any later version
+
+   or both in parallel, as here.
+
+   elfutils is distributed in the hope that it will be useful, but
+   WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see <http://www.gnu.org/licenses/>.  */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "libdwelfP.h"
+#include "libdwflP.h"
+
+#define NO_VADDR	((GElf_Addr) -1l)
+
+static int
+check_notes (Elf_Data *data, GElf_Addr data_elfaddr,
+             const void **build_id_bits, GElf_Addr *build_id_elfaddr,
+             int *build_id_len)
+{
+  size_t pos = 0;
+  GElf_Nhdr nhdr;
+  size_t name_pos;
+  size_t desc_pos;
+  while ((pos = gelf_getnote (data, pos, &nhdr, &name_pos, &desc_pos)) > 0)
+    if (nhdr.n_type == NT_GNU_BUILD_ID
+	&& nhdr.n_namesz == sizeof "GNU"
+	&& !memcmp (data->d_buf + name_pos, "GNU", sizeof "GNU"))
+	{
+	  *build_id_bits = data->d_buf + desc_pos;
+	  *build_id_elfaddr = (data_elfaddr == NO_VADDR
+	                      ? 0 : data_elfaddr + desc_pos);
+	  *build_id_len = nhdr.n_descsz;
+	  return 1;
+	}
+  return 0;
+}
+
+/* Defined here for reuse. The dwelf interface doesn't care about the
+   address of the note, but libdwfl does.  */
+static int
+find_elf_build_id (Dwfl_Module *mod, int e_type, Elf *elf,
+		   const void **build_id_bits, GElf_Addr *build_id_elfaddr,
+		   int *build_id_len)
+{
+  size_t shstrndx = SHN_UNDEF;
+  int result = 0;
+
+  Elf_Scn *scn = elf_nextscn (elf, NULL);
+
+  if (scn == NULL)
+    {
+      /* No sections, have to look for phdrs.  */
+      size_t phnum;
+      if (unlikely (elf_getphdrnum (elf, &phnum) != 0))
+	{
+	  if (mod != NULL)
+	    __libdwfl_seterrno (DWFL_E_LIBELF);
+	  return -1;
+	}
+      for (size_t i = 0; result == 0 && i < phnum; ++i)
+	{
+	  GElf_Phdr phdr_mem;
+	  GElf_Phdr *phdr = gelf_getphdr (elf, i, &phdr_mem);
+	  if (likely (phdr != NULL) && phdr->p_type == PT_NOTE)
+	    result = check_notes (elf_getdata_rawchunk (elf,
+							phdr->p_offset,
+							phdr->p_filesz,
+							ELF_T_NHDR),
+				  phdr->p_vaddr,
+				  build_id_bits,
+				  build_id_elfaddr,
+				  build_id_len);
+	}
+    }
+  else
+    do
+      {
+	GElf_Shdr shdr_mem;
+	GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
+	if (likely (shdr != NULL) && shdr->sh_type == SHT_NOTE)
+	  {
+	    /* Determine the right sh_addr in this module.  */
+	    GElf_Addr vaddr = 0;
+	    if (!(shdr->sh_flags & SHF_ALLOC))
+	      vaddr = NO_VADDR;
+	    else if (mod == NULL || e_type != ET_REL)
+	      vaddr = shdr->sh_addr;
+	    else if (__libdwfl_relocate_value (mod, elf, &shstrndx,
+					       elf_ndxscn (scn), &vaddr))
+	      vaddr = NO_VADDR;
+	    result = check_notes (elf_getdata (scn, NULL), vaddr,
+	                          build_id_bits,
+	                          build_id_elfaddr,
+	                          build_id_len);
+	  }
+      }
+    while (result == 0 && (scn = elf_nextscn (elf, scn)) != NULL);
+
+  return result;
+}
+
+int
+internal_function
+__libdwfl_find_elf_build_id (Dwfl_Module *mod, Elf *elf,
+			     const void **build_id_bits,
+			     GElf_Addr *build_id_elfaddr, int *build_id_len)
+{
+  GElf_Ehdr ehdr_mem, *ehdr = gelf_getehdr (elf, &ehdr_mem);
+  if (unlikely (ehdr == NULL))
+    {
+      __libdwfl_seterrno (DWFL_E_LIBELF);
+      return -1;
+    }
+  // MOD->E_TYPE is zero here.
+  assert (ehdr->e_type != ET_REL || mod != NULL);
+
+  return find_elf_build_id (mod, ehdr->e_type, elf,
+			    build_id_bits, build_id_elfaddr, build_id_len);
+}
+
+ssize_t
+dwelf_elf_gnu_build_id (Elf *elf, const void **build_idp)
+{
+  GElf_Addr build_id_elfaddr;
+  int build_id_len;
+  int result = find_elf_build_id (NULL, ET_NONE, elf, build_idp,
+				  &build_id_elfaddr, &build_id_len);
+  if (result > 0)
+    return build_id_len;
+
+  return result;
+}
+INTDEF(dwelf_elf_gnu_build_id)
diff --git a/libdwelf/dwelf_elf_gnu_debuglink.c b/libdwelf/dwelf_elf_gnu_debuglink.c
new file mode 100644
index 0000000..6e22cf6
--- /dev/null
+++ b/libdwelf/dwelf_elf_gnu_debuglink.c
@@ -0,0 +1,99 @@
+/* Returns the file name and crc stored in the .gnu_debuglink if found.
+   Copyright (C) 2014 Red Hat, Inc.
+   This file is part of elfutils.
+
+   This file is free software; you can redistribute it and/or modify
+   it under the terms of either
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at
+       your option) any later version
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at
+       your option) any later version
+
+   or both in parallel, as here.
+
+   elfutils is distributed in the hope that it will be useful, but
+   WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see <http://www.gnu.org/licenses/>.  */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "libdwelfP.h"
+
+const char *
+dwelf_elf_gnu_debuglink (Elf *elf, GElf_Word *crc)
+{
+  size_t shstrndx;
+  if (elf_getshdrstrndx (elf, &shstrndx) < 0)
+    return NULL;
+
+  Elf_Scn *scn = NULL;
+  while ((scn = elf_nextscn (elf, scn)) != NULL)
+    {
+      GElf_Shdr shdr_mem;
+      GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
+      if (shdr == NULL)
+        return NULL;
+
+      const char *name = elf_strptr (elf, shstrndx, shdr->sh_name);
+      if (name == NULL)
+        return NULL;
+
+      if (!strcmp (name, ".gnu_debuglink"))
+        break;
+    }
+
+  if (scn == NULL)
+    return NULL;
+
+  /* Found the .gnu_debuglink section.  Extract its contents.  */
+  Elf_Data *rawdata = elf_rawdata (scn, NULL);
+  if (rawdata == NULL || rawdata->d_buf == NULL)
+    return NULL;
+
+  /* The CRC comes after the zero-terminated file name,
+     (aligned up to 4 bytes) at the end of the section data.  */
+  if (rawdata->d_size <= sizeof *crc
+      || memchr (rawdata->d_buf, '\0', rawdata->d_size - sizeof *crc) == NULL)
+    return NULL;
+
+  Elf_Data crcdata =
+    {
+      .d_type = ELF_T_WORD,
+      .d_buf = crc,
+      .d_size = sizeof *crc,
+      .d_version = EV_CURRENT,
+    };
+  Elf_Data conv =
+    {
+      .d_type = ELF_T_WORD,
+      .d_buf = rawdata->d_buf + rawdata->d_size - sizeof *crc,
+      .d_size = sizeof *crc,
+      .d_version = EV_CURRENT,
+    };
+
+  GElf_Ehdr ehdr_mem;
+  GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
+  if (ehdr == NULL)
+    return NULL;
+
+  Elf_Data *d = gelf_xlatetom (elf, &crcdata, &conv, ehdr->e_ident[EI_DATA]);
+  if (d == NULL)
+    return NULL;
+  assert (d == &crcdata);
+
+  return rawdata->d_buf;
+}
+INTDEF(dwelf_elf_gnu_debuglink)
diff --git a/libdwelf/dwelf_scn_gnu_compressed_size.c b/libdwelf/dwelf_scn_gnu_compressed_size.c
new file mode 100644
index 0000000..d39b702
--- /dev/null
+++ b/libdwelf/dwelf_scn_gnu_compressed_size.c
@@ -0,0 +1,77 @@
+/* Return size of GNU compressed section.
+   Copyright (C) 2015 Red Hat, Inc.
+   This file is part of elfutils.
+
+   This file is free software; you can redistribute it and/or modify
+   it under the terms of either
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at
+       your option) any later version
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at
+       your option) any later version
+
+   or both in parallel, as here.
+
+   elfutils is distributed in the hope that it will be useful, but
+   WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see <http://www.gnu.org/licenses/>.  */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include "libdwelfP.h"
+#include "libelfP.h"
+
+ssize_t
+dwelf_scn_gnu_compressed_size (Elf_Scn *scn)
+{
+  if (scn == NULL)
+    return -1;
+
+  GElf_Shdr shdr;
+  if (gelf_getshdr (scn, &shdr) == NULL)
+    return -1;
+
+  /* Allocated or no bits sections can never be compressed.  */
+  if ((shdr.sh_flags & SHF_ALLOC) != 0
+      || shdr.sh_type == SHT_NULL
+      || shdr.sh_type == SHT_NOBITS)
+    return -1;
+
+  Elf_Data *d = elf_rawdata (scn, NULL);
+  if (d == NULL)
+    return -1;
+
+  if (d->d_size >= 4 + 8
+      && memcmp (d->d_buf, "ZLIB", 4) == 0)
+    {
+      /* There is a 12-byte header of "ZLIB" followed by
+	 an 8-byte big-endian size.  There is only one type and
+	 alignment isn't preserved separately.  */
+      uint64_t size;
+      memcpy (&size, d->d_buf + 4, sizeof size);
+      size = be64toh (size);
+
+      /* One more sanity check, size should be bigger than original
+	 data size plus some overhead (4 chars ZLIB + 8 bytes size + 6
+	 bytes zlib stream overhead + 5 bytes overhead max for one 16K
+	 block) and should fit into a size_t.  */
+      if (size + 4 + 8 + 6 + 5 < d->d_size || size > SIZE_MAX)
+	return -1;
+
+      return size;
+    }
+
+  return -1;
+}
diff --git a/libdwelf/dwelf_strtab.c b/libdwelf/dwelf_strtab.c
new file mode 100644
index 0000000..01e091c
--- /dev/null
+++ b/libdwelf/dwelf_strtab.c
@@ -0,0 +1,360 @@
+/* ELF/DWARF string table handling.
+   Copyright (C) 2000, 2001, 2002, 2005, 2016 Red Hat, Inc.
+   This file is part of elfutils.
+   Written by Ulrich Drepper <drepper@redhat.com>, 2000.
+
+   This file is free software; you can redistribute it and/or modify
+   it under the terms of either
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at
+       your option) any later version
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at
+       your option) any later version
+
+   or both in parallel, as here.
+
+   elfutils is distributed in the hope that it will be useful, but
+   WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see <http://www.gnu.org/licenses/>.  */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <assert.h>
+#include <inttypes.h>
+#include <libelf.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "libdwelfP.h"
+#include <system.h>
+
+
+struct Dwelf_Strent
+{
+  const char *string;
+  size_t len;
+  struct Dwelf_Strent *next;
+  struct Dwelf_Strent *left;
+  struct Dwelf_Strent *right;
+  size_t offset;
+  char reverse[0];
+};
+
+
+struct memoryblock
+{
+  struct memoryblock *next;
+  char memory[0];
+};
+
+
+struct Dwelf_Strtab
+{
+  struct Dwelf_Strent *root;
+  struct memoryblock *memory;
+  char *backp;
+  size_t left;
+  size_t total;
+  bool nullstr;
+
+  struct Dwelf_Strent null;
+};
+
+
+/* Cache for the pagesize.  */
+static size_t ps;
+/* We correct this value a bit so that `malloc' is not allocating more
+   than a page. */
+#define MALLOC_OVERHEAD (2 * sizeof (void *))
+
+
+Dwelf_Strtab *
+dwelf_strtab_init (bool nullstr)
+{
+  if (ps == 0)
+    {
+      ps = sysconf (_SC_PAGESIZE);
+      assert (sizeof (struct memoryblock) < ps - MALLOC_OVERHEAD);
+    }
+
+  Dwelf_Strtab *ret
+    = (Dwelf_Strtab *) calloc (1, sizeof (struct Dwelf_Strtab));
+  if (ret != NULL)
+    {
+      ret->nullstr = nullstr;
+
+      if (nullstr)
+	{
+	  ret->null.len = 1;
+	  ret->null.string = "";
+	}
+    }
+
+  return ret;
+}
+
+
+static int
+morememory (Dwelf_Strtab *st, size_t len)
+{
+  size_t overhead = offsetof (struct memoryblock, memory);
+  len += overhead + MALLOC_OVERHEAD;
+
+  /* Allocate nearest multiple of pagesize >= len.  */
+  len = ((len / ps) + (len % ps != 0)) * ps - MALLOC_OVERHEAD;
+
+  struct memoryblock *newmem = (struct memoryblock *) malloc (len);
+  if (newmem == NULL)
+    return 1;
+
+  newmem->next = st->memory;
+  st->memory = newmem;
+  st->backp = newmem->memory;
+  st->left = len - overhead;
+
+  return 0;
+}
+
+
+void
+dwelf_strtab_free (Dwelf_Strtab *st)
+{
+  struct memoryblock *mb = st->memory;
+
+  while (mb != NULL)
+    {
+      void *old = mb;
+      mb = mb->next;
+      free (old);
+    }
+
+  free (st);
+}
+
+
+static Dwelf_Strent *
+newstring (Dwelf_Strtab *st, const char *str, size_t len)
+{
+  /* Compute the amount of padding needed to make the structure aligned.  */
+  size_t align = ((__alignof__ (struct Dwelf_Strent)
+		   - (((uintptr_t) st->backp)
+		      & (__alignof__ (struct Dwelf_Strent) - 1)))
+		  & (__alignof__ (struct Dwelf_Strent) - 1));
+
+  /* Make sure there is enough room in the memory block.  */
+  if (st->left < align + sizeof (struct Dwelf_Strent) + len)
+    {
+      if (morememory (st, sizeof (struct Dwelf_Strent) + len))
+	return NULL;
+
+      align = 0;
+    }
+
+  /* Create the reserved string.  */
+  Dwelf_Strent *newstr = (Dwelf_Strent *) (st->backp + align);
+  newstr->string = str;
+  newstr->len = len;
+  newstr->next = NULL;
+  newstr->left = NULL;
+  newstr->right = NULL;
+  newstr->offset = 0;
+  for (int i = len - 2; i >= 0; --i)
+    newstr->reverse[i] = str[len - 2 - i];
+  newstr->reverse[len - 1] = '\0';
+  st->backp += align + sizeof (struct Dwelf_Strent) + len;
+  st->left -= align + sizeof (struct Dwelf_Strent) + len;
+
+  return newstr;
+}
+
+
+/* XXX This function should definitely be rewritten to use a balancing
+   tree algorith (AVL, red-black trees).  For now a simple, correct
+   implementation is enough.  */
+static Dwelf_Strent **
+searchstring (Dwelf_Strent **sep, Dwelf_Strent *newstr)
+{
+  /* More strings?  */
+  if (*sep == NULL)
+    {
+      *sep = newstr;
+      return sep;
+    }
+
+  /* Compare the strings.  */
+  int cmpres = memcmp ((*sep)->reverse, newstr->reverse,
+		       MIN ((*sep)->len, newstr->len) - 1);
+  if (cmpres == 0)
+    /* We found a matching string.  */
+    return sep;
+  else if (cmpres > 0)
+    return searchstring (&(*sep)->left, newstr);
+  else
+    return searchstring (&(*sep)->right, newstr);
+}
+
+
+/* Add new string.  The actual string is assumed to be permanent.  */
+static Dwelf_Strent *
+strtab_add (Dwelf_Strtab *st, const char *str, size_t len)
+{
+  /* Make sure all "" strings get offset 0 but only if the table was
+     created with a special null entry in mind.  */
+  if (len == 1 && st->null.string != NULL)
+    return &st->null;
+
+  /* Allocate memory for the new string and its associated information.  */
+  Dwelf_Strent *newstr = newstring (st, str, len);
+  if (newstr == NULL)
+    return NULL;
+
+  /* Search in the array for the place to insert the string.  If there
+     is no string with matching prefix and no string with matching
+     leading substring, create a new entry.  */
+  Dwelf_Strent **sep = searchstring (&st->root, newstr);
+  if (*sep != newstr)
+    {
+      /* This is not the same entry.  This means we have a prefix match.  */
+      if ((*sep)->len > newstr->len)
+	{
+	  /* Check whether we already know this string.  */
+	  for (Dwelf_Strent *subs = (*sep)->next; subs != NULL;
+	       subs = subs->next)
+	    if (subs->len == newstr->len)
+	      {
+		/* We have an exact match with a substring.  Free the memory
+		   we allocated.  */
+		st->left += st->backp - (char *) newstr;
+		st->backp = (char *) newstr;
+
+		return subs;
+	      }
+
+	  /* We have a new substring.  This means we don't need the reverse
+	     string of this entry anymore.  */
+	  st->backp -= newstr->len;
+	  st->left += newstr->len;
+
+	  newstr->next = (*sep)->next;
+	  (*sep)->next = newstr;
+	}
+      else if ((*sep)->len != newstr->len)
+	{
+	  /* When we get here it means that the string we are about to
+	     add has a common prefix with a string we already have but
+	     it is longer.  In this case we have to put it first.  */
+	  st->total += newstr->len - (*sep)->len;
+	  newstr->next = *sep;
+	  newstr->left = (*sep)->left;
+	  newstr->right = (*sep)->right;
+	  *sep = newstr;
+	}
+      else
+	{
+	  /* We have an exact match.  Free the memory we allocated.  */
+	  st->left += st->backp - (char *) newstr;
+	  st->backp = (char *) newstr;
+
+	  newstr = *sep;
+	}
+    }
+  else
+    st->total += newstr->len;
+
+  return newstr;
+}
+
+Dwelf_Strent *
+dwelf_strtab_add (Dwelf_Strtab *st, const char *str)
+{
+  return strtab_add (st, str, strlen (str) + 1);
+}
+
+Dwelf_Strent *
+dwelf_strtab_add_len (Dwelf_Strtab *st, const char *str, size_t len)
+{
+  return strtab_add (st, str, len);
+}
+
+static void
+copystrings (Dwelf_Strent *nodep, char **freep, size_t *offsetp)
+{
+  if (nodep->left != NULL)
+    copystrings (nodep->left, freep, offsetp);
+
+  /* Process the current node.  */
+  nodep->offset = *offsetp;
+  *freep = (char *) mempcpy (*freep, nodep->string, nodep->len);
+  *offsetp += nodep->len;
+
+  for (Dwelf_Strent *subs = nodep->next; subs != NULL; subs = subs->next)
+    {
+      assert (subs->len < nodep->len);
+      subs->offset = nodep->offset + nodep->len - subs->len;
+      assert (subs->offset != 0 || subs->string[0] == '\0');
+    }
+
+  if (nodep->right != NULL)
+    copystrings (nodep->right, freep, offsetp);
+}
+
+
+Elf_Data *
+dwelf_strtab_finalize (Dwelf_Strtab *st, Elf_Data *data)
+{
+  size_t nulllen = st->nullstr ? 1 : 0;
+
+  /* Fill in the information.  */
+  data->d_buf = malloc (st->total + nulllen);
+  if (data->d_buf == NULL)
+    return NULL;
+
+  /* The first byte must always be zero if we created the table with a
+     null string.  */
+  if (st->nullstr)
+    *((char *) data->d_buf) = '\0';
+
+  data->d_type = ELF_T_BYTE;
+  data->d_size = st->total + nulllen;
+  data->d_off = 0;
+  data->d_align = 1;
+  data->d_version = EV_CURRENT;
+
+  /* Now run through the tree and add all the string while also updating
+     the offset members of the elfstrent records.  */
+  char *endp = (char *) data->d_buf + nulllen;
+  size_t copylen = nulllen;
+  if (st->root)
+    copystrings (st->root, &endp, &copylen);
+  assert (copylen == st->total + nulllen);
+
+  return data;
+}
+
+
+size_t
+dwelf_strent_off (Dwelf_Strent *se)
+{
+  return se->offset;
+}
+
+
+const char *
+dwelf_strent_str (Dwelf_Strent *se)
+{
+  return se->string;
+}
diff --git a/libdwelf/libdwelf.h b/libdwelf/libdwelf.h
new file mode 100644
index 0000000..72089db
--- /dev/null
+++ b/libdwelf/libdwelf.h
@@ -0,0 +1,132 @@
+/* Interfaces for libdwelf. DWARF ELF Low-level Functions.
+   Copyright (C) 2014, 2015, 2016 Red Hat, Inc.
+   This file is part of elfutils.
+
+   This file is free software; you can redistribute it and/or modify
+   it under the terms of either
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at
+       your option) any later version
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at
+       your option) any later version
+
+   or both in parallel, as here.
+
+   elfutils is distributed in the hope that it will be useful, but
+   WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see <http://www.gnu.org/licenses/>.  */
+
+#ifndef _LIBDWELF_H
+#define _LIBDWELF_H	1
+
+#include "libdw.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* DWARF ELF Low-level Functions (dwelf).
+   Functions starting with dwelf_elf will take a (libelf) Elf object as
+   first argument and might set elf_errno on error.  Functions starting
+   with dwelf_dwarf will take a (libdw) Dwarf object as first argument
+   and might set dwarf_errno on error.  */
+
+/* Returns the name and the CRC32 of the separate debug file from the
+   .gnu_debuglink section if found in the ELF.  Return NULL if the ELF
+   file didn't have a .gnu_debuglink section, had malformed data in the
+   section or some other error occured.  */
+extern const char *dwelf_elf_gnu_debuglink (Elf *elf, GElf_Word *crc);
+
+/* Returns the name and build ID from the .gnu_debugaltlink section if
+   found in the ELF.  On success, pointers to the name and build ID
+   are written to *NAMEP and *BUILDID_P, and the positive length of
+   the build ID is returned.  Returns 0 if the ELF lacks a
+   .gnu_debugaltlink section.  Returns -1 in case of malformed data or
+   other errors.  */
+extern ssize_t dwelf_dwarf_gnu_debugaltlink (Dwarf *dwarf,
+					     const char **namep,
+					     const void **build_idp);
+
+/* Returns the build ID as found in a NT_GNU_BUILD_ID note from either
+   a SHT_NOTE section or from a PT_NOTE segment if the ELF file
+   doesn't contain any section headers.  On success a pointer to the
+   build ID is written to *BUILDID_P, and the positive length of the
+   build ID is returned.  Returns 0 if the ELF lacks a NT_GNU_BUILD_ID
+   note.  Returns -1 in case of malformed data or other errors.  */
+extern ssize_t dwelf_elf_gnu_build_id (Elf *elf, const void **build_idp);
+
+/* Returns the size of the uncompressed data of a GNU compressed
+   section.  The section name should start with .zdebug (but this
+   isn't checked by this function).  If the section isn't compressed
+   (the section data doesn't start with ZLIB) -1 is returned. If an
+   error occured -1 is returned and elf_errno is set.  */
+extern ssize_t dwelf_scn_gnu_compressed_size (Elf_Scn *scn);
+
+/* ELF/DWARF string table handling.  */
+typedef struct Dwelf_Strtab Dwelf_Strtab;
+typedef struct Dwelf_Strent Dwelf_Strent;
+
+/* Create a new ELF/DWARF string table object in memory.  ELF string
+   tables have a required zero length null string at offset zero.
+   DWARF string tables don't require such a null entry (unless they
+   are shared with an ELF string table).  If NULLSTR is true then a
+   null entry is always created (even if the string table is empty
+   otherwise).  */
+extern Dwelf_Strtab *dwelf_strtab_init (bool nullstr);
+
+/* Add string STR to string table ST.  Returns NULL if no memory could
+   be allocated.  The given STR is owned by the called and must be
+   valid till dwelf_strtab_free is called.  dwelf_strtab_finalize
+   might copy the string into the final table and dwelf_strent_str
+   might return it, or a reference to an identical copy/substring
+   added to the string table.  */
+extern Dwelf_Strent *dwelf_strtab_add (Dwelf_Strtab *st, const char *str)
+  __nonnull_attribute__ (1, 2);
+
+/* This is an optimized version of dwelf_strtab_add if the length of
+   the string is already known.  LEN is the length of STR including
+   zero terminator.  Calling dwelf_strtab_add (st, str) is similar to
+   calling dwelf_strtab_len (st, str, strlen (str) + 1).  */
+extern Dwelf_Strent *dwelf_strtab_add_len (Dwelf_Strtab *st,
+					   const char *str, size_t len)
+  __nonnull_attribute__ (1, 2);
+
+/* Finalize string table ST and store size and memory location
+   information in DATA d_size and d_buf.  DATA d_type will be set to
+   ELF_T_BYTE, d_off will be zero, d_align will be 1 and d_version
+   will be set to EV_CURRENT.  If no memory could be allocated NULL is
+   returned and DATA->d_buf will be set to NULL.  Otherwise DATA will
+   be returned.  */
+extern Elf_Data *dwelf_strtab_finalize (Dwelf_Strtab *st,
+					Elf_Data *data)
+  __nonnull_attribute__ (1, 2);
+
+/* Get offset in string table for string associated with entry.  Only
+   valid after dwelf_strtab_finalize has been called.  */
+extern size_t dwelf_strent_off (Dwelf_Strent *se)
+  __nonnull_attribute__ (1);
+
+/* Return the string associated with the entry.  */
+extern const char *dwelf_strent_str (Dwelf_Strent *se)
+  __nonnull_attribute__ (1);
+
+/* Free resources allocated for the string table.  This invalidates
+   any Dwelf_Strent references returned earlier. */
+extern void dwelf_strtab_free (Dwelf_Strtab *st)
+  __nonnull_attribute__ (1);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif	/* libdwelf.h */
diff --git a/libdwelf/libdwelfP.h b/libdwelf/libdwelfP.h
new file mode 100644
index 0000000..d83c759
--- /dev/null
+++ b/libdwelf/libdwelfP.h
@@ -0,0 +1,42 @@
+/* Internal definitions for libdwelf. DWARF ELF Low-level Functions.
+   Copyright (C) 2014 Red Hat, Inc.
+   This file is part of elfutils.
+
+   This file is free software; you can redistribute it and/or modify
+   it under the terms of either
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at
+       your option) any later version
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at
+       your option) any later version
+
+   or both in parallel, as here.
+
+   elfutils is distributed in the hope that it will be useful, but
+   WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see <http://www.gnu.org/licenses/>.  */
+
+#ifndef _LIBDWELFP_H
+#define _LIBDWELFP_H	1
+
+#include <libdwelf.h>
+#include "../libdw/libdwP.h"	/* We need its INTDECLs.  */
+#include <assert.h>
+#include <string.h>
+
+/* Avoid PLT entries.  */
+INTDECL (dwelf_elf_gnu_debuglink)
+INTDECL (dwelf_dwarf_gnu_debugaltlink)
+INTDECL (dwelf_elf_gnu_build_id)
+
+#endif	/* libdwelfP.h */