Merge "malloc_debug: reset TrackData mutex after fork"
diff --git a/libc/Android.mk b/libc/Android.mk
index 42f717e..f2004e1 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -850,7 +850,9 @@
 LOCAL_SRC_FILES := $(libc_upstream_netbsd_src_files)
 LOCAL_CFLAGS := \
     $(libc_common_cflags) \
-    -Wno-sign-compare -Wno-uninitialized \
+    -Wno-sign-compare \
+    -Wno-uninitialized \
+    -Wno-unused-parameter \
     -DPOSIX_MISTAKE \
     -include netbsd-compat.h \
 
diff --git a/libc/malloc_debug/BacktraceData.cpp b/libc/malloc_debug/BacktraceData.cpp
index 61267f0..400e282 100644
--- a/libc/malloc_debug/BacktraceData.cpp
+++ b/libc/malloc_debug/BacktraceData.cpp
@@ -44,7 +44,7 @@
 BacktraceData::BacktraceData(const Config& config, size_t* offset) {
   size_t hdr_len = sizeof(BacktraceHeader) + sizeof(uintptr_t) * config.backtrace_frames;
   alloc_offset_ = *offset;
-  *offset += BIONIC_ALIGN(hdr_len, sizeof(uintptr_t));
+  *offset += BIONIC_ALIGN(hdr_len, MINIMUM_ALIGNMENT_BYTES);
 }
 
 static BacktraceData* g_backtrace_data = nullptr;
diff --git a/libc/malloc_debug/Config.cpp b/libc/malloc_debug/Config.cpp
index 032c1fc..ce83aa4 100644
--- a/libc/malloc_debug/Config.cpp
+++ b/libc/malloc_debug/Config.cpp
@@ -347,10 +347,10 @@
   valid = valid && parser.Done();
 
   if (valid) {
-    // It's necessary to align the front guard to sizeof(uintptr_t) to
+    // It's necessary to align the front guard to MINIMUM_ALIGNMENT_BYTES to
     // make sure that the header is aligned properly.
     if (options & FRONT_GUARD) {
-      front_guard_bytes = BIONIC_ALIGN(front_guard_bytes, sizeof(uintptr_t));
+      front_guard_bytes = BIONIC_ALIGN(front_guard_bytes, MINIMUM_ALIGNMENT_BYTES);
     }
 
     // This situation can occur if the free_track option is specified and
diff --git a/libc/malloc_debug/Config.h b/libc/malloc_debug/Config.h
index d2cc56d..cb1de5a 100644
--- a/libc/malloc_debug/Config.h
+++ b/libc/malloc_debug/Config.h
@@ -41,6 +41,14 @@
 constexpr uint64_t TRACK_ALLOCS = 0x80;
 constexpr uint64_t LEAK_TRACK = 0x100;
 
+// In order to guarantee posix compliance, set the minimum alignment
+// to 8 bytes for 32 bit systems and 16 bytes for 64 bit systems.
+#if defined(__LP64__)
+constexpr size_t MINIMUM_ALIGNMENT_BYTES = 16;
+#else
+constexpr size_t MINIMUM_ALIGNMENT_BYTES = 8;
+#endif
+
 // If only one or more of these options is set, then no special header is needed.
 constexpr uint64_t NO_HEADER_OPTIONS = FILL_ON_ALLOC | FILL_ON_FREE | EXPAND_ALLOC;
 
diff --git a/libc/malloc_debug/DebugData.cpp b/libc/malloc_debug/DebugData.cpp
index cf16c29..0447566 100644
--- a/libc/malloc_debug/DebugData.cpp
+++ b/libc/malloc_debug/DebugData.cpp
@@ -47,7 +47,7 @@
     need_header_ = true;
 
     // Initialize all of the static header offsets.
-    pointer_offset_ = BIONIC_ALIGN(sizeof(Header), sizeof(uintptr_t));
+    pointer_offset_ = BIONIC_ALIGN(sizeof(Header), MINIMUM_ALIGNMENT_BYTES);
 
     if (config_.options & BACKTRACE) {
       backtrace.reset(new BacktraceData(config_, &pointer_offset_));
diff --git a/libc/malloc_debug/GuardData.cpp b/libc/malloc_debug/GuardData.cpp
index 4ba5253..c70e8f1 100644
--- a/libc/malloc_debug/GuardData.cpp
+++ b/libc/malloc_debug/GuardData.cpp
@@ -75,7 +75,7 @@
   // Create a buffer for fast comparisons of the front guard.
   cmp_mem_.resize(config.front_guard_bytes);
   memset(cmp_mem_.data(), config.front_guard_value, cmp_mem_.size());
-  // Assumes that front_bytes is a multiple of sizeof(uintptr_t).
+  // Assumes that front_bytes is a multiple of MINIMUM_ALIGNMENT_BYTES.
   offset_ = *offset;
   *offset += config.front_guard_bytes;
 }
diff --git a/libc/malloc_debug/malloc_debug.cpp b/libc/malloc_debug/malloc_debug.cpp
index 8562900..dcc6048 100644
--- a/libc/malloc_debug/malloc_debug.cpp
+++ b/libc/malloc_debug/malloc_debug.cpp
@@ -39,6 +39,7 @@
 #include <private/bionic_malloc_dispatch.h>
 
 #include "backtrace.h"
+#include "Config.h"
 #include "DebugData.h"
 #include "debug_disable.h"
 #include "debug_log.h"
@@ -289,7 +290,8 @@
       return nullptr;
     }
 
