Merge "Simplify fseek/ftell."
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/Android.mk b/tests/Android.mk
index af8283f..bf0524d 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -321,9 +321,15 @@
     libdl \
     libpagemap \
     libdl_preempt_test_1 \
-    libdl_preempt_test_2
+    libdl_preempt_test_2 \
+    libdl_test_df_1_global \
 
-common_bionic-unit-tests_shared_libraries_target += libdl_test_df_1_global
+# The order of these libraries matters, do not shuffle them.
+common_bionic-unit-tests_static_libraries_target := \
+    libbase \
+    libziparchive \
+    libz \
+    libutils \
 
 module_tag := optional
 build_type := target
@@ -340,6 +346,7 @@
 bionic-unit-tests_ldflags := $(common_bionic-unit-tests_ldflags)
 bionic-unit-tests_c_includes := $(common_bionic-unit-tests_c_includes)
 bionic-unit-tests_shared_libraries_target := $(common_bionic-unit-tests_shared_libraries_target)
+bionic-unit-tests_static_libraries_target := $(common_bionic-unit-tests_static_libraries_target)
 include $(LOCAL_PATH)/Android.build.mk
 
 module := bionic-unit-tests-gcc
@@ -353,6 +360,7 @@
 bionic-unit-tests-gcc_ldflags := $(common_bionic-unit-tests_ldflags)
 bionic-unit-tests-gcc_c_includes := $(common_bionic-unit-tests_c_includes)
 bionic-unit-tests-gcc_shared_libraries_target := $(common_bionic-unit-tests_shared_libraries_target)
+bionic-unit-tests-gcc_static_libraries_target := $(common_bionic-unit-tests_static_libraries_target)
 include $(LOCAL_PATH)/Android.build.mk
 
 # -----------------------------------------------------------------------------
diff --git a/tests/dlext_test.cpp b/tests/dlext_test.cpp
index 261aa55..c221402 100644
--- a/tests/dlext_test.cpp
+++ b/tests/dlext_test.cpp
@@ -30,6 +30,7 @@
 #include <sys/wait.h>
 
 #include <pagemap/pagemap.h>
+#include <ziparchive/zip_archive.h>
 
 #include "TemporaryFile.h"
 #include "utils.h"
@@ -61,8 +62,7 @@
 #define LIBPATH NATIVE_TESTS_PATH "/libdlext_test_fd/libdlext_test_fd.so"
 #define LIBZIPPATH NATIVE_TESTS_PATH "/libdlext_test_zip/libdlext_test_zip_zipaligned.zip"
 #define LIBZIPPATH_WITH_RUNPATH NATIVE_TESTS_PATH "/libdlext_test_runpath_zip/libdlext_test_runpath_zip_zipaligned.zip"
-
-#define LIBZIP_OFFSET PAGE_SIZE
+#define LIBZIP_SIMPLE_ZIP "libdir/libatest_simple_zip.so"
 
 class DlExtTest : public ::testing::Test {
 protected:
@@ -128,7 +128,17 @@
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
   extinfo.library_fd = TEMP_FAILURE_RETRY(open(lib_path.c_str(), O_RDONLY | O_CLOEXEC));
-  extinfo.library_fd_offset = LIBZIP_OFFSET;
+
+  // Find the offset of the shared library in the zip.
+  ZipArchiveHandle handle;
+  ASSERT_EQ(0, OpenArchive(lib_path.c_str(), &handle));
+  ZipEntry zip_entry;
+  ZipString zip_name;
+  zip_name.name = reinterpret_cast<const uint8_t*>(LIBZIP_SIMPLE_ZIP);
+  zip_name.name_length = sizeof(LIBZIP_SIMPLE_ZIP) - 1;
+  ASSERT_EQ(0, FindEntry(handle, zip_name, &zip_entry));
+  extinfo.library_fd_offset = zip_entry.offset;
+  CloseArchive(handle);
 
   handle_ = android_dlopen_ext(lib_path.c_str(), RTLD_NOW, &extinfo);
   ASSERT_DL_NOTNULL(handle_);
@@ -178,10 +188,11 @@
   close(extinfo.library_fd);
 }
 
-TEST_F(DlExtTest, ExtInfoUseOffsetWihtoutFd) {
+TEST_F(DlExtTest, ExtInfoUseOffsetWithoutFd) {
   android_dlextinfo extinfo;
   extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
-  extinfo.library_fd_offset = LIBZIP_OFFSET;
+  // This offset will not be used, so it doesn't matter.
+  extinfo.library_fd_offset = 0;
 
   handle_ = android_dlopen_ext("/some/lib/that/does_not_exist", RTLD_NOW, &extinfo);
   ASSERT_TRUE(handle_ == nullptr);
@@ -275,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);
 
@@ -284,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;
@@ -299,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;
@@ -314,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;
@@ -332,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;
@@ -350,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);
 
@@ -367,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) {
@@ -390,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;
@@ -442,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);
   }
