Blame SOURCES/glibc-rh677316-dynarray.patch

147e83
Backport of the following upstream commits:
147e83
147e83
commit ab5ac271e6210fa0af11cf3ca525ce573bc47c48
147e83
Author: Florian Weimer <fweimer@redhat.com>
147e83
Date:   Wed Sep 6 11:25:14 2017 +0200
147e83
147e83
    __libc_dynarray_emplace_enlarge: Add missing else
147e83
    
147e83
    Before, arrays of small elements received a starting allocation size of
147e83
    8, not 16.
147e83
147e83
commit 5898f4548efdcd7c0fd437a74eeb80facc51a117
147e83
Author: Florian Weimer <fweimer@redhat.com>
147e83
Date:   Wed Aug 30 20:10:56 2017 +0200
147e83
147e83
    dynarray: Set errno on overflow-induced allocation failure
147e83
    
147e83
    This allows the caller to return directly on such an error, with an
147e83
    appropriate errno value.
147e83
147e83
commit 5b83faf6a7ca57ef2bfbca2c77992cafc8daa0be
147e83
Author: Florian Weimer <fweimer@redhat.com>
147e83
Date:   Mon Jun 19 12:58:08 2017 +0200
147e83
147e83
    dynarray: Use libc_hidden_proto only for !_ISOMAC
147e83
147e83
    With this change, it is possible to use dynarray from non-internal
147e83
    tests.
147e83
147e83
commit f8bf87face3304f216bcd838081fa33bb4976ac6
147e83
Author: Florian Weimer <fweimer@redhat.com>
147e83
Date:   Tue Jun 13 17:03:56 2017 +0200
147e83
147e83
    dynarray: Implement begin/end functions in the spirit of C++
147e83
147e83
commit 990c32b93a29d8b8d599e10ebca19a260f84cbba
147e83
Author: Florian Weimer <fweimer@redhat.com>
147e83
Date:   Fri Jun 9 14:08:57 2017 +0200
147e83
147e83
    malloc: Remove tst-dynarray, tst-dynarray-fail from test-srcs
147e83
    
147e83
    They are already covered through the tests variable.
147e83
147e83
commit 91b6eb1140eda6bab324821ee3785e5d0ca155b8
147e83
Author: Florian Weimer <fweimer@redhat.com>
147e83
Date:   Fri Jun 2 11:59:28 2017 +0200
147e83
147e83
    Add internal facility for dynamic array handling
147e83
147e83
    This is intended as a type-safe alternative to obstacks and
147e83
    hand-written realloc constructs.  The implementation avoids
147e83
    writing function pointers to the heap.
147e83
147e83
malloc/tst-dynarray-at-fail.c has been adjusted to use __WORDSIZE
147e83
instead of SIZE_WIDTH.
147e83
147e83
malloc/Makefile has been adjusted to the changes in the build and test
147e83
process (no tests-internal in glibc 2.17, mtrace tests are handled
147e83
differently, there is no evaluate-test Makefile macro).
147e83
147e83
diff --git a/malloc/Makefile b/malloc/Makefile
147e83
index 38aa9e0993d4880c..63fc3291dcc4077a 100644
147e83
--- a/malloc/Makefile
147e83
+++ b/malloc/Makefile
147e83
@@ -34,6 +34,9 @@ tests := mallocbug tst-malloc tst-valloc tst-calloc tst-obstack \
147e83
 	 tst-interpose-static-nothread \
147e83
 	 tst-interpose-static-thread \
147e83
 	 tst-scratch_buffer \
147e83
+	 tst-dynarray \
147e83
+	 tst-dynarray-fail \
147e83
+	 tst-dynarray-at-fail \
147e83
 
147e83
 tests-static := \
147e83
 	 tst-interpose-static-nothread \
147e83
@@ -41,10 +44,17 @@ tests-static := \
147e83
 
147e83
 test-srcs = tst-mtrace
147e83
 
147e83
+generated += tst-dynarray-mem tst-dynarray-fail-mem
147e83
+
147e83
 routines = malloc morecore mcheck mtrace obstack \
147e83
   scratch_buffer_grow \
147e83
   scratch_buffer_grow_preserve \
147e83
   scratch_buffer_set_array_size \
147e83
+  dynarray_at_failure \
147e83
+  dynarray_emplace_enlarge \
147e83
+  dynarray_finalize \
147e83
+  dynarray_resize \
147e83
+  dynarray_resize_clear \
147e83
 
147e83
 
147e83
 install-lib := libmcheck.a
147e83
@@ -143,8 +153,7 @@ ifeq ($(run-built-tests),yes)
147e83
 ifeq (yes,$(build-shared))
147e83
 ifneq ($(PERL),no)
147e83
 tests: $(objpfx)tst-mtrace.out
147e83
-$(objpfx)tst-mtrace.out: tst-mtrace.sh $(objpfx)tst-mtrace
147e83
-	$(SHELL) $< $(common-objpfx) '$(run-program-prefix)'
147e83
+tests: $(objpfx)tst-dynarray-mem $(objpfx)tst-dynarray-fail-mem
147e83
 endif
147e83
 endif
147e83
 endif
147e83
@@ -194,3 +203,11 @@ $(objpfx)tst-interpose-static-thread: \
147e83
 # Compile the tests with a flag which suppresses the mallopt call in
147e83
 # the test skeleton.
147e83
 $(tests:%=$(objpfx)%.o): CPPFLAGS += -DTEST_NO_MALLOPT
147e83
+
147e83
+tst-dynarray-ENV = MALLOC_TRACE=$(objpfx)tst-dynarray.mtrace
147e83
+$(objpfx)tst-dynarray-mem: $(objpfx)tst-dynarray.out
147e83
+	$(common-objpfx)malloc/mtrace $(objpfx)tst-dynarray.mtrace > $@
147e83
+
147e83
+tst-dynarray-fail-ENV = MALLOC_TRACE=$(objpfx)tst-dynarray-fail.mtrace
147e83
+$(objpfx)tst-dynarray-fail-mem: $(objpfx)tst-dynarray-fail.out
147e83
+	$(common-objpfx)malloc/mtrace $(objpfx)tst-dynarray-fail.mtrace > $@
147e83
diff --git a/malloc/Versions b/malloc/Versions
147e83
index f3c3d8a0934bdcd3..16f9dab418a4e3f6 100644
147e83
--- a/malloc/Versions
147e83
+++ b/malloc/Versions
147e83
@@ -72,5 +72,12 @@ libc {
147e83
     __libc_scratch_buffer_grow;
147e83
     __libc_scratch_buffer_grow_preserve;
147e83
     __libc_scratch_buffer_set_array_size;
147e83
+
147e83
+    # dynarray support
147e83
+    __libc_dynarray_at_failure;
147e83
+    __libc_dynarray_emplace_enlarge;
147e83
+    __libc_dynarray_finalize;
147e83
+    __libc_dynarray_resize;
147e83
+    __libc_dynarray_resize_clear;
147e83
   }
147e83
 }