-    Header* header = reinterpret_cast<Header*>(g_dispatch->memalign(sizeof(uintptr_t), real_size));
+    Header* header = reinterpret_cast<Header*>(
+        g_dispatch->memalign(MINIMUM_ALIGNMENT_BYTES, real_size));
     if (header == nullptr) {
       return nullptr;
     }
@@ -380,10 +382,10 @@
     if (!powerof2(alignment)) {
       alignment = BIONIC_ROUND_UP_POWER_OF_2(alignment);
     }
-    // Force the alignment to at least sizeof(uintptr_t) to guarantee
+    // Force the alignment to at least MINIMUM_ALIGNMENT_BYTES to guarantee
     // that the header is aligned properly.
-    if (alignment < sizeof(uintptr_t)) {
-      alignment = sizeof(uintptr_t);
+    if (alignment < MINIMUM_ALIGNMENT_BYTES) {
+      alignment = MINIMUM_ALIGNMENT_BYTES;
     }
 
     // We don't have any idea what the natural alignment of
@@ -537,7 +539,8 @@
     }
 
     // Need to guarantee the alignment of the header.
-    Header* header = reinterpret_cast<Header*>(g_dispatch->memalign(sizeof(uintptr_t), real_size));
+    Header* header = reinterpret_cast<Header*>(
+        g_dispatch->memalign(MINIMUM_ALIGNMENT_BYTES, real_size));
     if (header == nullptr) {
       return nullptr;
     }
diff --git a/libc/malloc_debug/malloc_debug.h b/libc/malloc_debug/malloc_debug.h
index 6f9f90f..347fae2 100644
--- a/libc/malloc_debug/malloc_debug.h
+++ b/libc/malloc_debug/malloc_debug.h
@@ -39,7 +39,7 @@
 // will still be in this order.
 //   Header          (Required)
 //   BacktraceHeader (Optional: For the allocation backtrace)
-//   uint8_t data    (Optional: Front guard, will be a multiple of sizeof(uintptr_t))
+//   uint8_t data    (Optional: Front guard, will be a multiple of MINIMUM_ALIGNMENT_BYTES)
 //   allocation data
 //   uint8_t data    (Optional: End guard)
 //
diff --git a/libc/malloc_debug/tests/malloc_debug_config_tests.cpp b/libc/malloc_debug/tests/malloc_debug_config_tests.cpp
index 551e498..1c800db 100644
--- a/libc/malloc_debug/tests/malloc_debug_config_tests.cpp
+++ b/libc/malloc_debug/tests/malloc_debug_config_tests.cpp
@@ -230,6 +230,10 @@
   ASSERT_EQ(FRONT_GUARD, config->options);
   ASSERT_EQ(40U, config->front_guard_bytes);
 
+  ASSERT_TRUE(InitConfig("front_guard=41"));
+  ASSERT_EQ(FRONT_GUARD, config->options);
+  ASSERT_EQ(48U, config->front_guard_bytes);
+
   ASSERT_STREQ("", getFakeLogBuf().c_str());
   ASSERT_STREQ("", getFakeLogPrint().c_str());
 }
diff --git a/libc/malloc_debug/tests/malloc_debug_unit_tests.cpp b/libc/malloc_debug/tests/malloc_debug_unit_tests.cpp
index 9fc8a57..b316e8a 100644
--- a/libc/malloc_debug/tests/malloc_debug_unit_tests.cpp
+++ b/libc/malloc_debug/tests/malloc_debug_unit_tests.cpp
@@ -34,6 +34,7 @@
 #include <private/bionic_macros.h>
 #include <private/bionic_malloc_dispatch.h>
 