diff --git a/tests/libs/Android.build.dlext_testzip.mk b/tests/libs/Android.build.dlext_testzip.mk
index c06f4a9..56be1e2 100644
--- a/tests/libs/Android.build.dlext_testzip.mk
+++ b/tests/libs/Android.build.dlext_testzip.mk
@@ -18,6 +18,8 @@
 # Library used by dlext tests - zipped and aligned
 # -----------------------------------------------------------------------------
 
+BIONIC_TESTS_ZIPALIGN := $(HOST_OUT_EXECUTABLES)/bionic_tests_zipalign
+
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_CLASS := SHARED_LIBRARIES
@@ -33,12 +35,12 @@
   $($(bionic_2nd_arch_prefix)TARGET_OUT_INTERMEDIATE_LIBRARIES)/libdlext_test_zip.so \
   $($(bionic_2nd_arch_prefix)TARGET_OUT_INTERMEDIATE_LIBRARIES)/libatest_simple_zip.so
 
-$(LOCAL_BUILT_MODULE) : $(my_shared_libs) | $(ZIPALIGN)
-	@echo "Zipalign: $@"
+$(LOCAL_BUILT_MODULE) : $(my_shared_libs) | $(BIONIC_TESTS_ZIPALIGN)
+	@echo "Aligning zip: $@"
 	$(hide) rm -rf $(dir $@) && mkdir -p $(dir $@)/libdir
 	$(hide) cp $^ $(dir $@)/libdir
 	$(hide) (cd $(dir $@) && touch empty_file.txt && zip -qrD0 $(notdir $@).unaligned empty_file.txt libdir/*.so)
-	$(hide) $(ZIPALIGN) -p 4 $@.unaligned $@
+	$(hide) $(BIONIC_TESTS_ZIPALIGN) 4096 $@.unaligned $@
 
 include $(CLEAR_VARS)
 
@@ -68,8 +70,8 @@
   $($(bionic_2nd_arch_prefix)TARGET_OUT_INTERMEDIATE_LIBRARIES)/libtest_dt_runpath_c.so
 $(LOCAL_BUILT_MODULE) : PRIVATE_LIB_X := \
   $($(bionic_2nd_arch_prefix)TARGET_OUT_INTERMEDIATE_LIBRARIES)/libtest_dt_runpath_x.so
-$(LOCAL_BUILT_MODULE) : $(my_shared_libs) | $(ZIPALIGN)
-	@echo "Zipalign: $@"
+$(LOCAL_BUILT_MODULE) : $(my_shared_libs) | $(BIONIC_TESTS_ZIPALIGN)
+	@echo "Aligning zip: $@"
 	$(hide) rm -rf $(dir $@) && mkdir -p $(dir $@)/libdir && \
     mkdir -p $(dir $@)/libdir/dt_runpath_a && mkdir -p $(dir $@)/libdir/dt_runpath_b_c_x
 	$(hide) cp $(PRIVATE_LIB_D) $(dir $@)/libdir
@@ -78,5 +80,5 @@
 	$(hide) cp $(PRIVATE_LIB_C) $(dir $@)/libdir/dt_runpath_b_c_x
 	$(hide) cp $(PRIVATE_LIB_X) $(dir $@)/libdir/dt_runpath_b_c_x
 	$(hide) (cd $(dir $@) && touch empty_file.txt && zip -qrD0 $(notdir $@).unaligned empty_file.txt libdir)
-	$(hide) $(ZIPALIGN) -p 4 $@.unaligned $@
+	$(hide) $(BIONIC_TESTS_ZIPALIGN) 4096 $@.unaligned $@
 
diff --git a/tests/libs/Android.mk b/tests/libs/Android.mk
index 93d95ee..506d6f2 100644
--- a/tests/libs/Android.mk
+++ b/tests/libs/Android.mk
@@ -486,3 +486,18 @@
 
 module := libtest_dlopen_from_ctor_main
 include $(LOCAL_PATH)/Android.build.testlib.mk
+
+# -----------------------------------------------------------------------------
+# Tool to use to align the shared libraries in a zip file.
+# -----------------------------------------------------------------------------
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := bionic_tests_zipalign.cpp
+LOCAL_MODULE := bionic_tests_zipalign
+LOCAL_CFLAGS := -Wall -Werror
+
+LOCAL_STATIC_LIBRARIES := libziparchive-host liblog libbase libz libutils
+
+LOCAL_MODULE_HOST_OS := darwin linux windows
+
+include $(BUILD_HOST_EXECUTABLE)
diff --git a/tests/libs/bionic_tests_zipalign.cpp b/tests/libs/bionic_tests_zipalign.cpp
new file mode 100644
index 0000000..dbbfd7c
--- /dev/null
+++ b/tests/libs/bionic_tests_zipalign.cpp
@@ -0,0 +1,157 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <algorithm>
+#include <string>
+#include <vector>
+
+#include <ziparchive/zip_archive.h>
+#include <ziparchive/zip_archive_stream_entry.h>
+#include <ziparchive/zip_writer.h>
+
+static void usage() {
+  fprintf(stderr, "usage: bionic_tests_zipalign ALIGNMENT INPUT_ZIP_FILE OUTPUT_ZIP_FILE\n");
+  fprintf(stderr, "  ALIGNMENT:\n");
+  fprintf(stderr, "    The new alignment of all entries in the new zip file.\n");
+  fprintf(stderr, "  INPUT_ZIP_FILE:\n");
+  fprintf(stderr, "    The input zip file that will be read but left unmodified.\n");
+  fprintf(stderr, "  OUTPUT_ZIP_FILE:\n");
+  fprintf(stderr, "    The output zip file that will be created from the input file.\n");
+}
+
+typedef std::pair<ZipEntry*, ZipString*> ZipData;
+
+static bool GetEntries(ZipArchiveHandle handle, std::vector<ZipData>* entries) {
+  void* cookie;
+  int32_t return_value = StartIteration(handle, &cookie, nullptr, nullptr);
+  if (return_value != 0) {
+    fprintf(stderr, "Unable to iterate over entries: %s\n", ErrorCodeString(return_value));
+    return false;
+  }
+
+  ZipEntry entry;
+  ZipString name;
+  while ((return_value = Next(cookie, &entry, &name)) == 0) {
+    entries->push_back(std::make_pair(new ZipEntry(entry), new ZipString(name)));
+  }
+  if (return_value != -1) {
+    fprintf(stderr, "Error while iterating over zip entries: %s\n", ErrorCodeString(return_value));
+  } else {
+    // Sort by offset.
+    std::sort(entries->begin(), entries->end(),
+              [](ZipData a, ZipData b) { return a.first->offset < b.first->offset; });
+  }
+
+  EndIteration(cookie);
+  return return_value == -1;
+}
+
+static bool CreateAlignedZip(ZipArchiveHandle& handle, FILE* zip_dst, uint32_t alignment) {
+  std::vector<ZipData> entries;
+  // We will not free the memory created in entries since the program
+  // terminates right after this function is called.
+  if (!GetEntries(handle, &entries)) {
+    return false;
+  }
+
+  ZipWriter writer(zip_dst);
+
+  int32_t error;
+  for (auto& entry : entries) {
+    ZipEntry* zip_entry = entry.first;
+    ZipString* zip_str = entry.second;
+
+    size_t flags = 0;
+    if ((zip_entry->method & kCompressDeflated) != 0) {
+      flags |= ZipWriter::kCompress;
+    }
+    std::string zip_name(reinterpret_cast<const char*>(zip_str->name), zip_str->name_length);
+    error = writer.StartAlignedEntry(zip_name.c_str(), flags, alignment);
+    if (error != 0) {
+      fprintf(stderr, "StartAlignedEntry failed: %s\n", ZipWriter::ErrorCodeString(error));
+      return false;
+    }
+    std::unique_ptr<ZipArchiveStreamEntry> stream(
+        ZipArchiveStreamEntry::Create(handle, *zip_entry));
+    const std::vector<uint8_t>* data;
+    while ((data = stream->Read()) != nullptr) {
+      error = writer.WriteBytes(data->data(), data->size());
+      if (error != 0) {
+        fprintf(stderr, "WriteBytes failed: %s\n", ZipWriter::ErrorCodeString(error));
+        return false;
+      }
+    }
+    if (!stream->Verify()) {
+      fprintf(stderr, "Failed to verify zip stream writer entry.\n");
+      return false;
+    }
+    error = writer.FinishEntry();
+    if (error != 0) {
+      fprintf(stderr, "FinishEntry failed: %s\n", ZipWriter::ErrorCodeString(error));
+    }
+  }
+
+  error = writer.Finish();
+  if (error != 0) {
+    fprintf(stderr, "Finish failed: %s\n", ZipWriter::ErrorCodeString(error));
+    return false;
+  }
+  return true;
+}
+
+int main(int argc, char* argv[]) {
+  if (argc != 4) {
+    usage();
+    return 1;
+  }
+
+  char* end;
+  unsigned long int alignment = strtoul(argv[1], &end, 10);
+  if ((alignment == ULONG_MAX && errno == ERANGE) || *end != '\0') {
+    fprintf(stderr, "ALIGNMENT value is not a valid number: %s\n", argv[1]);
+    usage();
+    return 1;
+  }
+  if (((alignment - 1) & alignment) != 0) {
+    fprintf(stderr, "ALIGNMENT value is not a power of 2: %s\n", argv[1]);
+    return 1;
+  }
+
+  ZipArchiveHandle handle;
+
+  int32_t return_value = OpenArchive(argv[2], &handle);
+  if (return_value != 0) {
+    fprintf(stderr, "Unable to open '%s': %s\n", argv[2], ErrorCodeString(return_value));
+    return false;
+  }
+
+  FILE* zip_dst = fopen(argv[3], "we");
+  if (zip_dst == nullptr) {
+    fprintf(stderr, "Unable to create '%s': %s\n", argv[3], strerror(errno));
+    return 1;
+  }
+
+  bool success = CreateAlignedZip(handle, zip_dst, static_cast<uint32_t>(alignment));
+
+  CloseArchive(handle);
+  fclose(zip_dst);
+
+  return success ? 0 : 1;
+}