1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <errno.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 
21 #include <algorithm>
22 #include <memory>
23 #include <string>
24 #include <vector>
25 
26 #include <ziparchive/zip_archive.h>
27 #include <ziparchive/zip_archive_stream_entry.h>
28 #include <ziparchive/zip_writer.h>
29 
usage()30 static void usage() {
31   fprintf(stderr, "usage: bionic_tests_zipalign ALIGNMENT INPUT_ZIP_FILE OUTPUT_ZIP_FILE\n");
32   fprintf(stderr, "  ALIGNMENT:\n");
33   fprintf(stderr, "    The new alignment of all entries in the new zip file.\n");
34   fprintf(stderr, "  INPUT_ZIP_FILE:\n");
35   fprintf(stderr, "    The input zip file that will be read but left unmodified.\n");
36   fprintf(stderr, "  OUTPUT_ZIP_FILE:\n");
37   fprintf(stderr, "    The output zip file that will be created from the input file.\n");
38 }
39 
40 using ZipData = std::pair<std::unique_ptr<ZipEntry>, std::unique_ptr<ZipString>>;
41 
GetEntries(ZipArchiveHandle handle,std::vector<ZipData> * entries)42 static bool GetEntries(ZipArchiveHandle handle, std::vector<ZipData>* entries) {
43   void* cookie;
44   int32_t return_value = StartIteration(handle, &cookie, nullptr, nullptr);
45   if (return_value != 0) {
46     fprintf(stderr, "Unable to iterate over entries: %s\n", ErrorCodeString(return_value));
47     return false;
48   }
49 
50   ZipEntry entry;
51   ZipString name;
52   while ((return_value = Next(cookie, &entry, &name)) == 0) {
53     entries->emplace_back(std::make_pair(std::make_unique<ZipEntry>(entry),
54                                          std::make_unique<ZipString>(name)));
55   }
56   if (return_value != -1) {
57     fprintf(stderr, "Error while iterating over zip entries: %s\n", ErrorCodeString(return_value));
58   } else {
59     // Sort by offset.
60     std::sort(entries->begin(), entries->end(),
61               [](ZipData& a, ZipData& b) { return a.first->offset < b.first->offset; });
62   }
63 
64   EndIteration(cookie);
65   return return_value == -1;
66 }
67 
CreateAlignedZip(ZipArchiveHandle & handle,FILE * zip_dst,uint32_t alignment)68 static bool CreateAlignedZip(ZipArchiveHandle& handle, FILE* zip_dst, uint32_t alignment) {
69   std::vector<ZipData> entries;
70   // We will not free the memory created in entries since the program
71   // terminates right after this function is called.
72   if (!GetEntries(handle, &entries)) {
73     return false;
74   }
75 
76   ZipWriter writer(zip_dst);
77 
78   int32_t error;
79   for (auto& entry : entries) {
80     ZipEntry* zip_entry = entry.first.get();
81     ZipString* zip_str = entry.second.get();
82 
83     size_t flags = 0;
84     if ((zip_entry->method & kCompressDeflated) != 0) {
85       flags |= ZipWriter::kCompress;
86     }
87     std::string zip_name(reinterpret_cast<const char*>(zip_str->name), zip_str->name_length);
88     error = writer.StartAlignedEntry(zip_name.c_str(), flags, alignment);
89     if (error != 0) {
90       fprintf(stderr, "StartAlignedEntry failed: %s\n", ZipWriter::ErrorCodeString(error));
91       return false;
92     }
93     std::unique_ptr<ZipArchiveStreamEntry> stream(
94         ZipArchiveStreamEntry::Create(handle, *zip_entry));
95     const std::vector<uint8_t>* data;
96     while ((data = stream->Read()) != nullptr) {
97       error = writer.WriteBytes(data->data(), data->size());
98       if (error != 0) {
99         fprintf(stderr, "WriteBytes failed: %s\n", ZipWriter::ErrorCodeString(error));
100         return false;
101       }
102     }
103     if (!stream->Verify()) {
104       fprintf(stderr, "Failed to verify zip stream writer entry.\n");
105       return false;
106     }
107     error = writer.FinishEntry();
108     if (error != 0) {
109       fprintf(stderr, "FinishEntry failed: %s\n", ZipWriter::ErrorCodeString(error));
110     }
111   }
112 
113   error = writer.Finish();
114   if (error != 0) {
115     fprintf(stderr, "Finish failed: %s\n", ZipWriter::ErrorCodeString(error));
116     return false;
117   }
118   return true;
119 }
120 
main(int argc,char * argv[])121 int main(int argc, char* argv[]) {
122   if (argc != 4) {
123     usage();
124     return 1;
125   }
126 
127   char* end;
128   unsigned long int alignment = strtoul(argv[1], &end, 10);
129   if ((alignment == ULONG_MAX && errno == ERANGE) || *end != '\0') {
130     fprintf(stderr, "ALIGNMENT value is not a valid number: %s\n", argv[1]);
131     usage();
132     return 1;
133   }
134   if (((alignment - 1) & alignment) != 0) {
135     fprintf(stderr, "ALIGNMENT value is not a power of 2: %s\n", argv[1]);
136     return 1;
137   }
138 
139   ZipArchiveHandle handle;
140 
141   int32_t return_value = OpenArchive(argv[2], &handle);
142   if (return_value != 0) {
143     CloseArchive(handle);
144     fprintf(stderr, "Unable to open '%s': %s\n", argv[2], ErrorCodeString(return_value));
145     return false;
146   }
147 
148   FILE* zip_dst = fopen(argv[3], "we");
149   if (zip_dst == nullptr) {
150     fprintf(stderr, "Unable to create '%s': %s\n", argv[3], strerror(errno));
151     return 1;
152   }
153 
154   bool success = CreateAlignedZip(handle, zip_dst, static_cast<uint32_t>(alignment));
155 
156   CloseArchive(handle);
157   fclose(zip_dst);
158 
159   return success ? 0 : 1;
160 }
161