+#include "Config.h"
 #include "malloc_debug.h"
 
 #include "log_fake.h"
@@ -70,9 +71,9 @@
 constexpr uint32_t BACKTRACE_HEADER = 0x1;
 
 static size_t get_tag_offset(uint32_t flags = 0, size_t backtrace_frames = 0) {
-  size_t offset = BIONIC_ALIGN(sizeof(Header), sizeof(uintptr_t));
+  size_t offset = BIONIC_ALIGN(sizeof(Header), MINIMUM_ALIGNMENT_BYTES);
   if (flags & BACKTRACE_HEADER) {
-    offset += BIONIC_ALIGN(sizeof(BacktraceHeader) + sizeof(uintptr_t) * backtrace_frames, sizeof(uintptr_t));
+    offset += BIONIC_ALIGN(sizeof(BacktraceHeader) + sizeof(uintptr_t) * backtrace_frames, MINIMUM_ALIGNMENT_BYTES);
   }
   return offset;
 }
diff --git a/libc/upstream-netbsd/android/include/netbsd-compat.h b/libc/upstream-netbsd/android/include/netbsd-compat.h
index 8d1c46b..665d65e 100644
--- a/libc/upstream-netbsd/android/include/netbsd-compat.h
+++ b/libc/upstream-netbsd/android/include/netbsd-compat.h
@@ -20,17 +20,16 @@
 #define _BSD_SOURCE
 #define _GNU_SOURCE
 
-// NetBSD uses _DIAGASSERT to null-check arguments and the like.
-#include <assert.h>
-#define _DIAGASSERT(e) ((e) ? (void) 0 : __assert2(__FILE__, __LINE__, __func__, #e))
-
-// TODO: update our <sys/cdefs.h> to support this properly.
-#define __type_fit(t, a) (0 == 0)
+// NetBSD uses _DIAGASSERT to null-check arguments and the like,
+// but it's clear from the number of mistakes in their assertions
+// that they don't actually test or ship with this.
+#define _DIAGASSERT(e) /* nothing */
 
 // TODO: we don't yet have thread-safe environment variables.
 #define __readlockenv() 0
 #define __unlockenv() 0
 
+#include <sys/cdefs.h>
 #include <stddef.h>
 __LIBC_HIDDEN__ int reallocarr(void*, size_t, size_t);
 
diff --git a/linker/Android.mk b/linker/Android.mk
index 5bbe172..b940690 100644
--- a/linker/Android.mk
+++ b/linker/Android.mk
@@ -75,7 +75,11 @@
 
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
-LOCAL_STATIC_LIBRARIES := libc_nomalloc liblinker_malloc libziparchive libutils libbase libz liblog
+LOCAL_STATIC_LIBRARIES := libc_nomalloc libziparchive libutils libbase libz liblog
+
+# Important: The liblinker_malloc should be the last library in the list
+# to overwrite any other malloc implementations by other static libraries.
+LOCAL_STATIC_LIBRARIES += liblinker_malloc
 
 LOCAL_FORCE_STATIC_EXECUTABLE := true
 
diff --git a/linker/linker.cpp b/linker/linker.cpp
index a032068..e1e3578 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -216,14 +216,7 @@
 
 static link_map* r_debug_tail = 0;
 