147e83
diff --git a/malloc/dynarray-skeleton.c b/malloc/dynarray-skeleton.c
147e83
new file mode 100644
147e83
index 0000000000000000..7ec58788087e80d3
147e83
--- /dev/null
147e83
+++ b/malloc/dynarray-skeleton.c
147e83
@@ -0,0 +1,521 @@
147e83
+/* Type-safe arrays which grow dynamically.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+/* Pre-processor macros which act as parameters:
147e83
+
147e83
+   DYNARRAY_STRUCT
147e83
+      The struct tag of dynamic array to be defined.
147e83
+   DYNARRAY_ELEMENT
147e83
+      The type name of the element type.  Elements are copied
147e83
+      as if by memcpy, and can change address as the dynamic
147e83
+      array grows.
147e83
+   DYNARRAY_PREFIX
147e83
+      The prefix of the functions which are defined.
147e83
+
147e83
+   The following parameters are optional:
147e83
+
147e83
+   DYNARRAY_ELEMENT_FREE
147e83
+      DYNARRAY_ELEMENT_FREE (E) is evaluated to deallocate the
147e83
+      contents of elements. E is of type  DYNARRAY_ELEMENT *.
147e83
+   DYNARRAY_ELEMENT_INIT
147e83
+      DYNARRAY_ELEMENT_INIT (E) is evaluated to initialize a new
147e83
+      element.  E is of type  DYNARRAY_ELEMENT *.
147e83
+      If DYNARRAY_ELEMENT_FREE but not DYNARRAY_ELEMENT_INIT is
147e83
+      defined, new elements are automatically zero-initialized.
147e83
+      Otherwise, new elements have undefined contents.
147e83
+   DYNARRAY_INITIAL_SIZE
147e83
+      The size of the statically allocated array (default:
147e83
+      at least 2, more elements if they fit into 128 bytes).
147e83
+      Must be a preprocessor constant.  If DYNARRAY_INITIAL_SIZE is 0,
147e83
+      there is no statically allocated array at, and all non-empty
147e83
+      arrays are heap-allocated.
147e83
+   DYNARRAY_FINAL_TYPE
147e83
+      The name of the type which holds the final array.  If not
147e83
+      defined, is PREFIX##finalize not provided.  DYNARRAY_FINAL_TYPE
147e83
+      must be a struct type, with members of type DYNARRAY_ELEMENT and
147e83
+      size_t at the start (in this order).
147e83
+
147e83
+   These macros are undefined after this header file has been
147e83
+   included.
147e83
+
147e83
+   The following types are provided (their members are private to the
147e83
+   dynarray implementation):
147e83
+
147e83
+     struct DYNARRAY_STRUCT
147e83
+
147e83
+   The following functions are provided:
147e83
+
147e83
+     void DYNARRAY_PREFIX##init (struct DYNARRAY_STRUCT *);
147e83
+     void DYNARRAY_PREFIX##free (struct DYNARRAY_STRUCT *);
147e83
+     bool DYNARRAY_PREFIX##has_failed (const struct DYNARRAY_STRUCT *);
147e83
+     void DYNARRAY_PREFIX##mark_failed (struct DYNARRAY_STRUCT *);
147e83
+     size_t DYNARRAY_PREFIX##size (const struct DYNARRAY_STRUCT *);
147e83
+     DYNARRAY_ELEMENT *DYNARRAY_PREFIX##begin (const struct DYNARRAY_STRUCT *);
147e83
+     DYNARRAY_ELEMENT *DYNARRAY_PREFIX##end (const struct DYNARRAY_STRUCT *);
147e83
+     DYNARRAY_ELEMENT *DYNARRAY_PREFIX##at (struct DYNARRAY_STRUCT *, size_t);
147e83
+     void DYNARRAY_PREFIX##add (struct DYNARRAY_STRUCT *, DYNARRAY_ELEMENT);
147e83
+     DYNARRAY_ELEMENT *DYNARRAY_PREFIX##emplace (struct DYNARRAY_STRUCT *);
147e83
+     bool DYNARRAY_PREFIX##resize (struct DYNARRAY_STRUCT *, size_t);
147e83
+     void DYNARRAY_PREFIX##remove_last (struct DYNARRAY_STRUCT *);
147e83
+     void DYNARRAY_PREFIX##clear (struct DYNARRAY_STRUCT *);
147e83
+
147e83
+   The following functions are provided are provided if the
147e83
+   prerequisites are met:
147e83
+
147e83
+     bool DYNARRAY_PREFIX##finalize (struct DYNARRAY_STRUCT *,
147e83
+                                     DYNARRAY_FINAL_TYPE *);
147e83
+       (if DYNARRAY_FINAL_TYPE is defined)
147e83
+     DYNARRAY_ELEMENT *DYNARRAY_PREFIX##finalize (struct DYNARRAY_STRUCT *,
147e83
+                                                  size_t *);
147e83
+       (if DYNARRAY_FINAL_TYPE is not defined)
147e83
+*/
147e83
+
147e83
+#include <malloc/dynarray.h>
147e83
+
147e83
+#include <errno.h>
147e83
+#include <stdlib.h>
147e83
+#include <string.h>
147e83
+
147e83
+#ifndef DYNARRAY_STRUCT
147e83
+# error "DYNARRAY_STRUCT must be defined"
147e83
+#endif
147e83
+
147e83
+#ifndef DYNARRAY_ELEMENT
147e83
+# error "DYNARRAY_ELEMENT must be defined"
147e83
+#endif
147e83
+
147e83
+#ifndef DYNARRAY_PREFIX
147e83
+# error "DYNARRAY_PREFIX must be defined"
147e83
+#endif
147e83
+
147e83
+#ifdef DYNARRAY_INITIAL_SIZE
147e83
+# if DYNARRAY_INITIAL_SIZE < 0
147e83
+#  error "DYNARRAY_INITIAL_SIZE must be non-negative"
147e83
+# endif
147e83
+# if DYNARRAY_INITIAL_SIZE > 0
147e83
+#  define DYNARRAY_HAVE_SCRATCH 1
147e83
+# else
147e83
+#  define DYNARRAY_HAVE_SCRATCH 0
147e83
+# endif
147e83
+#else
147e83
+/* Provide a reasonable default which limits the size of
147e83
+   DYNARRAY_STRUCT.  */
147e83
+# define DYNARRAY_INITIAL_SIZE \
147e83
+  (sizeof (DYNARRAY_ELEMENT) > 64 ? 2 : 128 / sizeof (DYNARRAY_ELEMENT))
147e83
+# define DYNARRAY_HAVE_SCRATCH 1
147e83
+#endif
147e83
+
147e83
+/* Public type definitions.  */
147e83
+
147e83
+/* All fields of this struct are private to the implementation.  */
147e83
+struct DYNARRAY_STRUCT
147e83
+{
147e83
+  union
147e83
+  {
147e83
+    struct dynarray_header dynarray_abstract;
147e83
+    struct
147e83
+    {
147e83
+      /* These fields must match struct dynarray_header.  */
147e83
+      size_t used;
147e83
+      size_t allocated;
147e83
+      DYNARRAY_ELEMENT *array;
147e83
+    } dynarray_header;
147e83
+  };
147e83
+
147e83
+#if DYNARRAY_HAVE_SCRATCH
147e83
+  /* Initial inline allocation.  */
147e83
+  DYNARRAY_ELEMENT scratch[DYNARRAY_INITIAL_SIZE];
147e83
+#endif
147e83
+};
147e83
+
147e83
+/* Internal use only: Helper macros.  */
147e83
+
147e83
+/* Ensure macro-expansion of DYNARRAY_PREFIX.  */
147e83
+#define DYNARRAY_CONCAT0(prefix, name) prefix##name
147e83
+#define DYNARRAY_CONCAT1(prefix, name) DYNARRAY_CONCAT0(prefix, name)
147e83
+#define DYNARRAY_NAME(name) DYNARRAY_CONCAT1(DYNARRAY_PREFIX, name)
147e83
+
147e83
+/* Address of the scratch buffer if any.  */
147e83
+#if DYNARRAY_HAVE_SCRATCH
147e83
+# define DYNARRAY_SCRATCH(list) (list)->scratch
147e83
+#else
147e83
+# define DYNARRAY_SCRATCH(list) NULL
147e83
+#endif
147e83
+
147e83
+/* Internal use only: Helper functions.  */
147e83
+
147e83
+/* Internal function.  Call DYNARRAY_ELEMENT_FREE with the array
147e83
+   elements.  Name mangling needed due to the DYNARRAY_ELEMENT_FREE
147e83
+   macro expansion.  */
147e83
+static inline void
147e83
+DYNARRAY_NAME (free__elements__) (DYNARRAY_ELEMENT *__dynarray_array,
147e83
+                                  size_t __dynarray_used)
147e83
+{
147e83
+#ifdef DYNARRAY_ELEMENT_FREE
147e83
+  for (size_t __dynarray_i = 0; __dynarray_i < __dynarray_used; ++__dynarray_i)
147e83
+    DYNARRAY_ELEMENT_FREE (&__dynarray_array[__dynarray_i]);
147e83
+#endif /* DYNARRAY_ELEMENT_FREE */
147e83
+}
147e83
+
147e83
+/* Internal function.  Free the non-scratch array allocation.  */
147e83
+static inline void
147e83
+DYNARRAY_NAME (free__array__) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+#if DYNARRAY_HAVE_SCRATCH
147e83
+  if (list->dynarray_header.array != list->scratch)
147e83
+    free (list->dynarray_header.array);
147e83
+#else
147e83
+  free (list->dynarray_header.array);
147e83
+#endif
147e83
+}
147e83
+
147e83
+/* Public functions.  */
147e83
+
147e83
+/* Initialize a dynamic array object.  This must be called before any
147e83
+   use of the object.  */
147e83
+__attribute__ ((nonnull (1)))
147e83
+static void
147e83
+DYNARRAY_NAME (init) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  list->dynarray_header.used = 0;
147e83
+  list->dynarray_header.allocated = DYNARRAY_INITIAL_SIZE;
147e83
+  list->dynarray_header.array = DYNARRAY_SCRATCH (list);
147e83
+}
147e83
+
147e83
+/* Deallocate the dynamic array and its elements.  */
147e83
+__attribute__ ((unused, nonnull (1)))
147e83
+static void
147e83
+DYNARRAY_NAME (free) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  DYNARRAY_NAME (free__elements__)
147e83
+    (list->dynarray_header.array, list->dynarray_header.used);
147e83
+  DYNARRAY_NAME (free__array__) (list);
147e83
+  DYNARRAY_NAME (init) (list);
147e83
+}
147e83
+
147e83
+/* Return true if the dynamic array is in an error state.  */
147e83
+__attribute__ ((nonnull (1)))
147e83
+static inline bool
147e83
+DYNARRAY_NAME (has_failed) (const struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  return list->dynarray_header.allocated == __dynarray_error_marker ();
147e83
+}
147e83
+
147e83
+/* Mark the dynamic array as failed.  All elements are deallocated as
147e83
+   a side effect.  */
147e83
+__attribute__ ((nonnull (1)))
147e83
+static void
147e83
+DYNARRAY_NAME (mark_failed) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  DYNARRAY_NAME (free__elements__)
147e83
+    (list->dynarray_header.array, list->dynarray_header.used);
147e83
+  DYNARRAY_NAME (free__array__) (list);
147e83
+  list->dynarray_header.array = DYNARRAY_SCRATCH (list);
147e83
+  list->dynarray_header.used = 0;
147e83
+  list->dynarray_header.allocated = __dynarray_error_marker ();
147e83
+}
147e83
+
147e83
+/* Return the number of elements which have been added to the dynamic
147e83
+   array.  */
147e83
+__attribute__ ((nonnull (1)))
147e83
+static inline size_t
147e83
+DYNARRAY_NAME (size) (const struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  return list->dynarray_header.used;
147e83
+}
147e83
+
147e83
+/* Return a pointer to the array element at INDEX.  Terminate the
147e83
+   process if INDEX is out of bounds.  */
147e83
+__attribute__ ((nonnull (1)))
147e83
+static inline DYNARRAY_ELEMENT *
147e83
+DYNARRAY_NAME (at) (struct DYNARRAY_STRUCT *list, size_t index)
147e83
+{
147e83
+  if (__glibc_unlikely (index >= DYNARRAY_NAME (size) (list)))
147e83
+    __libc_dynarray_at_failure (DYNARRAY_NAME (size) (list), index);
147e83
+  return list->dynarray_header.array + index;
147e83
+}
147e83
+
147e83
+/* Return a pointer to the first array element, if any.  For a
147e83
+   zero-length array, the pointer can be NULL even though the dynamic
147e83
+   array has not entered the failure state.  */
147e83
+__attribute__ ((nonnull (1)))
147e83
+static inline DYNARRAY_ELEMENT *
147e83
+DYNARRAY_NAME (begin) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  return list->dynarray_header.array;
147e83
+}
147e83
+
147e83
+/* Return a pointer one element past the last array element.  For a
147e83
+   zero-length array, the pointer can be NULL even though the dynamic
147e83
+   array has not entered the failure state.  */
147e83
+__attribute__ ((nonnull (1)))
147e83
+static inline DYNARRAY_ELEMENT *
147e83
+DYNARRAY_NAME (end) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  return list->dynarray_header.array + list->dynarray_header.used;
147e83
+}
147e83
+
147e83
+/* Internal function.  Slow path for the add function below.  */
147e83
+static void
147e83
+DYNARRAY_NAME (add__) (struct DYNARRAY_STRUCT *list, DYNARRAY_ELEMENT item)
147e83
+{
147e83
+  if (__glibc_unlikely
147e83
+      (!__libc_dynarray_emplace_enlarge (&list->dynarray_abstract,
147e83
+                                         DYNARRAY_SCRATCH (list),
147e83
+                                         sizeof (DYNARRAY_ELEMENT))))
147e83
+    {
147e83
+      DYNARRAY_NAME (mark_failed) (list);
147e83
+      return;
147e83
+    }
147e83
+
147e83
+  /* Copy the new element and increase the array length.  */
147e83
+  list->dynarray_header.array[list->dynarray_header.used++] = item;
147e83
+}
147e83
+
147e83
+/* Add ITEM at the end of the array, enlarging it by one element.
147e83
+   Mark *LIST as failed if the dynamic array allocation size cannot be
147e83
+   increased.  */
147e83
+__attribute__ ((unused, nonnull (1)))
147e83
+static inline void
147e83
+DYNARRAY_NAME (add) (struct DYNARRAY_STRUCT *list, DYNARRAY_ELEMENT item)
147e83
+{
147e83
+  /* Do nothing in case of previous error.  */
147e83
+  if (DYNARRAY_NAME (has_failed) (list))
147e83
+    return;
147e83
+
147e83
+  /* Enlarge the array if necessary.  */
147e83
+  if (__glibc_unlikely (list->dynarray_header.used
147e83
+                        == list->dynarray_header.allocated))
147e83
+    {
147e83
+      DYNARRAY_NAME (add__) (list, item);
147e83
+      return;
147e83
+    }
147e83
+
147e83
+  /* Copy the new element and increase the array length.  */
147e83
+  list->dynarray_header.array[list->dynarray_header.used++] = item;
147e83
+}
147e83
+
147e83
+/* Internal function.  Building block for the emplace functions below.
147e83
+   Assumes space for one more element in *LIST.  */
147e83
+static inline DYNARRAY_ELEMENT *
147e83
+DYNARRAY_NAME (emplace__tail__) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  DYNARRAY_ELEMENT *result
147e83
+    = &list->dynarray_header.array[list->dynarray_header.used];
147e83
+  ++list->dynarray_header.used;
147e83
+#if defined (DYNARRAY_ELEMENT_INIT)
147e83
+  DYNARRAY_ELEMENT_INIT (result);
147e83
+#elif defined (DYNARRAY_ELEMENT_FREE)
147e83
+  memset (result, 0, sizeof (*result));
147e83
+#endif
147e83
+  return result;
147e83
+}
147e83
+
147e83
+/* Internal function.  Slow path for the emplace function below.  */
147e83
+static DYNARRAY_ELEMENT *
147e83
+DYNARRAY_NAME (emplace__) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  if (__glibc_unlikely
147e83
+      (!__libc_dynarray_emplace_enlarge (&list->dynarray_abstract,
147e83
+                                         DYNARRAY_SCRATCH (list),
147e83
+                                         sizeof (DYNARRAY_ELEMENT))))
147e83
+    {
147e83
+      DYNARRAY_NAME (mark_failed) (list);
147e83
+      return NULL;
147e83
+    }
147e83
+  return DYNARRAY_NAME (emplace__tail__) (list);
147e83
+}
147e83
+
147e83
+/* Allocate a place for a new element in *LIST and return a pointer to
147e83
+   it.  The pointer can be NULL if the dynamic array cannot be
147e83
+   enlarged due to a memory allocation failure.  */
147e83
+__attribute__ ((unused, warn_unused_result, nonnull (1)))
147e83
+static
147e83
+/* Avoid inlining with the larger initialization code.  */
147e83
+#if !(defined (DYNARRAY_ELEMENT_INIT) || defined (DYNARRAY_ELEMENT_FREE))
147e83
+inline
147e83
+#endif
147e83
+DYNARRAY_ELEMENT *
147e83
+DYNARRAY_NAME (emplace) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  /* Do nothing in case of previous error.  */
147e83
+  if (DYNARRAY_NAME (has_failed) (list))
147e83
+    return NULL;
147e83
+
147e83
+  /* Enlarge the array if necessary.  */
147e83
+  if (__glibc_unlikely (list->dynarray_header.used
147e83
+                        == list->dynarray_header.allocated))
147e83
+    return (DYNARRAY_NAME (emplace__) (list));
147e83
+  return DYNARRAY_NAME (emplace__tail__) (list);
147e83
+}
147e83
+
147e83
+/* Change the size of *LIST to SIZE.  If SIZE is larger than the
147e83
+   existing size, new elements are added (which can be initialized).
147e83
+   Otherwise, the list is truncated, and elements are freed.  Return
147e83
+   false on memory allocation failure (and mark *LIST as failed).  */
147e83
+__attribute__ ((unused, nonnull (1)))
147e83
+static bool
147e83
+DYNARRAY_NAME (resize) (struct DYNARRAY_STRUCT *list, size_t size)
147e83
+{
147e83
+  if (size > list->dynarray_header.used)
147e83
+    {
147e83
+      bool ok;
147e83
+#if defined (DYNARRAY_ELEMENT_INIT)
147e83
+      /* The new elements have to be initialized.  */
147e83
+      size_t old_size = list->dynarray_header.used;
147e83
+      ok = __libc_dynarray_resize (&list->dynarray_abstract,
147e83
+                                   size, DYNARRAY_SCRATCH (list),
147e83
+                                   sizeof (DYNARRAY_ELEMENT));
147e83
+      if (ok)
147e83
+        for (size_t i = old_size; i < size; ++i)
147e83
+          {
147e83
+            DYNARRAY_ELEMENT_INIT (&list->dynarray_header.array[i]);
147e83
+          }
147e83
+#elif defined (DYNARRAY_ELEMENT_FREE)
147e83
+      /* Zero initialization is needed so that the elements can be
147e83
+         safely freed.  */
147e83
+      ok = __libc_dynarray_resize_clear
147e83
+        (&list->dynarray_abstract, size,
147e83
+         DYNARRAY_SCRATCH (list), sizeof (DYNARRAY_ELEMENT));
147e83
+#else
147e83
+      ok =  __libc_dynarray_resize (&list->dynarray_abstract,
147e83
+                                    size, DYNARRAY_SCRATCH (list),
147e83
+                                    sizeof (DYNARRAY_ELEMENT));
147e83
+#endif
147e83
+      if (__glibc_unlikely (!ok))
147e83
+        DYNARRAY_NAME (mark_failed) (list);
147e83
+      return ok;
147e83
+    }
147e83
+  else
147e83
+    {
147e83
+      /* The list has shrunk in size.  Free the removed elements.  */
147e83
+      DYNARRAY_NAME (free__elements__)
147e83
+        (list->dynarray_header.array + size,
147e83
+         list->dynarray_header.used - size);
147e83
+      list->dynarray_header.used = size;
147e83
+      return true;
147e83
+    }
147e83
+}
147e83
+
147e83
+/* Remove the last element of LIST if it is present.  */
147e83
+__attribute__ ((unused, nonnull (1)))
147e83
+static void
147e83
+DYNARRAY_NAME (remove_last) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  /* used > 0 implies that the array is the non-failed state.  */
147e83
+  if (list->dynarray_header.used > 0)
147e83
+    {
147e83
+      size_t new_length = list->dynarray_header.used - 1;
147e83
+#ifdef DYNARRAY_ELEMENT_FREE
147e83
+      DYNARRAY_ELEMENT_FREE (&list->dynarray_header.array[new_length]);
147e83
+#endif
147e83
+      list->dynarray_header.used = new_length;
147e83
+    }
147e83
+}
147e83
+
147e83
+/* Remove all elements from the list.  The elements are freed, but the
147e83
+   list itself is not.  */
147e83
+__attribute__ ((unused, nonnull (1)))
147e83
+static void
147e83
+DYNARRAY_NAME (clear) (struct DYNARRAY_STRUCT *list)
147e83
+{
147e83
+  /* free__elements__ does nothing if the list is in the failed
147e83
+     state.  */
147e83
+  DYNARRAY_NAME (free__elements__)
147e83
+    (list->dynarray_header.array, list->dynarray_header.used);
147e83
+  list->dynarray_header.used = 0;
147e83
+}
147e83
+
147e83
+#ifdef DYNARRAY_FINAL_TYPE
147e83
+/* Transfer the dynamic array to a permanent location at *RESULT.
147e83
+   Returns true on success on false on allocation failure.  In either
147e83
+   case, *LIST is re-initialized and can be reused.  A NULL pointer is
147e83
+   stored in *RESULT if LIST refers to an empty list.  On success, the
147e83
+   pointer in *RESULT is heap-allocated and must be deallocated using
147e83
+   free.  */
147e83
+__attribute__ ((unused, warn_unused_result, nonnull (1, 2)))
147e83
+static bool
147e83
+DYNARRAY_NAME (finalize) (struct DYNARRAY_STRUCT *list,
147e83
+                          DYNARRAY_FINAL_TYPE *result)
147e83
+{
147e83
+  struct dynarray_finalize_result res;
147e83
+  if (__libc_dynarray_finalize (&list->dynarray_abstract,
147e83
+                                DYNARRAY_SCRATCH (list),
147e83
+                                sizeof (DYNARRAY_ELEMENT), &res))
147e83
+    {
147e83
+      /* On success, the result owns all the data.  */
147e83
+      DYNARRAY_NAME (init) (list);
147e83
+      *result = (DYNARRAY_FINAL_TYPE) { res.array, res.length };
147e83
+      return true;
147e83
+    }
147e83
+  else
147e83
+    {
147e83
+      /* On error, we need to free all data.  */
147e83
+      DYNARRAY_NAME (free) (list);
147e83
+      errno = ENOMEM;
147e83
+      return false;
147e83
+    }
147e83
+}
147e83
+#else /* !DYNARRAY_FINAL_TYPE */
147e83
+/* Transfer the dynamic array to a heap-allocated array and return a
147e83
+   pointer to it.  The pointer is NULL if memory allocation fails, or
147e83
+   if the array is empty, so this function should be used only for
147e83
+   arrays which are known not be empty (usually because they always
147e83
+   have a sentinel at the end).  If LENGTHP is not NULL, the array
147e83
+   length is written to *LENGTHP.  *LIST is re-initialized and can be
147e83
+   reused.  */
147e83
+__attribute__ ((unused, warn_unused_result, nonnull (1)))
147e83
+static DYNARRAY_ELEMENT *
147e83
+DYNARRAY_NAME (finalize) (struct DYNARRAY_STRUCT *list, size_t *lengthp)
147e83
+{
147e83
+  struct dynarray_finalize_result res;
147e83
+  if (__libc_dynarray_finalize (&list->dynarray_abstract,
147e83
+                                DYNARRAY_SCRATCH (list),
147e83
+                                sizeof (DYNARRAY_ELEMENT), &res))
147e83
+    {
147e83
+      /* On success, the result owns all the data.  */
147e83
+      DYNARRAY_NAME (init) (list);
147e83
+      if (lengthp != NULL)
147e83
+        *lengthp = res.length;
147e83
+      return res.array;
147e83
+    }
147e83
+  else
147e83
+    {
147e83
+      /* On error, we need to free all data.  */
147e83
+      DYNARRAY_NAME (free) (list);
147e83
+      errno = ENOMEM;
147e83
+      return NULL;
147e83
+    }
147e83
+}
147e83
+#endif /* !DYNARRAY_FINAL_TYPE */
147e83
+
147e83
+/* Undo macro definitions.  */
147e83
+
147e83
+#undef DYNARRAY_CONCAT0
147e83
+#undef DYNARRAY_CONCAT1
147e83
+#undef DYNARRAY_NAME
147e83
+#undef DYNARRAY_SCRATCH
147e83
+#undef DYNARRAY_HAVE_SCRATCH
147e83
+
147e83
+#undef DYNARRAY_STRUCT
147e83
+#undef DYNARRAY_ELEMENT
147e83
+#undef DYNARRAY_PREFIX
147e83
+#undef DYNARRAY_ELEMENT_FREE
147e83
+#undef DYNARRAY_ELEMENT_INIT
147e83
+#undef DYNARRAY_INITIAL_SIZE
147e83
+#undef DYNARRAY_FINAL_TYPE
147e83
diff --git a/malloc/dynarray.h b/malloc/dynarray.h
147e83
new file mode 100644
147e83
index 0000000000000000..5888bcbc1d4ae9bf
147e83
--- /dev/null
147e83
+++ b/malloc/dynarray.h
147e83
@@ -0,0 +1,179 @@
147e83
+/* Type-safe arrays which grow dynamically.  Shared definitions.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+/* To use the dynarray facility, you need to include
147e83
+   <malloc/dynarray-skeleton.c> and define the parameter macros
147e83
+   documented in that file.
147e83
+
147e83
+   A minimal example which provides a growing list of integers can be
147e83
+   defined like this:
147e83
+
147e83
+     struct int_array
147e83
+     {
147e83
+       // Pointer to result array followed by its length,
147e83
+       // as required by DYNARRAY_FINAL_TYPE.
147e83
+       int *array;
147e83
+       size_t length;
147e83
+     };
147e83
+
147e83
+     #define DYNARRAY_STRUCT dynarray_int
147e83
+     #define DYNARRAY_ELEMENT int
147e83
+     #define DYNARRAY_PREFIX dynarray_int_
147e83
+     #define DYNARRAY_FINAL_TYPE struct int_array
147e83
+     #include <malloc/dynarray-skeleton.c>
147e83
+
147e83
+   To create a three-element array with elements 1, 2, 3, use this
147e83
+   code:
147e83
+
147e83
+     struct dynarray_int dyn;
147e83
+     dynarray_int_init (&dyn);
147e83
+     for (int i = 1; i <= 3; ++i)
147e83
+       {
147e83
+         int *place = dynarray_int_emplace (&dyn);
147e83
+         assert (place != NULL);
147e83
+         *place = i;
147e83
+       }
147e83
+     struct int_array result;
147e83
+     bool ok = dynarray_int_finalize (&dyn, &result);
147e83
+     assert (ok);
147e83
+     assert (result.length == 3);
147e83
+     assert (result.array[0] == 1);
147e83
+     assert (result.array[1] == 2);
147e83
+     assert (result.array[2] == 3);
147e83
+     free (result.array);
147e83
+
147e83
+   If the elements contain resources which must be freed, define
147e83
+   DYNARRAY_ELEMENT_FREE appropriately, like this:
147e83
+
147e83
+     struct str_array
147e83
+     {
147e83
+       char **array;
147e83
+       size_t length;
147e83
+     };
147e83
+
147e83
+     #define DYNARRAY_STRUCT dynarray_str
147e83
+     #define DYNARRAY_ELEMENT char *
147e83
+     #define DYNARRAY_ELEMENT_FREE(ptr) free (*ptr)
147e83
+     #define DYNARRAY_PREFIX dynarray_str_
147e83
+     #define DYNARRAY_FINAL_TYPE struct str_array
147e83
+     #include <malloc/dynarray-skeleton.c>
147e83
+
147e83
+   Compared to scratch buffers, dynamic arrays have the following
147e83
+   features:
147e83
+
147e83
+   - They have an element type, and are not just an untyped buffer of
147e83
+     bytes.
147e83
+
147e83
+   - When growing, previously stored elements are preserved.  (It is
147e83
+     expected that scratch_buffer_grow_preserve and
147e83
+     scratch_buffer_set_array_size eventually go away because all
147e83
+     current users are moved to dynamic arrays.)
147e83
+
147e83
+   - Scratch buffers have a more aggressive growth policy because
147e83
+     growing them typically means a retry of an operation (across an
147e83
+     NSS service module boundary), which is expensive.
147e83
+
147e83
+   - For the same reason, scratch buffers have a much larger initial
147e83
+     stack allocation.  */
147e83
+
147e83
+#ifndef _DYNARRAY_H
147e83
+#define _DYNARRAY_H
147e83
+
147e83
+#include <stdbool.h>
147e83
+#include <stddef.h>
147e83
+#include <string.h>
147e83
+
147e83
+struct dynarray_header
147e83
+{
147e83
+  size_t used;
147e83
+  size_t allocated;
147e83
+  void *array;
147e83
+};
147e83
+
147e83
+/* Marker used in the allocated member to indicate that an error was
147e83
+   encountered.  */
147e83
+static inline size_t
147e83
+__dynarray_error_marker (void)
147e83
+{
147e83
+  return -1;
147e83
+}
147e83
+
147e83
+/* Internal function.  See the has_failed function in
147e83
+   dynarray-skeleton.c.  */
147e83
+static inline bool
147e83
+__dynarray_error (struct dynarray_header *list)
147e83
+{
147e83
+  return list->allocated == __dynarray_error_marker ();
147e83
+}
147e83
+
147e83
+/* Internal function.  Enlarge the dynamically allocated area of the
147e83
+   array to make room for one more element.  SCRATCH is a pointer to
147e83
+   the scratch area (which is not heap-allocated and must not be
147e83
+   freed).  ELEMENT_SIZE is the size, in bytes, of one element.
147e83
+   Return false on failure, true on success.  */
147e83
+bool __libc_dynarray_emplace_enlarge (struct dynarray_header *,
147e83
+                                      void *scratch, size_t element_size);
147e83
+
147e83
+/* Internal function.  Enlarge the dynamically allocated area of the
147e83
+   array to make room for at least SIZE elements (which must be larger
147e83
+   than the existing used part of the dynamic array).  SCRATCH is a
147e83
+   pointer to the scratch area (which is not heap-allocated and must
147e83
+   not be freed).  ELEMENT_SIZE is the size, in bytes, of one element.
147e83
+   Return false on failure, true on success.  */
147e83
+bool __libc_dynarray_resize (struct dynarray_header *, size_t size,
147e83
+                             void *scratch, size_t element_size);
147e83
+
147e83
+/* Internal function.  Like __libc_dynarray_resize, but clear the new
147e83
+   part of the dynamic array.  */
147e83
+bool __libc_dynarray_resize_clear (struct dynarray_header *, size_t size,
147e83
+                                   void *scratch, size_t element_size);
147e83
+
147e83
+/* Internal type.  */
147e83
+struct dynarray_finalize_result
147e83
+{
147e83
+  void *array;
147e83
+  size_t length;
147e83
+};
147e83
+
147e83
+/* Internal function.  Copy the dynamically-allocated area to an
147e83
+   explicitly-sized heap allocation.  SCRATCH is a pointer to the
147e83
+   embedded scratch space.  ELEMENT_SIZE is the size, in bytes, of the
147e83
+   element type.  On success, true is returned, and pointer and length
147e83
+   are written to *RESULT.  On failure, false is returned.  The caller
147e83
+   has to take care of some of the memory management; this function is
147e83
+   expected to be called from dynarray-skeleton.c.  */
147e83
+bool __libc_dynarray_finalize (struct dynarray_header *list, void *scratch,
147e83
+                               size_t element_size,
147e83
+                               struct dynarray_finalize_result *result);
147e83
+
147e83
+
147e83
+/* Internal function.  Terminate the process after an index error.
147e83
+   SIZE is the number of elements of the dynamic array.  INDEX is the
147e83
+   lookup index which triggered the failure.  */
147e83
+void __libc_dynarray_at_failure (size_t size, size_t index)
147e83
+  __attribute__ ((noreturn));
147e83
+
147e83
+#ifndef _ISOMAC
147e83
+libc_hidden_proto (__libc_dynarray_emplace_enlarge)
147e83
+libc_hidden_proto (__libc_dynarray_resize)
147e83
+libc_hidden_proto (__libc_dynarray_resize_clear)
147e83
+libc_hidden_proto (__libc_dynarray_finalize)
147e83
+libc_hidden_proto (__libc_dynarray_at_failure)
147e83
+#endif
147e83
+
147e83
+#endif /* _DYNARRAY_H */
147e83
diff --git a/malloc/dynarray_at_failure.c b/malloc/dynarray_at_failure.c
147e83
new file mode 100644
147e83
index 0000000000000000..fcc06f030b035165
147e83
--- /dev/null
147e83
+++ b/malloc/dynarray_at_failure.c
147e83
@@ -0,0 +1,31 @@
147e83
+/* Report an dynamic array index out of bounds condition.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+#include <dynarray.h>
147e83
+#include <stdio.h>
147e83
+
147e83
+void
147e83
+__libc_dynarray_at_failure (size_t size, size_t index)
147e83
+{
147e83
+  char buf[200];
147e83
+  __snprintf (buf, sizeof (buf), "Fatal glibc error: "
147e83
+              "array index %zu not less than array length %zu\n",
147e83
+              index, size);
147e83
+ __libc_fatal (buf);
147e83
+}
147e83
+libc_hidden_def (__libc_dynarray_at_failure)
147e83
diff --git a/malloc/dynarray_emplace_enlarge.c b/malloc/dynarray_emplace_enlarge.c
147e83
new file mode 100644
147e83
index 0000000000000000..a15245f4cb3d4288
147e83
--- /dev/null
147e83
+++ b/malloc/dynarray_emplace_enlarge.c
147e83
@@ -0,0 +1,73 @@
147e83
+/* Increase the size of a dynamic array in preparation of an emplace operation.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+#include <dynarray.h>
147e83
+#include <errno.h>
147e83
+#include <malloc-internal.h>
147e83
+#include <stdlib.h>
147e83
+#include <string.h>
147e83
+
147e83
+bool
147e83
+__libc_dynarray_emplace_enlarge (struct dynarray_header *list,
147e83
+                                 void *scratch, size_t element_size)
147e83
+{
147e83
+  size_t new_allocated;
147e83
+  if (list->allocated == 0)
147e83
+    {
147e83
+      /* No scratch buffer provided.  Choose a reasonable default
147e83
+         size.  */
147e83
+      if (element_size < 4)
147e83
+        new_allocated = 16;
147e83
+      else if (element_size < 8)
147e83
+        new_allocated = 8;
147e83
+      else
147e83
+        new_allocated = 4;
147e83
+    }
147e83
+  else
147e83
+    /* Increase the allocated size, using an exponential growth
147e83
+       policy.  */
147e83
+    {
147e83
+      new_allocated = list->allocated + list->allocated / 2 + 1;
147e83
+      if (new_allocated <= list->allocated)
147e83
+        {
147e83
+          /* Overflow.  */
147e83
+          __set_errno (ENOMEM);
147e83
+          return false;
147e83
+        }
147e83
+    }
147e83
+
147e83
+  size_t new_size;
147e83
+  if (check_mul_overflow_size_t (new_allocated, element_size, &new_size))
147e83
+    return false;
147e83
+  void *new_array;
147e83
+  if (list->array == scratch)
147e83
+    {
147e83
+      /* The previous array was not heap-allocated.  */
147e83
+      new_array = malloc (new_size);
147e83
+      if (new_array != NULL && list->array != NULL)
147e83
+        memcpy (new_array, list->array, list->used * element_size);
147e83
+    }
147e83
+  else
147e83
+    new_array = realloc (list->array, new_size);
147e83
+  if (new_array == NULL)
147e83
+    return false;
147e83
+  list->array = new_array;
147e83
+  list->allocated = new_allocated;
147e83
+  return true;
147e83
+}
147e83
+libc_hidden_def (__libc_dynarray_emplace_enlarge)
147e83
diff --git a/malloc/dynarray_finalize.c b/malloc/dynarray_finalize.c
147e83
new file mode 100644
147e83
index 0000000000000000..6dd8705382c73ae8
147e83
--- /dev/null
147e83
+++ b/malloc/dynarray_finalize.c
147e83
@@ -0,0 +1,62 @@
147e83
+/* Copy the dynamically-allocated area to an explicitly-sized heap allocation.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+#include <dynarray.h>
147e83
+#include <stdlib.h>
147e83
+#include <string.h>
147e83
+
147e83
+bool
147e83
+__libc_dynarray_finalize (struct dynarray_header *list,
147e83
+                          void *scratch, size_t element_size,
147e83
+                          struct dynarray_finalize_result *result)
147e83
+{
147e83
+  if (__dynarray_error (list))
147e83
+    /* The caller will reported the deferred error.  */
147e83
+    return false;
147e83
+
147e83
+  size_t used = list->used;
147e83
+
147e83
+  /* Empty list.  */
147e83
+  if (used == 0)
147e83
+    {
147e83
+      /* An empty list could still be backed by a heap-allocated
147e83
+         array.  Free it if necessary.  */
147e83
+      if (list->array != scratch)
147e83
+        free (list->array);
147e83
+      *result = (struct dynarray_finalize_result) { NULL, 0 };
147e83
+      return true;
147e83
+    }
147e83
+
147e83
+  size_t allocation_size = used * element_size;
147e83
+  void *heap_array = malloc (allocation_size);
147e83
+  if (heap_array != NULL)
147e83
+    {
147e83
+      /* The new array takes ownership of the strings.  */
147e83
+      if (list->array != NULL)
147e83
+        memcpy (heap_array, list->array, allocation_size);
147e83
+      if (list->array != scratch)
147e83
+        free (list->array);
147e83
+      *result = (struct dynarray_finalize_result)
147e83
+        { .array = heap_array, .length = used };
147e83
+      return true;
147e83
+    }
147e83
+  else
147e83
+    /* The caller will perform the freeing operation.  */
147e83
+    return false;
147e83
+}
147e83
+libc_hidden_def (__libc_dynarray_finalize)
147e83
diff --git a/malloc/dynarray_resize.c b/malloc/dynarray_resize.c
147e83
new file mode 100644
147e83
index 0000000000000000..63c981bf61f67145
147e83
--- /dev/null
147e83
+++ b/malloc/dynarray_resize.c
147e83
@@ -0,0 +1,64 @@
147e83
+/* Increase the size of a dynamic array.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+#include <dynarray.h>
147e83
+#include <errno.h>
147e83
+#include <malloc-internal.h>
147e83
+#include <stdlib.h>
147e83
+#include <string.h>
147e83
+
147e83
+bool
147e83
+__libc_dynarray_resize (struct dynarray_header *list, size_t size,
147e83
+                        void *scratch, size_t element_size)
147e83
+{
147e83
+  /* The existing allocation provides sufficient room.  */
147e83
+  if (size <= list->allocated)
147e83
+    {
147e83
+      list->used = size;
147e83
+      return true;
147e83
+    }
147e83
+
147e83
+  /* Otherwise, use size as the new allocation size.  The caller is
147e83
+     expected to provide the final size of the array, so there is no
147e83
+     over-allocation here.  */
147e83
+
147e83
+  size_t new_size_bytes;
147e83
+  if (check_mul_overflow_size_t (size, element_size, &new_size_bytes))
147e83
+    {
147e83
+      /* Overflow.  */
147e83
+      __set_errno (ENOMEM);
147e83
+      return false;
147e83
+    }
147e83
+  void *new_array;
147e83
+  if (list->array == scratch)
147e83
+    {
147e83
+      /* The previous array was not heap-allocated.  */
147e83
+      new_array = malloc (new_size_bytes);
147e83
+      if (new_array != NULL && list->array != NULL)
147e83
+        memcpy (new_array, list->array, list->used * element_size);
147e83
+    }
147e83
+  else
147e83
+    new_array = realloc (list->array, new_size_bytes);
147e83
+  if (new_array == NULL)
147e83
+    return false;
147e83
+  list->array = new_array;
147e83
+  list->allocated = size;
147e83
+  list->used = size;
147e83
+  return true;
147e83
+}
147e83
+libc_hidden_def (__libc_dynarray_resize)
147e83
diff --git a/malloc/dynarray_resize_clear.c b/malloc/dynarray_resize_clear.c
147e83
new file mode 100644
147e83
index 0000000000000000..0c4ced1d38b77918
147e83
--- /dev/null
147e83
+++ b/malloc/dynarray_resize_clear.c
147e83
@@ -0,0 +1,35 @@
147e83
+/* Increase the size of a dynamic array and clear the new part.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+#include <dynarray.h>
147e83
+#include <stdlib.h>
147e83
+#include <string.h>
147e83
+
147e83
+bool
147e83
+__libc_dynarray_resize_clear (struct dynarray_header *list, size_t size,
147e83
+                              void *scratch, size_t element_size)
147e83
+{
147e83
+  size_t old_size = list->used;
147e83
+  if (!__libc_dynarray_resize (list, size, scratch, element_size))
147e83
+    return false;
147e83
+  /* __libc_dynarray_resize already checked for overflow.  */
147e83
+  memset (list->array + (old_size * element_size), 0,
147e83
+          (size - old_size) * element_size);
147e83
+  return true;
147e83
+}
147e83
+libc_hidden_def (__libc_dynarray_resize_clear)
147e83
diff --git a/malloc/tst-dynarray-at-fail.c b/malloc/tst-dynarray-at-fail.c
147e83
new file mode 100644
147e83
index 0000000000000000..8ba5f92b58141c52
147e83
--- /dev/null
147e83
+++ b/malloc/tst-dynarray-at-fail.c
147e83
@@ -0,0 +1,125 @@
147e83
+/* Test reporting of out-of-bounds access for dynamic arrays.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+#include "tst-dynarray-shared.h"
147e83
+
147e83
+#include <signal.h>
147e83
+#include <stdint.h>
147e83
+#include <string.h>
147e83
+#include <support/capture_subprocess.h>
147e83
+#include <support/check.h>
147e83
+
147e83
+/* Run CALLBACK and check that the data on standard error equals
147e83
+   EXPECTED.  */
147e83
+static void
147e83
+check (const char *test, void (*callback) (void *), size_t index,
147e83
+       const char *expected)
147e83
+{
147e83
+  struct support_capture_subprocess result
147e83
+    = support_capture_subprocess (callback, &index);
147e83
+  if (strcmp (result.err.buffer, expected) != 0)
147e83
+    {
147e83
+      support_record_failure ();
147e83
+      printf ("error: test %s (%zu) unexpected standard error data\n"
147e83
+              "  expected: %s\n"
147e83
+              "  actual:   %s\n",
147e83
+              test, index, expected, result.err.buffer);
147e83
+    }
147e83
+  TEST_VERIFY (strlen (result.out.buffer) == 0);
147e83
+  TEST_VERIFY (WIFSIGNALED (result.status));
147e83
+  if (WIFSIGNALED (result.status))
147e83
+    TEST_VERIFY (WTERMSIG (result.status) == SIGABRT);
147e83
+  support_capture_subprocess_free (&result);
147e83
+}
147e83
+
147e83
+/* Try indexing an empty array.  */
147e83
+static void
147e83
+test_empty (void *closure)
147e83
+{
147e83
+  size_t *pindex = closure;
147e83
+  struct dynarray_int dyn;
147e83
+  dynarray_int_init (&dyn);
147e83
+  dynarray_int_at (&dyn, *pindex);
147e83
+}
147e83
+
147e83
+/* Try indexing a one-element array.  */
147e83
+static void
147e83
+test_one (void *closure)
147e83
+{
147e83
+  size_t *pindex = closure;
147e83
+  struct dynarray_int dyn;
147e83
+  dynarray_int_init (&dyn);
147e83
+  TEST_VERIFY (dynarray_int_resize (&dyn, 1));
147e83
+  dynarray_int_at (&dyn, *pindex);
147e83
+}
147e83
+
147e83
+/* Try indexing a longer array.  */
147e83
+static void
147e83
+test_many (void *closure)
147e83
+{
147e83
+  size_t *pindex = closure;
147e83
+  struct dynarray_int dyn;
147e83
+  dynarray_int_init (&dyn);
147e83
+  TEST_VERIFY (dynarray_int_resize (&dyn, 5371));
147e83
+  dynarray_int_at (&dyn, *pindex);
147e83
+}
147e83
+
147e83
+/* (size_t) -1 for use in string literals.  */
147e83
+#if __WORDSIZE == 32
147e83
+# define MINUS_1 "4294967295"
147e83
+#elif __WORDSIZE == 64
147e83
+# define MINUS_1 "18446744073709551615"
147e83
+#else
147e83
+# error "unknown value for __WORDSIZE"
147e83
+#endif
147e83
+
147e83
+static int
147e83
+do_test (void)
147e83
+{
147e83
+  TEST_VERIFY (setenv ("LIBC_FATAL_STDERR_", "1", 1) == 0);
147e83
+
147e83
+  check ("test_empty", test_empty, 0,
147e83
+         "Fatal glibc error: array index 0 not less than array length 0\n");
147e83
+  check ("test_empty", test_empty, 1,
147e83
+         "Fatal glibc error: array index 1 not less than array length 0\n");
147e83
+  check ("test_empty", test_empty, -1,
147e83
+         "Fatal glibc error: array index " MINUS_1
147e83
+         " not less than array length 0\n");
147e83
+
147e83
+  check ("test_one", test_one, 1,
147e83
+         "Fatal glibc error: array index 1 not less than array length 1\n");
147e83
+  check ("test_one", test_one, 2,
147e83
+         "Fatal glibc error: array index 2 not less than array length 1\n");
147e83
+  check ("test_one", test_one, -1,
147e83
+         "Fatal glibc error: array index " MINUS_1
147e83
+         " not less than array length 1\n");
147e83
+
147e83
+  check ("test_many", test_many, 5371,
147e83
+         "Fatal glibc error: array index 5371"
147e83
+         " not less than array length 5371\n");
147e83
+  check ("test_many", test_many, 5372,
147e83
+         "Fatal glibc error: array index 5372"
147e83
+         " not less than array length 5371\n");
147e83
+  check ("test_many", test_many, -1,
147e83
+         "Fatal glibc error: array index " MINUS_1
147e83
+         " not less than array length 5371\n");
147e83
+
147e83
+  return 0;
147e83
+}
147e83
+
147e83
+#include <support/test-driver.c>
147e83
diff --git a/malloc/tst-dynarray-fail.c b/malloc/tst-dynarray-fail.c
147e83
new file mode 100644
147e83
index 0000000000000000..508dbae93e6bce31
147e83
--- /dev/null
147e83
+++ b/malloc/tst-dynarray-fail.c
147e83
@@ -0,0 +1,418 @@
147e83
+/* Test allocation failures with dynamic arrays.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+/* This test is separate from tst-dynarray because it cannot run under
147e83
+   valgrind.  */
147e83
+
147e83
+#include "tst-dynarray-shared.h"
147e83
+
147e83
+#include <mcheck.h>
147e83
+#include <stdio.h>
147e83
+#include <support/check.h>
147e83
+#include <support/support.h>
147e83
+#include <support/xunistd.h>
147e83
+#include <sys/mman.h>
147e83
+#include <sys/resource.h>
147e83
+#include <unistd.h>
147e83
+
147e83
+/* Data structure to fill up the heap.  */
147e83
+struct heap_filler
147e83
+{
147e83
+  struct heap_filler *next;
147e83
+};
147e83
+
147e83
+/* Allocate objects until the heap is full.  */
147e83
+static struct heap_filler *
147e83
+fill_heap (void)
147e83
+{
147e83
+  size_t pad = 4096;
147e83
+  struct heap_filler *head = NULL;
147e83
+  while (true)
147e83
+    {
147e83
+      struct heap_filler *new_head = malloc (sizeof (*new_head) + pad);
147e83
+      if (new_head == NULL)
147e83
+        {
147e83
+          if (pad > 0)
147e83
+            {
147e83
+              /* Try again with smaller allocations.  */
147e83
+              pad = 0;
147e83
+              continue;
147e83
+            }
147e83
+          else
147e83
+            break;
147e83
+        }
147e83
+      new_head->next = head;
147e83
+      head = new_head;
147e83
+    }
147e83
+  return head;
147e83
+}
147e83
+
147e83
+/* Free the heap-filling allocations, so that we can continue testing
147e83
+   and detect memory leaks elsewhere.  */
147e83
+static void
147e83
+free_fill_heap (struct heap_filler *head)
147e83
+{
147e83
+  while (head != NULL)
147e83
+    {
147e83
+      struct heap_filler *next = head->next;
147e83
+      free (head);
147e83
+      head = next;
147e83
+    }
147e83
+}
147e83
+
147e83
+/* Check allocation failures for int arrays (without an element free
147e83
+   function).  */
147e83
+static void
147e83
+test_int_fail (void)
147e83
+{
147e83
+  /* Exercise failure in add/emplace.
147e83
+
147e83
+     do_add: Use emplace (false) or add (true) to add elements.
147e83
+     do_finalize: Perform finalization at the end (instead of free).  */
147e83
+  for (int do_add = 0; do_add < 2; ++do_add)
147e83
+    for (int do_finalize = 0; do_finalize < 2; ++do_finalize)
147e83
+      {
147e83
+        struct dynarray_int dyn;
147e83
+        dynarray_int_init (&dyn);
147e83
+        size_t count = 0;
147e83
+        while (true)
147e83
+          {
147e83
+            if (do_add)
147e83
+              {
147e83
+                dynarray_int_add (&dyn, 0);
147e83
+                if (dynarray_int_has_failed (&dyn))
147e83
+                  break;
147e83
+              }
147e83
+            else
147e83
+              {
147e83
+                int *place = dynarray_int_emplace (&dyn);
147e83
+                if (place == NULL)
147e83
+                  break;
147e83
+                TEST_VERIFY_EXIT (!dynarray_int_has_failed (&dyn));
147e83
+                *place = 0;
147e83
+              }
147e83
+            ++count;
147e83
+          }
147e83
+        printf ("info: %s: failure after %zu elements\n", __func__, count);
147e83
+        TEST_VERIFY_EXIT (dynarray_int_has_failed (&dyn));
147e83
+        if (do_finalize)
147e83
+          {
147e83
+            struct int_array result = { (int *) (uintptr_t) -1, -1 };
147e83
+            TEST_VERIFY_EXIT (!dynarray_int_finalize (&dyn, &result));
147e83
+            TEST_VERIFY_EXIT (result.array == (int *) (uintptr_t) -1);
147e83
+            TEST_VERIFY_EXIT (result.length == (size_t) -1);
147e83
+          }
147e83
+        else
147e83
+          dynarray_int_free (&dyn);
147e83
+        CHECK_INIT_STATE (int, &dyn);
147e83
+      }
147e83
+
147e83
+  /* Exercise failure in finalize.  */
147e83
+  for (int do_add = 0; do_add < 2; ++do_add)
147e83
+    {
147e83
+      struct dynarray_int dyn;
147e83
+      dynarray_int_init (&dyn);
147e83
+      for (unsigned int i = 0; i < 10000; ++i)
147e83
+        {
147e83
+          if (do_add)
147e83
+            {
147e83
+              dynarray_int_add (&dyn, i);
147e83
+              TEST_VERIFY_EXIT (!dynarray_int_has_failed (&dyn));
147e83
+            }
147e83
+          else
147e83
+            {
147e83
+              int *place = dynarray_int_emplace (&dyn);
147e83
+              TEST_VERIFY_EXIT (place != NULL);
147e83
+              *place = i;
147e83
+            }
147e83
+        }
147e83
+      TEST_VERIFY_EXIT (!dynarray_int_has_failed (&dyn));
147e83
+      struct heap_filler *heap_filler = fill_heap ();
147e83
+      struct int_array result = { (int *) (uintptr_t) -1, -1 };
147e83
+      TEST_VERIFY_EXIT (!dynarray_int_finalize (&dyn, &result));
147e83
+      TEST_VERIFY_EXIT (result.array == (int *) (uintptr_t) -1);
147e83
+      TEST_VERIFY_EXIT (result.length == (size_t) -1);
147e83
+      CHECK_INIT_STATE (int, &dyn);
147e83
+      free_fill_heap (heap_filler);
147e83
+    }
147e83
+
147e83
+  /* Exercise failure in resize.  */
147e83
+  {
147e83
+    struct dynarray_int dyn;
147e83
+    dynarray_int_init (&dyn);
147e83
+    struct heap_filler *heap_filler = fill_heap ();
147e83
+    TEST_VERIFY (!dynarray_int_resize (&dyn, 1000));
147e83
+    TEST_VERIFY (dynarray_int_has_failed (&dyn));
147e83
+    free_fill_heap (heap_filler);
147e83
+
147e83
+    dynarray_int_init (&dyn);
147e83
+    TEST_VERIFY (dynarray_int_resize (&dyn, 1));
147e83
+    heap_filler = fill_heap ();
147e83
+    TEST_VERIFY (!dynarray_int_resize (&dyn, 1000));
147e83
+    TEST_VERIFY (dynarray_int_has_failed (&dyn));
147e83
+    free_fill_heap (heap_filler);
147e83
+
147e83
+    dynarray_int_init (&dyn);
147e83
+    TEST_VERIFY (dynarray_int_resize (&dyn, 1000));
147e83
+    heap_filler = fill_heap ();
147e83
+    TEST_VERIFY (!dynarray_int_resize (&dyn, 2000));
147e83
+    TEST_VERIFY (dynarray_int_has_failed (&dyn));
147e83
+    free_fill_heap (heap_filler);
147e83
+  }
147e83
+}
147e83
+
147e83
+/* Check allocation failures for char * arrays (which automatically
147e83
+   free the pointed-to strings).  */
147e83
+static void
147e83
+test_str_fail (void)
147e83
+{
147e83
+  /* Exercise failure in add/emplace.
147e83
+
147e83
+     do_add: Use emplace (false) or add (true) to add elements.
147e83
+     do_finalize: Perform finalization at the end (instead of free).  */
147e83
+  for (int do_add = 0; do_add < 2; ++do_add)
147e83
+    for (int do_finalize = 0; do_finalize < 2; ++do_finalize)
147e83
+      {
147e83
+        struct dynarray_str dyn;
147e83
+        dynarray_str_init (&dyn);
147e83
+        size_t count = 0;
147e83
+        while (true)
147e83
+          {
147e83
+            char **place;
147e83
+            if (do_add)
147e83
+              {
147e83
+                dynarray_str_add (&dyn, NULL);
147e83
+                if (dynarray_str_has_failed (&dyn))
147e83
+                  break;
147e83
+                else
147e83
+                  place = dynarray_str_at (&dyn, dynarray_str_size (&dyn) - 1);
147e83
+              }
147e83
+            else
147e83
+              {
147e83
+                place = dynarray_str_emplace (&dyn);
147e83
+                if (place == NULL)
147e83
+                  break;
147e83
+              }
147e83
+            TEST_VERIFY_EXIT (!dynarray_str_has_failed (&dyn));
147e83
+            TEST_VERIFY_EXIT (*place == NULL);
147e83
+            *place = strdup ("placeholder");
147e83
+            if (*place == NULL)
147e83
+              {
147e83
+                /* Second loop to wait for failure of
147e83
+                   dynarray_str_emplace.  */
147e83
+                while (true)
147e83
+                  {
147e83
+                    if (do_add)
147e83
+                      {
147e83
+                        dynarray_str_add (&dyn, NULL);
147e83
+                        if (dynarray_str_has_failed (&dyn))
147e83
+                          break;
147e83
+                      }
147e83
+                    else
147e83
+                      {
147e83
+                        char **place = dynarray_str_emplace (&dyn);
147e83
+                        if (place == NULL)
147e83
+                          break;
147e83
+                        TEST_VERIFY_EXIT (!dynarray_str_has_failed (&dyn));
147e83
+                        *place = NULL;
147e83
+                      }
147e83
+                    ++count;
147e83
+                  }
147e83
+                break;
147e83
+              }
147e83
+            ++count;
147e83
+          }
147e83
+        printf ("info: %s: failure after %zu elements\n", __func__, count);
147e83
+        TEST_VERIFY_EXIT (dynarray_str_has_failed (&dyn));
147e83
+        if (do_finalize)
147e83
+          {
147e83
+            struct str_array result = { (char **) (uintptr_t) -1, -1 };
147e83
+            TEST_VERIFY_EXIT (!dynarray_str_finalize (&dyn, &result));
147e83
+            TEST_VERIFY_EXIT (result.array == (char **) (uintptr_t) -1);
147e83
+            TEST_VERIFY_EXIT (result.length == (size_t) -1);
147e83
+          }
147e83
+        else
147e83
+          dynarray_str_free (&dyn);
147e83
+        TEST_VERIFY_EXIT (!dynarray_str_has_failed (&dyn));
147e83
+        TEST_VERIFY_EXIT (dyn.dynarray_header.array == dyn.scratch);
147e83
+        TEST_VERIFY_EXIT (dynarray_str_size (&dyn) == 0);
147e83
+        TEST_VERIFY_EXIT (dyn.dynarray_header.allocated > 0);
147e83
+      }
147e83
+
147e83
+  /* Exercise failure in finalize.  */
147e83
+  for (int do_add = 0; do_add < 2; ++do_add)
147e83
+    {
147e83
+      struct dynarray_str dyn;
147e83
+      dynarray_str_init (&dyn);
147e83
+      for (unsigned int i = 0; i < 1000; ++i)
147e83
+        {
147e83
+          if (do_add)
147e83
+            dynarray_str_add (&dyn, xstrdup ("placeholder"));
147e83
+          else
147e83
+            {
147e83
+              char **place = dynarray_str_emplace (&dyn);
147e83
+              TEST_VERIFY_EXIT (place != NULL);
147e83
+              TEST_VERIFY_EXIT (*place == NULL);
147e83
+              *place = xstrdup ("placeholder");
147e83
+            }
147e83
+        }
147e83
+      TEST_VERIFY_EXIT (!dynarray_str_has_failed (&dyn));
147e83
+      struct heap_filler *heap_filler = fill_heap ();
147e83
+      struct str_array result = { (char **) (uintptr_t) -1, -1 };
147e83
+      TEST_VERIFY_EXIT (!dynarray_str_finalize (&dyn, &result));
147e83
+      TEST_VERIFY_EXIT (result.array == (char **) (uintptr_t) -1);
147e83
+      TEST_VERIFY_EXIT (result.length == (size_t) -1);
147e83
+      TEST_VERIFY_EXIT (!dynarray_str_has_failed (&dyn));
147e83
+      TEST_VERIFY_EXIT (dyn.dynarray_header.array == dyn.scratch);
147e83
+      TEST_VERIFY_EXIT (dynarray_str_size (&dyn) == 0);
147e83
+      TEST_VERIFY_EXIT (dyn.dynarray_header.allocated > 0);
147e83
+      free_fill_heap (heap_filler);
147e83
+    }
147e83
+
147e83
+  /* Exercise failure in resize.  */
147e83
+  {
147e83
+    struct dynarray_str dyn;
147e83
+    dynarray_str_init (&dyn);
147e83
+    struct heap_filler *heap_filler = fill_heap ();
147e83
+    TEST_VERIFY (!dynarray_str_resize (&dyn, 1000));
147e83
+    TEST_VERIFY (dynarray_str_has_failed (&dyn));
147e83
+    free_fill_heap (heap_filler);
147e83
+
147e83
+    dynarray_str_init (&dyn);
147e83
+    TEST_VERIFY (dynarray_str_resize (&dyn, 1));
147e83
+    *dynarray_str_at (&dyn, 0) = xstrdup ("allocated");
147e83
+    heap_filler = fill_heap ();
147e83
+    TEST_VERIFY (!dynarray_str_resize (&dyn, 1000));
147e83
+    TEST_VERIFY (dynarray_str_has_failed (&dyn));
147e83
+    free_fill_heap (heap_filler);
147e83
+
147e83
+    dynarray_str_init (&dyn);
147e83
+    TEST_VERIFY (dynarray_str_resize (&dyn, 1000));
147e83
+    *dynarray_str_at (&dyn, 0) = xstrdup ("allocated");
147e83
+    heap_filler = fill_heap ();
147e83
+    TEST_VERIFY (!dynarray_str_resize (&dyn, 2000));
147e83
+    TEST_VERIFY (dynarray_str_has_failed (&dyn));
147e83
+    free_fill_heap (heap_filler);
147e83
+  }
147e83
+}
147e83
+
147e83
+/* Test if mmap can allocate a page.  This is necessary because
147e83
+   setrlimit does not fail even if it reduces the RLIMIT_AS limit
147e83
+   below what is currently needed by the process.  */
147e83
+static bool
147e83
+mmap_works (void)
147e83
+{
147e83
+  void *ptr =  mmap (NULL, 1, PROT_READ | PROT_WRITE,
147e83
+                     MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
147e83
+  if (ptr == MAP_FAILED)
147e83
+    return false;
147e83
+  xmunmap (ptr, 1);
147e83
+  return true;
147e83
+}
147e83
+
147e83
+/* Set the RLIMIT_AS limit to the value in *LIMIT.  */
147e83
+static void
147e83
+xsetrlimit_as (const struct rlimit *limit)
147e83
+{
147e83
+  if (setrlimit (RLIMIT_AS, limit) != 0)
147e83
+    FAIL_EXIT1 ("setrlimit (RLIMIT_AS, %lu): %m",
147e83
+                (unsigned long) limit->rlim_cur);
147e83
+}
147e83
+
147e83
+/* Approximately this many bytes can be allocated after
147e83
+   reduce_rlimit_as has run.  */
147e83
+enum { as_limit_reserve = 2 * 1024 * 1024 };
147e83
+
147e83
+/* Limit the size of the process, so that memory allocation in
147e83
+   allocate_thread will eventually fail, without impacting the entire
147e83
+   system.  By default, a dynamic limit which leaves room for 2 MiB is
147e83
+   activated.  The TEST_RLIMIT_AS environment variable overrides
147e83
+   it.  */
147e83
+static void
147e83
+reduce_rlimit_as (void)
147e83
+{
147e83
+  struct rlimit limit;
147e83
+  if (getrlimit (RLIMIT_AS, &limit) != 0)
147e83
+    FAIL_EXIT1 ("getrlimit (RLIMIT_AS) failed: %m");
147e83
+
147e83
+  /* Use the TEST_RLIMIT_AS setting if available.  */
147e83
+  {
147e83
+    long target = 0;
147e83
+    const char *variable = "TEST_RLIMIT_AS";
147e83
+    const char *target_str = getenv (variable);
147e83
+    if (target_str != NULL)
147e83
+      {
147e83
+        target = atoi (target_str);
147e83
+        if (target <= 0)
147e83
+          FAIL_EXIT1 ("invalid %s value: \"%s\"", variable, target_str);
147e83
+        printf ("info: setting RLIMIT_AS to %ld MiB\n", target);
147e83
+        target *= 1024 * 1024;      /* Convert to megabytes.  */
147e83
+        limit.rlim_cur = target;
147e83
+        xsetrlimit_as (&limit);
147e83
+        return;
147e83
+      }
147e83
+  }
147e83
+
147e83
+  /* Otherwise, try to find the limit with a binary search.  */
147e83
+  unsigned long low = 1 << 20;
147e83
+  limit.rlim_cur = low;
147e83
+  xsetrlimit_as (&limit);
147e83
+
147e83
+  /* Find working upper limit.  */
147e83
+  unsigned long high = 1 << 30;
147e83
+  while (true)
147e83
+    {
147e83
+      limit.rlim_cur = high;
147e83
+      xsetrlimit_as (&limit);
147e83
+      if (mmap_works ())
147e83
+        break;
147e83
+      if (2 * high < high)
147e83
+        FAIL_EXIT1 ("cannot find upper AS limit");
147e83
+      high *= 2;
147e83
+    }
147e83
+
147e83
+  /* Perform binary search.  */
147e83
+  while ((high - low) > 128 * 1024)
147e83
+    {
147e83
+      unsigned long middle = (low + high) / 2;
147e83
+      limit.rlim_cur = middle;
147e83
+      xsetrlimit_as (&limit);
147e83
+      if (mmap_works ())
147e83
+        high = middle;
147e83
+      else
147e83
+        low = middle;
147e83
+    }
147e83
+
147e83
+  unsigned long target = high + as_limit_reserve;
147e83
+  limit.rlim_cur = target;
147e83
+  xsetrlimit_as (&limit);
147e83
+  printf ("info: RLIMIT_AS limit: %lu bytes\n", target);
147e83
+}
147e83
+
147e83
+static int
147e83
+do_test (void)
147e83
+{
147e83
+  mtrace ();
147e83
+  reduce_rlimit_as ();
147e83
+  test_int_fail ();
147e83
+  test_str_fail ();
147e83
+  return 0;
147e83
+}
147e83
+
147e83
+#define TIMEOUT 90
147e83
+#include <support/test-driver.c>
147e83
diff --git a/malloc/tst-dynarray-shared.h b/malloc/tst-dynarray-shared.h
147e83
new file mode 100644
147e83
index 0000000000000000..1de9c04be88843d0
147e83
--- /dev/null
147e83
+++ b/malloc/tst-dynarray-shared.h
147e83
@@ -0,0 +1,80 @@
147e83
+/* Shared definitions for dynarray tests.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+#include <stddef.h>
147e83
+
147e83
+struct int_array
147e83
+{
147e83
+  int *array;
147e83
+  size_t length;
147e83
+};
147e83
+
147e83
+#define DYNARRAY_STRUCT dynarray_int
147e83
+#define DYNARRAY_ELEMENT int
147e83
+#define DYNARRAY_PREFIX dynarray_int_
147e83
+#define DYNARRAY_FINAL_TYPE struct int_array
147e83
+#include <malloc/dynarray-skeleton.c>
147e83
+
147e83
+struct str_array
147e83
+{
147e83
+  char **array;
147e83
+  size_t length;
147e83
+};
147e83
+
147e83
+#define DYNARRAY_STRUCT dynarray_str
147e83
+#define DYNARRAY_ELEMENT char *
147e83
+#define DYNARRAY_ELEMENT_FREE(ptr) free (*ptr)
147e83
+#define DYNARRAY_PREFIX dynarray_str_
147e83
+#define DYNARRAY_FINAL_TYPE struct str_array
147e83
+#include <malloc/dynarray-skeleton.c>
147e83
+
147e83
+/* Check that *DYN is equivalent to its initial state.  */
147e83
+#define CHECK_INIT_STATE(type, dyn)                             \
147e83
+  ({                                                            \
147e83
+    TEST_VERIFY_EXIT (!dynarray_##type##_has_failed (dyn));     \
147e83
+    TEST_VERIFY_EXIT (dynarray_##type##_size (dyn) == 0);       \
147e83
+    TEST_VERIFY_EXIT ((dyn)->dynarray_header.array              \
147e83
+                      == (dyn)->scratch);                       \
147e83
+    TEST_VERIFY_EXIT ((dyn)->dynarray_header.allocated > 0);    \
147e83
+    (void) 0;                                                   \
147e83
+  })
147e83
+
147e83
+/* Check that *DYN behaves as if it is in its initial state.  */
147e83
+#define CHECK_EMPTY(type, dyn)                                       \
147e83
+  ({                                                                 \
147e83
+    CHECK_INIT_STATE (type, (dyn));                                  \
147e83
+    dynarray_##type##_free (dyn);                                    \
147e83
+    CHECK_INIT_STATE (type, (dyn));                                  \
147e83
+    dynarray_##type##_clear (dyn);                                   \
147e83
+    CHECK_INIT_STATE (type, (dyn));                                  \
147e83
+    dynarray_##type##_remove_last (dyn);                             \
147e83
+    CHECK_INIT_STATE (type, (dyn));                                  \
147e83
+    dynarray_##type##_mark_failed (dyn);                             \
147e83
+    TEST_VERIFY_EXIT (dynarray_##type##_has_failed (dyn));           \
147e83
+    dynarray_##type##_clear (dyn);                                   \
147e83
+    TEST_VERIFY_EXIT (dynarray_##type##_has_failed (dyn));           \
147e83
+    dynarray_##type##_remove_last (dyn);                             \
147e83
+    TEST_VERIFY_EXIT (dynarray_##type##_has_failed (dyn));           \
147e83
+    TEST_VERIFY_EXIT (dynarray_##type##_emplace (dyn) == NULL);      \
147e83
+    dynarray_##type##_free (dyn);                                    \
147e83
+    CHECK_INIT_STATE (type, (dyn));                                  \
147e83
+    /* These functions should not assert.  */                        \
147e83
+    dynarray_##type##_begin (dyn);                                   \
147e83
+    dynarray_##type##_end (dyn);                                     \
147e83
+    (void) 0;                                                        \
147e83
+  })
147e83
diff --git a/malloc/tst-dynarray.c b/malloc/tst-dynarray.c
147e83
new file mode 100644
147e83
index 0000000000000000..d11f7bb8a343a16a
147e83
--- /dev/null
147e83
+++ b/malloc/tst-dynarray.c
147e83
@@ -0,0 +1,574 @@
147e83
+/* Test for dynamic arrays.
147e83
+   Copyright (C) 2017 Free Software Foundation, Inc.
147e83
+   This file is part of the GNU C Library.
147e83
+
147e83
+   The GNU C Library is free software; you can redistribute it and/or
147e83
+   modify it under the terms of the GNU Lesser General Public
147e83
+   License as published by the Free Software Foundation; either
147e83
+   version 2.1 of the License, or (at your option) any later version.
147e83
+
147e83
+   The GNU C Library is distributed in the hope that it will be useful,
147e83
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
147e83
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
147e83
+   Lesser General Public License for more details.
147e83
+
147e83
+   You should have received a copy of the GNU Lesser General Public
147e83
+   License along with the GNU C Library; if not, see
147e83
+   <http://www.gnu.org/licenses/>.  */
147e83
+
147e83
+#include "tst-dynarray-shared.h"
147e83
+
147e83
+#include <errno.h>
147e83
+#include <stdint.h>
147e83
+
147e83
+#define DYNARRAY_STRUCT dynarray_long
147e83
+#define DYNARRAY_ELEMENT long
147e83
+#define DYNARRAY_PREFIX dynarray_long_
147e83
+#define DYNARRAY_ELEMENT_INIT(e) (*(e) = 17)
147e83
+#include <malloc/dynarray-skeleton.c>
147e83
+
147e83
+struct long_array
147e83
+{
147e83
+  long *array;
147e83
+  size_t length;
147e83
+};
147e83
+
147e83
+#define DYNARRAY_STRUCT dynarray_long_noscratch
147e83
+#define DYNARRAY_ELEMENT long
147e83
+#define DYNARRAY_PREFIX dynarray_long_noscratch_
147e83
+#define DYNARRAY_ELEMENT_INIT(e) (*(e) = 23)
147e83
+#define DYNARRAY_FINAL_TYPE struct long_array
147e83
+#define DYNARRAY_INITIAL_SIZE 0
147e83
+#include <malloc/dynarray-skeleton.c>
147e83
+
147e83
+#define DYNARRAY_STRUCT zstr
147e83
+#define DYNARRAY_ELEMENT char
147e83
+#define DYNARRAY_PREFIX zstr_
147e83
+#define DYNARRAY_INITIAL_SIZE 128
147e83
+#include <malloc/dynarray-skeleton.c>
147e83
+
147e83
+#include <malloc.h>
147e83
+#include <mcheck.h>
147e83
+#include <stdint.h>
147e83
+#include <support/check.h>
147e83
+#include <support/support.h>
147e83
+
147e83
+enum { max_count = 20 };
147e83
+
147e83
+/* Test dynamic arrays with int elements (no automatic deallocation
147e83
+   for elements).  */
147e83
+static void
147e83
+test_int (void)
147e83
+{
147e83
+  /* Empty array.  */
147e83
+  {
147e83
+    struct dynarray_int dyn;
147e83
+    dynarray_int_init (&dyn);
147e83
+    CHECK_EMPTY (int, &dyn);
147e83
+  }
147e83
+
147e83
+  /* Empty array with finalization.  */
147e83
+  {
147e83
+    struct dynarray_int dyn;
147e83
+    dynarray_int_init (&dyn);
147e83
+    CHECK_INIT_STATE (int, &dyn);
147e83
+    struct int_array result = { (int *) (uintptr_t) -1, -1 };
147e83
+    TEST_VERIFY_EXIT (dynarray_int_finalize (&dyn, &result));
147e83
+    CHECK_INIT_STATE (int, &dyn);
147e83
+    TEST_VERIFY_EXIT (result.array == NULL);
147e83
+    TEST_VERIFY_EXIT (result.length == 0);
147e83
+  }
147e83
+
147e83
+  /* Non-empty array tests.
147e83
+
147e83
+     do_add: Switch between emplace (false) and add (true).
147e83
+     do_finalize: Perform finalize call at the end.
147e83
+     do_clear: Perform clear call at the end.
147e83
+     do_remove_last: Perform remove_last call after adding elements.
147e83
+     count: Number of elements added to the array.  */
147e83
+  for (int do_add = 0; do_add < 2; ++do_add)
147e83
+    for (int do_finalize = 0; do_finalize < 2; ++do_finalize)
147e83
+      for (int do_clear = 0; do_clear < 2; ++do_clear)
147e83
+        for (int do_remove_last = 0; do_remove_last < 2; ++do_remove_last)
147e83
+          for (unsigned int count = 0; count < max_count; ++count)
147e83
+            {
147e83
+              if (do_remove_last && count == 0)
147e83
+                continue;
147e83
+              unsigned int base = count * count;
147e83
+              struct dynarray_int dyn;
147e83
+              dynarray_int_init (&dyn);
147e83
+              for (unsigned int i = 0; i < count; ++i)
147e83
+                {
147e83
+                  if (do_add)
147e83
+                    dynarray_int_add (&dyn, base + i);
147e83
+                  else
147e83
+                    {
147e83
+                      int *place = dynarray_int_emplace (&dyn);
147e83
+                      TEST_VERIFY_EXIT (place != NULL);
147e83
+                      *place = base + i;
147e83
+                    }
147e83
+                  TEST_VERIFY_EXIT (!dynarray_int_has_failed (&dyn));
147e83
+                  TEST_VERIFY_EXIT (dynarray_int_size (&dyn) == i + 1);
147e83
+                  TEST_VERIFY_EXIT (dynarray_int_size (&dyn)
147e83
+                                    <= dyn.dynarray_header.allocated);
147e83
+                }
147e83
+              TEST_VERIFY_EXIT (dynarray_int_size (&dyn) == count);
147e83
+              TEST_VERIFY_EXIT (count <= dyn.dynarray_header.allocated);
147e83
+              if (count > 0)
147e83
+                {
147e83
+                  TEST_VERIFY (dynarray_int_begin (&dyn)
147e83
+                               == dynarray_int_at (&dyn, 0));
147e83
+                  TEST_VERIFY (dynarray_int_end (&dyn)
147e83
+                               == dynarray_int_at (&dyn, count - 1) + 1);
147e83
+                }
147e83
+              unsigned final_count;
147e83
+              bool heap_array = dyn.dynarray_header.array != dyn.scratch;
147e83
+              if (do_remove_last)
147e83
+                {
147e83
+                  dynarray_int_remove_last (&dyn);
147e83
+                  if (count == 0)
147e83
+                    final_count = 0;
147e83
+                  else
147e83
+                    final_count = count - 1;
147e83
+                }
147e83
+              else
147e83
+                final_count = count;
147e83
+              if (final_count > 0)
147e83
+                {
147e83
+                  TEST_VERIFY (dynarray_int_begin (&dyn)
147e83
+                               == dynarray_int_at (&dyn, 0));
147e83
+                  TEST_VERIFY (dynarray_int_end (&dyn)
147e83
+                               == dynarray_int_at (&dyn, final_count - 1) + 1);
147e83
+                }
147e83
+              if (do_clear)
147e83
+                {
147e83
+                  dynarray_int_clear (&dyn);
147e83
+                  final_count = 0;
147e83
+                }
147e83
+              TEST_VERIFY_EXIT (!dynarray_int_has_failed (&dyn));
147e83
+              TEST_VERIFY_EXIT ((dyn.dynarray_header.array != dyn.scratch)
147e83
+                                == heap_array);
147e83
+              TEST_VERIFY_EXIT (dynarray_int_size (&dyn) == final_count);
147e83
+              TEST_VERIFY_EXIT (dyn.dynarray_header.allocated >= final_count);
147e83
+              if (!do_clear)
147e83
+                for (unsigned int i = 0; i < final_count; ++i)
147e83
+                  TEST_VERIFY_EXIT (*dynarray_int_at (&dyn, i) == base + i);
147e83
+              if (do_finalize)
147e83
+                {
147e83
+                  struct int_array result = { (int *) (uintptr_t) -1, -1 };
147e83
+                  TEST_VERIFY_EXIT (dynarray_int_finalize (&dyn, &result));
147e83
+                  CHECK_INIT_STATE (int, &dyn);
147e83
+                  TEST_VERIFY_EXIT (result.length == final_count);
147e83
+                  if (final_count == 0)
147e83
+                    TEST_VERIFY_EXIT (result.array == NULL);
147e83
+                  else
147e83
+                    {
147e83
+                      TEST_VERIFY_EXIT (result.array != NULL);
147e83
+                      TEST_VERIFY_EXIT (result.array != (int *) (uintptr_t) -1);
147e83
+                      TEST_VERIFY_EXIT
147e83
+                        (malloc_usable_size (result.array)
147e83
+                         >= final_count * sizeof (result.array[0]));
147e83
+                      for (unsigned int i = 0; i < final_count; ++i)
147e83
+                        TEST_VERIFY_EXIT (result.array[i] == base + i);
147e83
+                      free (result.array);
147e83
+                    }
147e83
+                }
147e83
+              else /* !do_finalize */
147e83
+                {
147e83
+                  dynarray_int_free (&dyn);
147e83
+                  CHECK_INIT_STATE (int, &dyn);
147e83
+                }
147e83
+            }
147e83
+}
147e83
+
147e83
+/* Test dynamic arrays with char * elements (with automatic
147e83
+   deallocation of the pointed-to strings).  */
147e83
+static void
147e83
+test_str (void)
147e83
+{
147e83
+  /* Empty array.  */
147e83
+  {
147e83
+    struct dynarray_str dyn;
147e83
+    dynarray_str_init (&dyn);
147e83
+    CHECK_EMPTY (str, &dyn);
147e83
+  }
147e83
+
147e83
+  /* Empty array with finalization.  */
147e83
+  {
147e83
+    struct dynarray_str dyn;
147e83
+    dynarray_str_init (&dyn);
147e83
+    TEST_VERIFY_EXIT (!dynarray_str_has_failed (&dyn));
147e83
+    struct str_array result = { (char **) (uintptr_t) -1, -1 };
147e83
+    TEST_VERIFY_EXIT (dynarray_str_finalize (&dyn, &result));
147e83
+    CHECK_INIT_STATE (str, &dyn);
147e83
+    TEST_VERIFY_EXIT (result.array == NULL);
147e83
+    TEST_VERIFY_EXIT (result.length == 0);
147e83
+  }
147e83
+
147e83
+  /* Non-empty array tests.
147e83
+
147e83
+     do_add: Switch between emplace (false) and add (true).
147e83
+     do_finalize: Perform finalize call at the end.
147e83
+     do_clear: Perform clear call at the end.
147e83
+     do_remove_last: Perform remove_last call after adding elements.
147e83
+     count: Number of elements added to the array.  */
147e83
+  for (int do_add = 0; do_add < 2; ++do_add)
147e83
+    for (int do_finalize = 0; do_finalize < 2; ++do_finalize)
147e83
+      for (int do_clear = 0; do_clear < 2; ++do_clear)
147e83
+        for (int do_remove_last = 0; do_remove_last < 2; ++do_remove_last)
147e83
+          for (unsigned int count = 0; count < max_count; ++count)
147e83
+            {
147e83
+              if (do_remove_last && count == 0)
147e83
+                continue;
147e83
+              unsigned int base = count * count;
147e83
+              struct dynarray_str dyn;
147e83
+              dynarray_str_init (&dyn);
147e83
+              for (unsigned int i = 0; i < count; ++i)
147e83
+                {
147e83
+                  char *item = xasprintf ("%d", base + i);
147e83
+                  if (do_add)
147e83
+                    dynarray_str_add (&dyn, item);
147e83
+                  else
147e83
+                    {
147e83
+                      char **place = dynarray_str_emplace (&dyn);
147e83
+                      TEST_VERIFY_EXIT (place != NULL);
147e83
+                      TEST_VERIFY_EXIT (*place == NULL);
147e83
+                      *place = item;
147e83
+                    }
147e83
+                  TEST_VERIFY_EXIT (!dynarray_str_has_failed (&dyn));
147e83
+                  TEST_VERIFY_EXIT (dynarray_str_size (&dyn) == i + 1);
147e83
+                  TEST_VERIFY_EXIT (dynarray_str_size (&dyn)
147e83
+                                    <= dyn.dynarray_header.allocated);
147e83
+                }
147e83
+              TEST_VERIFY_EXIT (dynarray_str_size (&dyn) == count);
147e83
+              TEST_VERIFY_EXIT (count <= dyn.dynarray_header.allocated);
147e83
+              if (count > 0)
147e83
+                {
147e83
+                  TEST_VERIFY (dynarray_str_begin (&dyn)
147e83
+                               == dynarray_str_at (&dyn, 0));
147e83
+                  TEST_VERIFY (dynarray_str_end (&dyn)
147e83
+                               == dynarray_str_at (&dyn, count - 1) + 1);
147e83
+                }
147e83
+              unsigned final_count;
147e83
+              bool heap_array = dyn.dynarray_header.array != dyn.scratch;
147e83
+              if (do_remove_last)
147e83
+                {
147e83
+                  dynarray_str_remove_last (&dyn);
147e83
+                  if (count == 0)
147e83
+                    final_count = 0;
147e83
+                  else
147e83
+                    final_count = count - 1;
147e83
+                }
147e83
+              else
147e83
+                final_count = count;
147e83
+              if (final_count > 0)
147e83
+                {
147e83
+                  TEST_VERIFY (dynarray_str_begin (&dyn)
147e83
+                               == dynarray_str_at (&dyn, 0));
147e83
+                  TEST_VERIFY (dynarray_str_end (&dyn)
147e83
+                               == dynarray_str_at (&dyn, final_count - 1) + 1);
147e83
+                }
147e83
+              if (do_clear)
147e83
+                {
147e83
+                  dynarray_str_clear (&dyn);
147e83
+                  final_count = 0;
147e83
+                }
147e83
+              TEST_VERIFY_EXIT (!dynarray_str_has_failed (&dyn));
147e83
+              TEST_VERIFY_EXIT ((dyn.dynarray_header.array != dyn.scratch)
147e83
+                                == heap_array);
147e83
+              TEST_VERIFY_EXIT (dynarray_str_size (&dyn) == final_count);
147e83
+              TEST_VERIFY_EXIT (dyn.dynarray_header.allocated >= final_count);
147e83
+              if (!do_clear)
147e83
+                for (unsigned int i = 0; i < count - do_remove_last; ++i)
147e83
+                  {
147e83
+                    char *expected = xasprintf ("%d", base + i);
147e83
+                    const char *actual = *dynarray_str_at (&dyn, i);
147e83
+                    TEST_VERIFY_EXIT (strcmp (actual, expected) == 0);
147e83
+                    free (expected);
147e83
+                  }
147e83
+              if (do_finalize)
147e83
+                {
147e83
+                  struct str_array result = { (char **) (uintptr_t) -1, -1 };
147e83
+                  TEST_VERIFY_EXIT (dynarray_str_finalize (&dyn, &result));
147e83
+                  CHECK_INIT_STATE (str, &dyn);
147e83
+                  TEST_VERIFY_EXIT (result.length == final_count);
147e83
+                  if (final_count == 0)
147e83
+                    TEST_VERIFY_EXIT (result.array == NULL);
147e83
+                  else
147e83
+                    {
147e83
+                      TEST_VERIFY_EXIT (result.array != NULL);
147e83
+                      TEST_VERIFY_EXIT (result.array
147e83
+                                        != (char **) (uintptr_t) -1);
147e83
+                      TEST_VERIFY_EXIT (result.length
147e83
+                                        == count - do_remove_last);
147e83
+                      TEST_VERIFY_EXIT
147e83
+                        (malloc_usable_size (result.array)
147e83
+                         >= final_count * sizeof (result.array[0]));
147e83
+                      for (unsigned int i = 0; i < count - do_remove_last; ++i)
147e83
+                        {
147e83
+                          char *expected = xasprintf ("%d", base + i);
147e83
+                          char *actual = result.array[i];
147e83
+                          TEST_VERIFY_EXIT (strcmp (actual, expected) == 0);
147e83
+                          free (expected);
147e83
+                          free (actual);
147e83
+                        }
147e83
+                      free (result.array);
147e83
+                    }
147e83
+                }
147e83
+              else /* !do_finalize */
147e83
+                {
147e83
+                  dynarray_str_free (&dyn);
147e83
+                  CHECK_INIT_STATE (str, &dyn);
147e83
+                }
147e83
+            }
147e83
+
147e83
+  /* Test resizing.  */
147e83
+  {
147e83
+    enum { count = 2131 };
147e83
+    struct dynarray_str dyn;
147e83
+    dynarray_str_init (&dyn);
147e83
+
147e83
+    /* From length 0 to length 1.  */
147e83
+    TEST_VERIFY (dynarray_str_resize (&dyn, 1));
147e83
+    TEST_VERIFY (dynarray_str_size (&dyn) == 1);
147e83
+    TEST_VERIFY (*dynarray_str_at (&dyn, 0) == NULL);
147e83
+    *dynarray_str_at (&dyn, 0) = xstrdup ("allocated");
147e83
+    dynarray_str_free (&dyn);
147e83
+
147e83
+    /* From length 0 to length 1 and 2.  */
147e83
+    TEST_VERIFY (dynarray_str_resize (&dyn, 1));
147e83
+    TEST_VERIFY (dynarray_str_size (&dyn) == 1);
147e83
+    TEST_VERIFY (*dynarray_str_at (&dyn, 0) == NULL);
147e83
+    *dynarray_str_at (&dyn, 0) = xstrdup ("allocated0");
147e83
+    TEST_VERIFY (dynarray_str_resize (&dyn, 2));
147e83
+    TEST_VERIFY (dynarray_str_size (&dyn) == 2);
147e83
+    TEST_VERIFY (strcmp (*dynarray_str_at (&dyn, 0), "allocated0") == 0);
147e83
+    TEST_VERIFY (*dynarray_str_at (&dyn, 1) == NULL);
147e83
+    *dynarray_str_at (&dyn, 1) = xstrdup ("allocated1");
147e83
+    TEST_VERIFY (dynarray_str_resize (&dyn, count));
147e83
+    TEST_VERIFY (dynarray_str_size (&dyn) == count);
147e83
+    TEST_VERIFY (strcmp (*dynarray_str_at (&dyn, 0), "allocated0") == 0);
147e83
+    TEST_VERIFY (strcmp (*dynarray_str_at (&dyn, 1), "allocated1") == 0);
147e83
+    for (int i = 2; i < count; ++i)
147e83
+      TEST_VERIFY (*dynarray_str_at (&dyn, i) == NULL);
147e83
+    *dynarray_str_at (&dyn, count - 1) = xstrdup ("allocated2");
147e83
+    TEST_VERIFY (dynarray_str_resize (&dyn, 3));
147e83
+    TEST_VERIFY (strcmp (*dynarray_str_at (&dyn, 0), "allocated0") == 0);
147e83
+    TEST_VERIFY (strcmp (*dynarray_str_at (&dyn, 1), "allocated1") == 0);
147e83
+    TEST_VERIFY (*dynarray_str_at (&dyn, 2) == NULL);
147e83
+    dynarray_str_free (&dyn);
147e83
+  }
147e83
+}
147e83
+
147e83
+/* Verify that DYNARRAY_ELEMENT_INIT has an effect.  */
147e83
+static void
147e83
+test_long_init (void)
147e83
+{
147e83
+  enum { count = 2131 };
147e83
+  {
147e83
+    struct dynarray_long dyn;
147e83
+    dynarray_long_init (&dyn);
147e83
+    for (int i = 0; i < count; ++i)
147e83
+      {
147e83
+        long *place = dynarray_long_emplace (&dyn);
147e83
+        TEST_VERIFY_EXIT (place != NULL);
147e83
+        TEST_VERIFY (*place == 17);
147e83
+      }
147e83
+    TEST_VERIFY (dynarray_long_size (&dyn) == count);
147e83
+    for (int i = 0; i < count; ++i)
147e83
+      TEST_VERIFY (*dynarray_long_at (&dyn, i) == 17);
147e83
+    dynarray_long_free (&dyn);
147e83
+
147e83
+    TEST_VERIFY (dynarray_long_resize (&dyn, 1));
147e83
+    TEST_VERIFY (dynarray_long_size (&dyn) == 1);
147e83
+    TEST_VERIFY (*dynarray_long_at (&dyn, 0) == 17);
147e83
+    *dynarray_long_at (&dyn, 0) = 18;
147e83
+    dynarray_long_free (&dyn);
147e83
+    TEST_VERIFY (dynarray_long_resize (&dyn, 1));
147e83
+    TEST_VERIFY (dynarray_long_size (&dyn) == 1);
147e83
+    TEST_VERIFY (*dynarray_long_at (&dyn, 0) == 17);
147e83
+    TEST_VERIFY (dynarray_long_resize (&dyn, 2));
147e83
+    TEST_VERIFY (dynarray_long_size (&dyn) == 2);
147e83
+    TEST_VERIFY (*dynarray_long_at (&dyn, 0) == 17);
147e83
+    TEST_VERIFY (*dynarray_long_at (&dyn, 1) == 17);
147e83
+    *dynarray_long_at (&dyn, 0) = 18;
147e83
+    TEST_VERIFY (dynarray_long_resize (&dyn, count));
147e83
+    TEST_VERIFY (dynarray_long_size (&dyn) == count);
147e83
+    TEST_VERIFY (*dynarray_long_at (&dyn, 0) == 18);
147e83
+    for (int i = 1; i < count; ++i)
147e83
+      TEST_VERIFY (*dynarray_long_at (&dyn, i) == 17);
147e83
+    dynarray_long_free (&dyn);
147e83
+  }
147e83
+
147e83
+  /* Similar, but without an on-stack scratch region
147e83
+     (DYNARRAY_INITIAL_SIZE is 0).  */
147e83
+  {
147e83
+    struct dynarray_long_noscratch dyn;
147e83
+    dynarray_long_noscratch_init (&dyn);
147e83
+    struct long_array result;
147e83
+    TEST_VERIFY_EXIT (dynarray_long_noscratch_finalize (&dyn, &result));
147e83
+    TEST_VERIFY (result.array == NULL);
147e83
+    TEST_VERIFY (result.length == 0);
147e83
+
147e83
+    /* Test with one element.  */
147e83
+    {
147e83
+      long *place = dynarray_long_noscratch_emplace (&dyn);
147e83
+      TEST_VERIFY_EXIT (place != NULL);
147e83
+      TEST_VERIFY (*place == 23);
147e83
+    }
147e83
+    TEST_VERIFY (dynarray_long_noscratch_size (&dyn) == 1);
147e83
+    TEST_VERIFY (*dynarray_long_noscratch_at (&dyn, 0) == 23);
147e83
+    TEST_VERIFY_EXIT (dynarray_long_noscratch_finalize (&dyn, &result));
147e83
+    TEST_VERIFY_EXIT (result.array != NULL);
147e83
+    TEST_VERIFY (result.length == 1);
147e83
+    TEST_VERIFY (result.array[0] == 23);
147e83
+    free (result.array);
147e83
+
147e83
+    for (int i = 0; i < count; ++i)
147e83
+      {
147e83
+        long *place = dynarray_long_noscratch_emplace (&dyn);
147e83
+        TEST_VERIFY_EXIT (place != NULL);
147e83
+        TEST_VERIFY (*place == 23);
147e83
+        if (i == 0)
147e83
+          *place = 29;
147e83
+      }
147e83
+    TEST_VERIFY (dynarray_long_noscratch_size (&dyn) == count);
147e83
+    TEST_VERIFY (*dynarray_long_noscratch_at (&dyn, 0) == 29);
147e83
+    for (int i = 1; i < count; ++i)
147e83
+      TEST_VERIFY (*dynarray_long_noscratch_at (&dyn, i) == 23);
147e83
+    TEST_VERIFY_EXIT (dynarray_long_noscratch_finalize (&dyn, &result));
147e83
+    TEST_VERIFY_EXIT (result.array != NULL);
147e83
+    TEST_VERIFY (result.length == count);
147e83
+    TEST_VERIFY (result.array[0] == 29);
147e83
+    for (int i = 1; i < count; ++i)
147e83
+      TEST_VERIFY (result.array[i] == 23);
147e83
+    free (result.array);
147e83
+
147e83
+    TEST_VERIFY (dynarray_long_noscratch_resize (&dyn, 1));
147e83
+    TEST_VERIFY (dynarray_long_noscratch_size (&dyn) == 1);
147e83
+    TEST_VERIFY (*dynarray_long_noscratch_at (&dyn, 0) == 23);
147e83
+    *dynarray_long_noscratch_at (&dyn, 0) = 24;
147e83
+    dynarray_long_noscratch_free (&dyn);
147e83
+    TEST_VERIFY (dynarray_long_noscratch_resize (&dyn, 1));
147e83
+    TEST_VERIFY (dynarray_long_noscratch_size (&dyn) == 1);
147e83
+    TEST_VERIFY (*dynarray_long_noscratch_at (&dyn, 0) == 23);
147e83
+    TEST_VERIFY (dynarray_long_noscratch_resize (&dyn, 2));
147e83
+    TEST_VERIFY (dynarray_long_noscratch_size (&dyn) == 2);
147e83
+    TEST_VERIFY (*dynarray_long_noscratch_at (&dyn, 0) == 23);
147e83
+    TEST_VERIFY (*dynarray_long_noscratch_at (&dyn, 1) == 23);
147e83
+    *dynarray_long_noscratch_at (&dyn, 0) = 24;
147e83
+    TEST_VERIFY (dynarray_long_noscratch_resize (&dyn, count));
147e83
+    TEST_VERIFY (dynarray_long_noscratch_size (&dyn) == count);
147e83
+    TEST_VERIFY (*dynarray_long_noscratch_at (&dyn, 0) == 24);
147e83
+    for (int i = 1; i < count; ++i)
147e83
+      TEST_VERIFY (*dynarray_long_noscratch_at (&dyn, i) == 23);
147e83
+    dynarray_long_noscratch_free (&dyn);
147e83
+  }
147e83
+}
147e83
+
147e83
+/* Test overflow in resize.  */
147e83
+static void
147e83
+test_long_overflow (void)
147e83
+{
147e83
+  {
147e83
+    struct dynarray_long dyn;
147e83
+    dynarray_long_init (&dyn);
147e83
+    errno = EINVAL;
147e83
+    TEST_VERIFY (!dynarray_long_resize
147e83
+                 (&dyn, (SIZE_MAX / sizeof (long)) + 1));
147e83
+    TEST_VERIFY (errno == ENOMEM);
147e83
+    TEST_VERIFY (dynarray_long_has_failed (&dyn));
147e83
+  }
147e83
+
147e83
+  {
147e83
+    struct dynarray_long_noscratch dyn;
147e83
+    dynarray_long_noscratch_init (&dyn);
147e83
+    errno = EINVAL;
147e83
+    TEST_VERIFY (!dynarray_long_noscratch_resize
147e83
+                 (&dyn, (SIZE_MAX / sizeof (long)) + 1));
147e83
+    TEST_VERIFY (errno == ENOMEM);
147e83
+    TEST_VERIFY (dynarray_long_noscratch_has_failed (&dyn));
147e83
+  }
147e83
+}
147e83
+
147e83
+/* Test NUL-terminated string construction with the add function and
147e83
+   the simple finalize function.  */
147e83
+static void
147e83
+test_zstr (void)
147e83
+{
147e83
+  /* Totally empty string (no NUL termination).  */
147e83
+  {
147e83
+    struct zstr s;
147e83
+    zstr_init (&s);
147e83
+    char *result = zstr_finalize (&s, NULL);
147e83
+    TEST_VERIFY (result == NULL);
147e83
+    TEST_VERIFY (zstr_size (&s) == 0);
147e83
+    size_t length = 1;
147e83
+    result = zstr_finalize (&s, &length);
147e83
+    TEST_VERIFY (result == NULL);
147e83
+    TEST_VERIFY (length == 0);
147e83
+    TEST_VERIFY (zstr_size (&s) == 0);
147e83
+  }
147e83
+
147e83
+  /* Empty string.  */
147e83
+  {
147e83
+    struct zstr s;
147e83
+    zstr_init (&s);
147e83
+    zstr_add (&s, '\0');
147e83
+    char *result = zstr_finalize (&s, NULL);
147e83
+    TEST_VERIFY_EXIT (result != NULL);
147e83
+    TEST_VERIFY (*result == '\0');
147e83
+    TEST_VERIFY (zstr_size (&s) == 0);
147e83
+    free (result);
147e83
+
147e83
+    zstr_add (&s, '\0');
147e83
+    size_t length = 1;
147e83
+    result = zstr_finalize (&s, &length);
147e83
+    TEST_VERIFY_EXIT (result != NULL);
147e83
+    TEST_VERIFY (*result == '\0');
147e83
+    TEST_VERIFY (length == 1);
147e83
+    TEST_VERIFY (zstr_size (&s) == 0);
147e83
+    free (result);
147e83
+  }
147e83
+
147e83
+  /* A few characters.  */
147e83
+  {
147e83
+    struct zstr s;
147e83
+    zstr_init (&s);
147e83
+    zstr_add (&s, 'A');
147e83
+    zstr_add (&s, 'b');
147e83
+    zstr_add (&s, 'c');
147e83
+    zstr_add (&s, '\0');
147e83
+    char *result = zstr_finalize (&s, NULL);
147e83
+    TEST_VERIFY_EXIT (result != NULL);
147e83
+    TEST_VERIFY (strcmp (result, "Abc") == 0);
147e83
+    TEST_VERIFY (zstr_size (&s) == 0);
147e83
+    free (result);
147e83
+
147e83
+    zstr_add (&s, 'X');
147e83
+    zstr_add (&s, 'y');
147e83
+    zstr_add (&s, 'z');
147e83
+    zstr_add (&s, '\0');
147e83
+    size_t length = 1;
147e83
+    result = zstr_finalize (&s, &length);
147e83
+    TEST_VERIFY_EXIT (result != NULL);
147e83
+    TEST_VERIFY (strcmp (result, "Xyz") == 0);
147e83
+    TEST_VERIFY (length == 4);
147e83
+    TEST_VERIFY (zstr_size (&s) == 0);
147e83
+    free (result);
147e83
+  }
147e83
+}
147e83
+
147e83
+static int
147e83
+do_test (void)
147e83
+{
147e83
+  mtrace ();
147e83
+  test_int ();
147e83
+  test_str ();
147e83
+  test_long_init ();
147e83
+  test_long_overflow ();
147e83
+  test_zstr ();
147e83
+  return 0;
147e83
+}
147e83
+
147e83
+#include <support/test-driver.c>