1 /*
2  * Copyright (C) 2008 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 "zip_archive.h"
18 
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 #include <vector>
25 
26 #include "android-base/stringprintf.h"
27 #include "ziparchive/zip_archive.h"
28 
29 #include "base/mman.h"
30 #include "bit_utils.h"
31 #include "unix_file/fd_file.h"
32 
33 namespace art {
34 
35 // Log file contents and mmap info when mapping entries directly.
36 static constexpr const bool kDebugZipMapDirectly = false;
37 
38 using android::base::StringPrintf;
39 
GetUncompressedLength()40 uint32_t ZipEntry::GetUncompressedLength() {
41   return zip_entry_->uncompressed_length;
42 }
43 
GetCrc32()44 uint32_t ZipEntry::GetCrc32() {
45   return zip_entry_->crc32;
46 }
47 
IsUncompressed()48 bool ZipEntry::IsUncompressed() {
49   return zip_entry_->method == kCompressStored;
50 }
51 
IsAlignedTo(size_t alignment) const52 bool ZipEntry::IsAlignedTo(size_t alignment) const {
53   DCHECK(IsPowerOfTwo(alignment)) << alignment;
54   return IsAlignedParam(zip_entry_->offset, static_cast<int>(alignment));
55 }
56 
~ZipEntry()57 ZipEntry::~ZipEntry() {
58   delete zip_entry_;
59 }
60 
ExtractToFile(File & file,std::string * error_msg)61 bool ZipEntry::ExtractToFile(File& file, std::string* error_msg) {
62   const int32_t error = ExtractEntryToFile(handle_, zip_entry_, file.Fd());
63   if (error != 0) {
64     *error_msg = std::string(ErrorCodeString(error));
65     return false;
66   }
67 
68   return true;
69 }
70 
ExtractToMemMap(const char * zip_filename,const char * entry_filename,std::string * error_msg)71 MemMap ZipEntry::ExtractToMemMap(const char* zip_filename,
72                                  const char* entry_filename,
73                                  std::string* error_msg) {
74   std::string name(entry_filename);
75   name += " extracted in memory from ";
76   name += zip_filename;
77   MemMap map = MemMap::MapAnonymous(name.c_str(),
78                                     GetUncompressedLength(),
79                                     PROT_READ | PROT_WRITE,
80                                     /*low_4gb=*/ false,
81                                     error_msg);
82   if (!map.IsValid()) {
83     DCHECK(!error_msg->empty());
84     return MemMap::Invalid();
85   }
86 
87   DCHECK_EQ(map.Size(), GetUncompressedLength());
88   if (!ExtractToMemory(map.Begin(), error_msg)) {
89     return MemMap::Invalid();
90   }
91 
92   return map;
93 }
94 
ExtractToMemory(uint8_t * buffer,std::string * error_msg)95 bool ZipEntry::ExtractToMemory(/*out*/uint8_t* buffer, /*out*/std::string* error_msg) {
96   const int32_t error = ::ExtractToMemory(handle_, zip_entry_, buffer, GetUncompressedLength());
97   if (error != 0) {
98     *error_msg = std::string(ErrorCodeString(error));
99     return false;
100   }
101   return true;
102 }
103 
MapDirectlyFromFile(const char * zip_filename,std::string * error_msg)104 MemMap ZipEntry::MapDirectlyFromFile(const char* zip_filename, std::string* error_msg) {
105   const int zip_fd = GetFileDescriptor(handle_);
106   const char* entry_filename = entry_name_.c_str();
107 
108   // Should not happen since we don't have a memory ZipArchive constructor.
109   // However the underlying ZipArchive isn't required to have an FD,
110   // so check to be sure.
111   CHECK_GE(zip_fd, 0) <<
112       StringPrintf("Cannot map '%s' (in zip '%s') directly because the zip archive "
113                    "is not file backed.",
114                    entry_filename,
115                    zip_filename);
116 
117   if (!IsUncompressed()) {
118     *error_msg = StringPrintf("Cannot map '%s' (in zip '%s') directly because it is compressed.",
119                               entry_filename,
120                               zip_filename);
121     return MemMap::Invalid();
122   } else if (zip_entry_->uncompressed_length != zip_entry_->compressed_length) {
123     *error_msg = StringPrintf("Cannot map '%s' (in zip '%s') directly because "
124                               "entry has bad size (%u != %u).",
125                               entry_filename,
126                               zip_filename,
127                               zip_entry_->uncompressed_length,
128                               zip_entry_->compressed_length);
129     return MemMap::Invalid();
130   }
131 
132   std::string name(entry_filename);
133   name += " mapped directly in memory from ";
134   name += zip_filename;
135 
136   const off_t offset = zip_entry_->offset;
137 
138   if (kDebugZipMapDirectly) {
139     LOG(INFO) << "zip_archive: " << "make mmap of " << name << " @ offset = " << offset;
140   }
141 
142   MemMap map =
143       MemMap::MapFile(GetUncompressedLength(),  // Byte count
144                       PROT_READ | PROT_WRITE,
145                       MAP_PRIVATE,
146                       zip_fd,
147                       offset,
148                       /*low_4gb=*/ false,
149                       name.c_str(),
150                       error_msg);
151 
152   if (!map.IsValid()) {
153     DCHECK(!error_msg->empty());
154   }
155 
156   if (kDebugZipMapDirectly) {
157     // Dump contents of file, same format as using this shell command:
158     // $> od -j <offset> -t x1 <zip_filename>
159     static constexpr const int kMaxDumpChars = 15;
160     lseek(zip_fd, 0, SEEK_SET);
161 
162     int count = offset + kMaxDumpChars;
163 
164     std::string tmp;
165     char buf;
166 
167     // Dump file contents.
168     int i = 0;
169     while (read(zip_fd, &buf, 1) > 0 && i < count) {
170       tmp += StringPrintf("%3d ", (unsigned int)buf);
171       ++i;
172     }
173 
174     LOG(INFO) << "map_fd raw bytes starting at 0";
175     LOG(INFO) << "" << tmp;
176     LOG(INFO) << "---------------------------";
177 
178     // Dump map contents.
179     if (map.IsValid()) {
180       tmp = "";
181 
182       count = kMaxDumpChars;
183 
184       uint8_t* begin = map.Begin();
185       for (i = 0; i < count; ++i) {
186         tmp += StringPrintf("%3d ", (unsigned int)begin[i]);
187       }
188 
189       LOG(INFO) << "map address " << StringPrintf("%p", begin);
190       LOG(INFO) << "map first " << kMaxDumpChars << " chars:";
191       LOG(INFO) << tmp;
192     }
193   }
194 
195   return map;
196 }
197 
MapDirectlyOrExtract(const char * zip_filename,const char * entry_filename,std::string * error_msg,size_t alignment)198 MemMap ZipEntry::MapDirectlyOrExtract(const char* zip_filename,
199                                       const char* entry_filename,
200                                       std::string* error_msg,
201                                       size_t alignment) {
202   if (IsUncompressed() && IsAlignedTo(alignment) && GetFileDescriptor(handle_) >= 0) {
203     std::string local_error_msg;
204     MemMap ret = MapDirectlyFromFile(zip_filename, &local_error_msg);
205     if (ret.IsValid()) {
206       return ret;
207     }
208     // Fall back to extraction for the failure case.
209   }
210   return ExtractToMemMap(zip_filename, entry_filename, error_msg);
211 }
212 
SetCloseOnExec(int fd)213 static void SetCloseOnExec(int fd) {
214 #ifdef _WIN32
215   // Exec is not supported on Windows.
216   UNUSED(fd);
217   PLOG(ERROR) << "SetCloseOnExec is not supported on Windows.";
218 #else
219   // This dance is more portable than Linux's O_CLOEXEC open(2) flag.
220   int flags = fcntl(fd, F_GETFD);
221   if (flags == -1) {
222     PLOG(WARNING) << "fcntl(" << fd << ", F_GETFD) failed";
223     return;
224   }
225   int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
226   if (rc == -1) {
227     PLOG(WARNING) << "fcntl(" << fd << ", F_SETFD, " << flags << ") failed";
228     return;
229   }
230 #endif
231 }
232 
Open(const char * filename,std::string * error_msg)233 ZipArchive* ZipArchive::Open(const char* filename, std::string* error_msg) {
234   DCHECK(filename != nullptr);
235 
236   ZipArchiveHandle handle;
237   const int32_t error = OpenArchive(filename, &handle);
238   if (error != 0) {
239     *error_msg = std::string(ErrorCodeString(error));
240     CloseArchive(handle);
241     return nullptr;
242   }
243 
244   SetCloseOnExec(GetFileDescriptor(handle));
245   return new ZipArchive(handle);
246 }
247 
OpenFromFd(int fd,const char * filename,std::string * error_msg)248 ZipArchive* ZipArchive::OpenFromFd(int fd, const char* filename, std::string* error_msg) {
249   DCHECK(filename != nullptr);
250   DCHECK_GT(fd, 0);
251 
252   ZipArchiveHandle handle;
253   const int32_t error = OpenArchiveFd(fd, filename, &handle);
254   if (error != 0) {
255     *error_msg = std::string(ErrorCodeString(error));
256     CloseArchive(handle);
257     return nullptr;
258   }
259 
260   SetCloseOnExec(GetFileDescriptor(handle));
261   return new ZipArchive(handle);
262 }
263 
Find(const char * name,std::string * error_msg) const264 ZipEntry* ZipArchive::Find(const char* name, std::string* error_msg) const {
265   DCHECK(name != nullptr);
266 
267   // Resist the urge to delete the space. <: is a bigraph sequence.
268   std::unique_ptr< ::ZipEntry> zip_entry(new ::ZipEntry);
269   const int32_t error = FindEntry(handle_, name, zip_entry.get());
270   if (error != 0) {
271     *error_msg = std::string(ErrorCodeString(error));
272     return nullptr;
273   }
274 
275   return new ZipEntry(handle_, zip_entry.release(), name);
276 }
277 
~ZipArchive()278 ZipArchive::~ZipArchive() {
279   CloseArchive(handle_);
280 }
281 
282 }  // namespace art
283