Merge "Remove dependency on zipalign."
diff --git a/libc/Android.bp b/libc/Android.bp
index 35453c5..47d076d 100644
--- a/libc/Android.bp
+++ b/libc/Android.bp
@@ -6,8 +6,6 @@
     "bionic/ether_ntoa.c",
     "bionic/fts.c",
     "bionic/getpriority.c",
-    "bionic/if_indextoname.c",
-    "bionic/if_nametoindex.c",
     "bionic/initgroups.c",
     "bionic/isatty.c",
     "bionic/memmem.c",
@@ -236,12 +234,9 @@
         "upstream-netbsd/lib/libc/isc/ev_streams.c",
         "upstream-netbsd/lib/libc/isc/ev_timers.c",
         "upstream-netbsd/lib/libc/resolv/mtctxres.c",
-        // We use the OpenBSD res_random.
-        "upstream-openbsd/lib/libc/net/res_random.c",
     ],
 
     cflags: [
-        "-Dres_randomid=__res_randomid",
         "-DANDROID_CHANGES",
         "-DINET6",
         "-fvisibility=hidden",
@@ -474,10 +469,10 @@
         "upstream-openbsd/lib/libc/net/inet_pton.c",
         "upstream-openbsd/lib/libc/net/ntohl.c",
         "upstream-openbsd/lib/libc/net/ntohs.c",
+        "upstream-openbsd/lib/libc/net/res_random.c",
         "upstream-openbsd/lib/libc/stdio/asprintf.c",
         "upstream-openbsd/lib/libc/stdio/clrerr.c",
         "upstream-openbsd/lib/libc/stdio/dprintf.c",
-        "upstream-openbsd/lib/libc/stdio/fclose.c",
         "upstream-openbsd/lib/libc/stdio/fdopen.c",
         "upstream-openbsd/lib/libc/stdio/feof.c",
         "upstream-openbsd/lib/libc/stdio/ferror.c",
@@ -488,7 +483,6 @@
         "upstream-openbsd/lib/libc/stdio/fgets.c",
         "upstream-openbsd/lib/libc/stdio/fgetwc.c",
         "upstream-openbsd/lib/libc/stdio/fgetws.c",
-        "upstream-openbsd/lib/libc/stdio/fileno.c",
         "upstream-openbsd/lib/libc/stdio/flags.c",
         "upstream-openbsd/lib/libc/stdio/fmemopen.c",
         "upstream-openbsd/lib/libc/stdio/fopen.c",
@@ -1308,6 +1302,7 @@
         "bionic/arpa_inet.cpp",
         "bionic/assert.cpp",
         "bionic/atof.cpp",
+        "bionic/bionic_netlink.cpp",
         "bionic/bionic_systrace.cpp",
         "bionic/bionic_time_conversions.cpp",
         "bionic/brk.cpp",
@@ -1374,6 +1369,7 @@
         "bionic/mntent.cpp",
         "bionic/mremap.cpp",
         "bionic/NetdClientDispatch.cpp",
+        "bionic/net_if.cpp",
         "bionic/open.cpp",
         "bionic/pathconf.cpp",
         "bionic/pause.cpp",
diff --git a/libc/Android.mk b/libc/Android.mk
index 45f419a..2609644 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -54,12 +54,11 @@
     bionic/siginterrupt.c \
     bionic/sigsetmask.c \
     bionic/system_properties_compat.c \
-    stdio/findfp.c \
     stdio/fread.c \
     stdio/refill.c \
     stdio/snprintf.c\
     stdio/sprintf.c \
-    stdio/stdio.c \
+    stdio/stdio.cpp \
     stdio/stdio_ext.cpp \
     stdlib/atexit.c \
     stdlib/exit.c \
diff --git a/libc/stdio/stdio.c b/libc/stdio/stdio.c
deleted file mode 100644
index fc2115e..0000000
--- a/libc/stdio/stdio.c
+++ /dev/null
@@ -1,90 +0,0 @@
-/*	$OpenBSD: stdio.c,v 1.9 2005/08/08 08:05:36 espie Exp $ */
-/*-
- * Copyright (c) 1990, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Chris Torek.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <stdio.h>
-#include "local.h"
-
-/*
- * Small standard I/O/seek/close functions.
- * These maintain the `known seek offset' for seek optimisation.
- */
-int
-__sread(void *cookie, char *buf, int n)
-{
-	FILE *fp = cookie;
-	int ret;
-	
-	ret = TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
-	/* if the read succeeded, update the current offset */
-	if (ret >= 0)
-		fp->_offset += ret;
-	else
-		fp->_flags &= ~__SOFF;	/* paranoia */
-	return (ret);
-}
-
-int
-__swrite(void *cookie, const char *buf, int n)
-{
-	FILE *fp = cookie;
-
-	if (fp->_flags & __SAPP)
-		(void) TEMP_FAILURE_RETRY(lseek(fp->_file, (off_t)0, SEEK_END));
-	fp->_flags &= ~__SOFF;	/* in case FAPPEND mode is set */
-	return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
-}
-
-fpos_t
-__sseek(void *cookie, fpos_t offset, int whence)
-{
-	FILE *fp = cookie;
-	off_t ret;
-	
-	ret = TEMP_FAILURE_RETRY(lseek(fp->_file, (off_t)offset, whence));
-	if (ret == (off_t)-1)
-		fp->_flags &= ~__SOFF;
-	else {
-		fp->_flags |= __SOFF;
-		fp->_offset = ret;
-	}
-	return (ret);
-}
-
-int
-__sclose(void *cookie)
-{
-	return close(((FILE *)cookie)->_file);
-}
diff --git a/libc/stdio/findfp.c b/libc/stdio/stdio.cpp
similarity index 72%
rename from libc/stdio/findfp.c
rename to libc/stdio/stdio.cpp
index 2a6be15..1ea3ef5 100644
--- a/libc/stdio/findfp.c
+++ b/libc/stdio/stdio.cpp
@@ -31,12 +31,15 @@
  * SUCH DAMAGE.
  */
 
-#include <sys/param.h>
-#include <unistd.h>
 #include <stdio.h>
+
 #include <errno.h>
+#include <fcntl.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/param.h>
+#include <unistd.h>
+
 #include "local.h"
 #include "glue.h"
 #include "private/thread_private.h"
@@ -82,41 +85,31 @@
 struct glue __sglue = { NULL, 3, __sF };
 static struct glue* lastglue = &__sglue;
 
-static struct glue *
-moreglue(int n)
-{
-	struct glue *g;
-	FILE *p;
-	struct __sfileext *pext;
-	static FILE empty;
-	char *data;
+static glue* moreglue(int n) {
+    static FILE empty;
 
-	data = malloc(sizeof(*g) + ALIGNBYTES + n * sizeof(FILE)
-	    + n * sizeof(struct __sfileext));
-	if (data == NULL)
-		return (NULL);
-	g = (struct glue *)data;
-	p = (FILE *)ALIGN(data + sizeof(*g));
-	pext = (struct __sfileext *)
-	    (ALIGN(data + sizeof(*g)) + n * sizeof(FILE));
-	g->next = NULL;
-	g->niobs = n;
-	g->iobs = p;
-	while (--n >= 0) {
-		*p = empty;
-		_FILEEXT_SETUP(p, pext);
-		p++;
-		pext++;
-	}
-	return (g);
+    char* data = new char[sizeof(glue) + ALIGNBYTES + n * sizeof(FILE) + n * sizeof(__sfileext)];
+    if (data == nullptr) return nullptr;
+
+    glue* g = reinterpret_cast<glue*>(data);
+    FILE* p = reinterpret_cast<FILE*>(ALIGN(data + sizeof(*g)));
+    __sfileext* pext = reinterpret_cast<__sfileext*>(ALIGN(data + sizeof(*g)) + n * sizeof(FILE));
+    g->next = NULL;
+    g->niobs = n;
+    g->iobs = p;
+    while (--n >= 0) {
+        *p = empty;
+        _FILEEXT_SETUP(p, pext);
+        p++;
+        pext++;
+    }
+    return g;
 }
 
 /*
  * Find a free FILE for fopen et al.
  */
-FILE *
-__sfp(void)
-{
+FILE* __sfp(void) {
 	FILE *fp;
 	int n;
 	struct glue *g;
@@ -153,7 +146,7 @@
 	return (fp);
 }
 
-__LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
+extern "C" __LIBC_HIDDEN__ void __libc_stdio_cleanup(void) {
 	/* (void) _fwalk(fclose); */
 	(void) _fwalk(__sflush);		/* `cheating' */
 }
@@ -191,3 +184,44 @@
     FUNLOCKFILE(fp);
     return result;
 }
+
+// Small standard I/O/seek/close functions.
+// These maintain the `known seek offset' for seek optimisation.
+int __sread(void* cookie, char* buf, int n) {
+    FILE* fp = reinterpret_cast<FILE*>(cookie);
+    int ret = TEMP_FAILURE_RETRY(read(fp->_file, buf, n));
+    // If the read succeeded, update the current offset.
+    if (ret >= 0) {
+        fp->_offset += ret;
+    } else {
+        fp->_flags &= ~__SOFF; // Paranoia.
+    }
+    return ret;
+}
+
+int __swrite(void* cookie, const char* buf, int n) {
+    FILE* fp = reinterpret_cast<FILE*>(cookie);
+    if (fp->_flags & __SAPP) {
+        (void) TEMP_FAILURE_RETRY(lseek(fp->_file, 0, SEEK_END));
+    }
+    fp->_flags &= ~__SOFF; // In case FAPPEND mode is set.
+    return TEMP_FAILURE_RETRY(write(fp->_file, buf, n));
+}
+
+// TODO: _FILE_OFFSET_BITS=64.
+fpos_t __sseek(void* cookie, fpos_t offset, int whence) {
+    FILE* fp = reinterpret_cast<FILE*>(cookie);
+    off_t ret = TEMP_FAILURE_RETRY(lseek(fp->_file, offset, whence));
+    if (ret == -1) {
+        fp->_flags &= ~__SOFF;
+    } else {
+        fp->_flags |= __SOFF;
+        fp->_offset = ret;
+    }
+    return ret;
+}
+
+int __sclose(void* cookie) {
+    FILE* fp = reinterpret_cast<FILE*>(cookie);
+    return close(fp->_file);
+}
diff --git a/linker/linker.cpp b/linker/linker.cpp
index 70c2ca5..1c1650e 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -356,7 +356,13 @@
   }
 
   if (si->base != 0 && si->size != 0) {
-    munmap(reinterpret_cast<void*>(si->base), si->size);
+    if (!si->is_mapped_by_caller()) {
+      munmap(reinterpret_cast<void*>(si->base), si->size);
+    } else {
+      // remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
+      mmap(reinterpret_cast<void*>(si->base), si->size, PROT_NONE,
+           MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
+    }
   }
 
   soinfo *prev = nullptr, *trav;
@@ -1160,6 +1166,7 @@
 
     si_->base = elf_reader.load_start();
     si_->size = elf_reader.load_size();
+    si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
     si_->load_bias = elf_reader.load_bias();
     si_->phnum = elf_reader.phdr_count();
     si_->phdr = elf_reader.loaded_phdr();
@@ -3248,6 +3255,19 @@
   return local_group_root_;
 }
 
+
+void soinfo::set_mapped_by_caller(bool mapped_by_caller) {
+  if (mapped_by_caller) {
+    flags_ |= FLAG_MAPPED_BY_CALLER;
+  } else {
+    flags_ &= ~FLAG_MAPPED_BY_CALLER;
+  }
+}
+
+bool soinfo::is_mapped_by_caller() const {
+  return (flags_ & FLAG_MAPPED_BY_CALLER) != 0;
+}
+
 // This function returns api-level at the time of
 // dlopen/load. Note that libraries opened by system
 // will always have 'current' api level.
diff --git a/linker/linker.h b/linker/linker.h
index 5a06853..389c5b3 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -79,11 +79,13 @@
 #define ELF64_R_TYPE(info)  (((info) >> 56) & 0xff)
 #endif
 
-#define FLAG_LINKED     0x00000001
-#define FLAG_EXE        0x00000004 // The main executable
-#define FLAG_LINKER     0x00000010 // The linker itself
-#define FLAG_GNU_HASH   0x00000040 // uses gnu hash
-#define FLAG_NEW_SOINFO 0x40000000 // new soinfo format
+#define FLAG_LINKED           0x00000001
+#define FLAG_EXE              0x00000004 // The main executable
+#define FLAG_LINKER           0x00000010 // The linker itself
+#define FLAG_GNU_HASH         0x00000040 // uses gnu hash
+#define FLAG_MAPPED_BY_CALLER 0x00000080 // the map is reserved by the caller
+                                         // and should not be unmapped
+#define FLAG_NEW_SOINFO       0x40000000 // new soinfo format
 
 #define SUPPORTED_DT_FLAGS_1 (DF_1_NOW | DF_1_GLOBAL | DF_1_NODELETE)
 
@@ -337,6 +339,9 @@
   const std::vector<std::string>& get_dt_runpath() const;
   android_namespace_t* get_namespace();
 
+  void set_mapped_by_caller(bool reserved_map);
+  bool is_mapped_by_caller() const;
+
  private:
   bool elf_lookup(SymbolName& symbol_name, const version_info* vi, uint32_t* symbol_index) const;
   ElfW(Sym)* elf_addr_lookup(const void* addr);
diff --git a/linker/linker_phdr.cpp b/linker/linker_phdr.cpp
index 4c4ce17..e81e325 100644
--- a/linker/linker_phdr.cpp
+++ b/linker/linker_phdr.cpp
@@ -137,7 +137,8 @@
 ElfReader::ElfReader()
     : did_read_(false), did_load_(false), fd_(-1), file_offset_(0), file_size_(0), phdr_num_(0),
       phdr_table_(nullptr), shdr_table_(nullptr), shdr_num_(0), dynamic_(nullptr), strtab_(nullptr),
-      strtab_size_(0), load_start_(nullptr), load_size_(0), load_bias_(0), loaded_phdr_(nullptr) {
+      strtab_size_(0), load_start_(nullptr), load_size_(0), load_bias_(0), loaded_phdr_(nullptr),
+      mapped_by_caller_(false) {
 }
 
 bool ElfReader::Read(const char* name, int fd, off64_t file_offset, off64_t file_size) {
@@ -467,6 +468,7 @@
     }
   } else {
     start = extinfo->reserved_addr;
+    mapped_by_caller_ = true;
   }
 
   load_start_ = start;
diff --git a/linker/linker_phdr.h b/linker/linker_phdr.h
index c359cca..89ec094 100644
--- a/linker/linker_phdr.h
+++ b/linker/linker_phdr.h
@@ -53,6 +53,7 @@
   const ElfW(Phdr)* loaded_phdr() const { return loaded_phdr_; }
   const ElfW(Dyn)* dynamic() const { return dynamic_; }
   const char* get_string(ElfW(Word) index) const;
+  bool is_mapped_by_caller() const { return mapped_by_caller_; }
 
  private:
   bool ReadElfHeader();
@@ -99,6 +100,9 @@
 
   // Loaded phdr.
   const ElfW(Phdr)* loaded_phdr_;
+
+  // Is map owned by the caller
+  bool mapped_by_caller_;
 };
 
 size_t phdr_table_get_load_size(const ElfW(Phdr)* phdr_table, size_t phdr_count,
diff --git a/tests/dlext_test.cpp b/tests/dlext_test.cpp
index 00eea58..c221402 100644
--- a/tests/dlext_test.cpp
+++ b/tests/dlext_test.cpp
@@ -286,7 +286,8 @@
   ASSERT_TRUE(fn != nullptr);
   EXPECT_EQ(4, fn());
 
-  uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_testlib_taxicab_number"));
+  uint32_t* taxicab_number =
+          reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_testlib_taxicab_number"));
   ASSERT_DL_NOTNULL(taxicab_number);
   EXPECT_EQ(1729U, *taxicab_number);
 
@@ -295,8 +296,7 @@
 
 
 TEST_F(DlExtTest, Reserved) {
-  void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
-                     -1, 0);
+  void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   ASSERT_TRUE(start != MAP_FAILED);
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
@@ -310,11 +310,17 @@
   EXPECT_LT(reinterpret_cast<void*>(f),
             reinterpret_cast<char*>(start) + LIBSIZE);
   EXPECT_EQ(4, f());
+
+  // Check that after dlclose reserved address space is unmapped (and can be reused)
+  dlclose(handle_);
+  handle_ = nullptr;
+
+  void* new_start = mmap(start, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+  ASSERT_NE(start, new_start) << "dlclose unmapped reserved space";
 }
 
 TEST_F(DlExtTest, ReservedTooSmall) {
-  void* start = mmap(nullptr, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
-                     -1, 0);
+  void* start = mmap(nullptr, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   ASSERT_TRUE(start != MAP_FAILED);
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
@@ -325,8 +331,7 @@
 }
 
 TEST_F(DlExtTest, ReservedHint) {
-  void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
-                     -1, 0);
+  void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   ASSERT_TRUE(start != MAP_FAILED);
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS_HINT;
@@ -343,8 +348,7 @@
 }
 
 TEST_F(DlExtTest, ReservedHintTooSmall) {
-  void* start = mmap(nullptr, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
-                     -1, 0);
+  void* start = mmap(nullptr, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   ASSERT_TRUE(start != MAP_FAILED);
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_RESERVED_ADDRESS_HINT;
@@ -361,8 +365,7 @@
 }
 
 TEST_F(DlExtTest, LoadAtFixedAddress) {
-  void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
-                     -1, 0);
+  void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
   ASSERT_TRUE(start != MAP_FAILED);
   munmap(start, LIBSIZE);
 
@@ -378,6 +381,12 @@
   EXPECT_LT(reinterpret_cast<void*>(f), reinterpret_cast<char*>(start) + LIBSIZE);
 
   EXPECT_EQ(4, f());
+  dlclose(handle_);
+  handle_ = nullptr;
+
+  // Check that dlclose unmapped the file
+  void* addr = mmap(start, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+  ASSERT_EQ(start, addr) << "dlclose did not unmap the memory";
 }
 
 TEST_F(DlExtTest, LoadAtFixedAddressTooSmall) {
@@ -401,8 +410,7 @@
 protected:
   virtual void SetUp() {
     DlExtTest::SetUp();
-    void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
-                       -1, 0);
+    void* start = mmap(nullptr, LIBSIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
     ASSERT_TRUE(start != MAP_FAILED);
     extinfo_.flags = ANDROID_DLEXT_RESERVED_ADDRESS;
     extinfo_.reserved_addr = start;
@@ -453,7 +461,8 @@
     ASSERT_DL_NOTNULL(f);
     EXPECT_EQ(4, f());
 
-    uint32_t* taxicab_number = reinterpret_cast<uint32_t*>(dlsym(handle_, "dlopen_testlib_taxicab_number"));
+    uint32_t* taxicab_number =
+            reinterpret_cast<uint32_t*>(dlsym(handle_, "dlopen_testlib_taxicab_number"));
     ASSERT_DL_NOTNULL(taxicab_number);
     EXPECT_EQ(1729U, *taxicab_number);
   }