-static void insert_soinfo_into_debug_map(soinfo* info) {
-  // Copy the necessary fields into the debug structure.
-  link_map* map = &(info->link_map_head);
-  map->l_addr = info->load_bias;
-  // link_map l_name field is not const.
-  map->l_name = const_cast<char*>(info->get_realpath());
-  map->l_ld = info->dynamic;
-
+static void insert_link_map_into_debug_map(link_map* map) {
   // Stick the new library at the end of the list.
   // gdb tends to care more about libc than it does
   // about leaf libraries, and ordering it this way
@@ -240,6 +233,17 @@
   r_debug_tail = map;
 }
 
+static void insert_soinfo_into_debug_map(soinfo* info) {
+  // Copy the necessary fields into the debug structure.
+  link_map* map = &(info->link_map_head);
+  map->l_addr = info->load_bias;
+  // link_map l_name field is not const.
+  map->l_name = const_cast<char*>(info->get_realpath());
+  map->l_ld = info->dynamic;
+
+  insert_link_map_into_debug_map(map);
+}
+
 static void remove_soinfo_from_debug_map(soinfo* info) {
   link_map* map = &(info->link_map_head);
 
@@ -3885,21 +3889,6 @@
 #endif
 }
 
-/*
- * This is linker soinfo for GDB. See details below.
- */
-#if defined(__LP64__)
-#define LINKER_PATH "/system/bin/linker64"
-#else
-#define LINKER_PATH "/system/bin/linker"
-#endif
-
-// This is done to avoid calling c-tor prematurely
-// because soinfo c-tor needs memory allocator
-// which might be initialized after global variables.
-static uint8_t linker_soinfo_for_gdb_buf[sizeof(soinfo)] __attribute__((aligned(8)));
-static soinfo* linker_soinfo_for_gdb = nullptr;
-
 /* gdb expects the linker to be in the debug shared object list.
  * Without this, gdb has trouble locating the linker's ".text"
  * and ".plt" sections. Gdb could also potentially use this to
@@ -3908,10 +3897,15 @@
  * be on the soinfo list.
  */
 static void init_linker_info_for_gdb(ElfW(Addr) linker_base) {
-  linker_soinfo_for_gdb = new (linker_soinfo_for_gdb_buf) soinfo(nullptr, LINKER_PATH,
-                                                                 nullptr, 0, 0);
+  static link_map linker_link_map_for_gdb;
+#if defined(__LP64__)
+  static char kLinkerPath[] = "/system/bin/linker64";
+#else
+  static char kLinkerPath[] = "/system/bin/linker";
+#endif
 
-  linker_soinfo_for_gdb->load_bias = linker_base;
+  linker_link_map_for_gdb.l_addr = linker_base;
+  linker_link_map_for_gdb.l_name = kLinkerPath;
 
   /*
    * Set the dynamic field in the link map otherwise gdb will complain with
@@ -3922,8 +3916,9 @@
   ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_base);
   ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_base + elf_hdr->e_phoff);
   phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
-                                 &linker_soinfo_for_gdb->dynamic, nullptr);
-  insert_soinfo_into_debug_map(linker_soinfo_for_gdb);
+                                 &linker_link_map_for_gdb.l_ld, nullptr);
+
+  insert_link_map_into_debug_map(&linker_link_map_for_gdb);
 }
 
 static void init_default_namespace() {
@@ -4017,7 +4012,6 @@
   // Extract information passed from the kernel.
   si->phdr = reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR));
   si->phnum = args.getauxval(AT_PHNUM);
-  si->entry = args.getauxval(AT_ENTRY);
 
   /* Compute the value of si->base. We can't rely on the fact that
    * the first entry is the PHDR because this will not be true
@@ -4146,8 +4140,9 @@
   fflush(stdout);
 #endif
 
-  TRACE("[ Ready to execute '%s' @ %p ]", si->get_realpath(), reinterpret_cast<void*>(si->entry));
-  return si->entry;
+  ElfW(Addr) entry = args.getauxval(AT_ENTRY);
+  TRACE("[ Ready to execute '%s' @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
+  return entry;
 }
 
 /* Compute the load-bias of an existing executable. This shall only
diff --git a/linker/linker.h b/linker/linker.h
index 389c5b3..c669c46 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -173,7 +173,9 @@
  public:
   const ElfW(Phdr)* phdr;
   size_t phnum;
-  ElfW(Addr) entry;
+#if defined(__work_around_b_24465209__)
+  ElfW(Addr) unused0; // DO NOT USE, maintained for compatibility.
+#endif
   ElfW(Addr) base;
   size_t size;
 
diff --git a/tests/malloc_test.cpp b/tests/malloc_test.cpp
index d3a9d01..8fba1c4 100644
--- a/tests/malloc_test.cpp
+++ b/tests/malloc_test.cpp
@@ -430,3 +430,73 @@
   void* p2 = realloc(p, 0);
   ASSERT_TRUE(p2 == nullptr);
 }
+
+constexpr size_t MAX_LOOPS = 200;
+
+// Make sure that memory returned by malloc is aligned to allow these data types.
+TEST(malloc, verify_alignment) {
+  uint32_t** values_32 = new uint32_t*[MAX_LOOPS];
+  uint64_t** values_64 = new uint64_t*[MAX_LOOPS];
+  long double** values_ldouble = new long double*[MAX_LOOPS];
+  // Use filler to attempt to force the allocator to get potentially bad alignments.
+  void** filler = new void*[MAX_LOOPS];
+
+  for (size_t i = 0; i < MAX_LOOPS; i++) {
+    // Check uint32_t pointers.
+    filler[i] = malloc(1);
+    ASSERT_TRUE(filler[i] != nullptr);
+
+    values_32[i] = reinterpret_cast<uint32_t*>(malloc(sizeof(uint32_t)));
+    ASSERT_TRUE(values_32[i] != nullptr);
+    *values_32[i] = i;
+    ASSERT_EQ(*values_32[i], i);
+    ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(values_32[i]) & (sizeof(uint32_t) - 1));
+
+    free(filler[i]);
+  }
+
+  for (size_t i = 0; i < MAX_LOOPS; i++) {
+    // Check uint64_t pointers.
+    filler[i] = malloc(1);
+    ASSERT_TRUE(filler[i] != nullptr);
+
+    values_64[i] = reinterpret_cast<uint64_t*>(malloc(sizeof(uint64_t)));
+    ASSERT_TRUE(values_64[i] != nullptr);
+    *values_64[i] = 0x1000 + i;
+    ASSERT_EQ(*values_64[i], 0x1000 + i);
+    ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(values_64[i]) & (sizeof(uint64_t) - 1));
+
+    free(filler[i]);
+  }
+
+  for (size_t i = 0; i < MAX_LOOPS; i++) {
+    // Check long double pointers.
+    filler[i] = malloc(1);
+    ASSERT_TRUE(filler[i] != nullptr);
+
+    values_ldouble[i] = reinterpret_cast<long double*>(malloc(sizeof(long double)));
+    ASSERT_TRUE(values_ldouble[i] != nullptr);
+    *values_ldouble[i] = 5.5 + i;
+    ASSERT_DOUBLE_EQ(*values_ldouble[i], 5.5 + i);
+    // 32 bit glibc has a long double size of 12 bytes, so hardcode the
+    // required alignment to 0x7.
+#if !defined(__BIONIC__) && !defined(__LP64__)
+    ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(values_ldouble[i]) & 0x7);
+#else
+    ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(values_ldouble[i]) & (sizeof(long double) - 1));
+#endif
+
+    free(filler[i]);
+  }
+
+  for (size_t i = 0; i < MAX_LOOPS; i++) {
+    free(values_32[i]);
+    free(values_64[i]);
+    free(values_ldouble[i]);
+  }
+
+  delete[] filler;
+  delete[] values_32;
+  delete[] values_64;
+  delete[] values_ldouble;
+}
diff --git a/tests/regex_test.cpp b/tests/regex_test.cpp
index 4a4409e..0e7f8dd 100644
--- a/tests/regex_test.cpp
+++ b/tests/regex_test.cpp
@@ -46,3 +46,14 @@
   ASSERT_EQ(2, matches[0].rm_eo);
   regfree(&re);
 }
+
+TEST(regex, regerror_NULL_0) {
+  regex_t re;
+  int error = regcomp(&re, "*", REG_EXTENDED);
+  ASSERT_NE(0, error);
+
+  // Passing a null pointer and a size of 0 is a legitimate way to ask
+  // how large a buffer we would need for the error message.
+  int error_length = regerror(error, &re, nullptr, 0);
+  ASSERT_GT(error_length, 0);
+}
diff --git a/tests/string_test.cpp b/tests/string_test.cpp
index 96b4143..4b2cca2 100644
--- a/tests/string_test.cpp
+++ b/tests/string_test.cpp
@@ -24,6 +24,9 @@
 #include <math.h>
 #include <stdint.h>
 
+#include <algorithm>
+#include <vector>
+
 #include "buffer_tests.h"
 
 #if defined(NOFORTIFY)
@@ -1432,3 +1435,23 @@
   char dst[6];
   ASSERT_EQ(&dst[4], reinterpret_cast<char*>(mempcpy(dst, "hello", 4)));
 }
+
+// clang depends on the fact that a memcpy where src and dst is the same
+// still operates correctly. This test verifies that this assumption
+// holds true.
+// See https://llvm.org/bugs/show_bug.cgi?id=11763 for more information.
+static std::vector<uint8_t> g_memcpy_same_buffer;
+
+static void DoMemcpySameTest(uint8_t* buffer, size_t len) {
+  memcpy(buffer, g_memcpy_same_buffer.data(), len);
+  ASSERT_EQ(buffer, memcpy(buffer, buffer, len));
+  ASSERT_TRUE(memcmp(buffer, g_memcpy_same_buffer.data(), len) == 0);
+}
+
+TEST(STRING_TEST, memcpy_src_dst_same) {
+  g_memcpy_same_buffer.resize(MEDIUM);
+  for (size_t i = 0; i < MEDIUM; i++) {
+    g_memcpy_same_buffer[i] = i;
+  }
+  RunSingleBufferAlignTest(MEDIUM, DoMemcpySameTest);
+}