1 /*
2  * Copyright (C) 2011 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 <sys/stat.h>
21 #include <sys/types.h>
22 #include <zlib.h>
23 #include <memory>
24 
25 #include "base/common_art_test.h"
26 #include "file_utils.h"
27 #include "os.h"
28 #include "unix_file/fd_file.h"
29 
30 namespace art {
31 
32 class ZipArchiveTest : public CommonArtTest {};
33 
TEST_F(ZipArchiveTest,FindAndExtract)34 TEST_F(ZipArchiveTest, FindAndExtract) {
35   std::string error_msg;
36   std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(GetLibCoreDexFileNames()[0].c_str(), &error_msg));
37   ASSERT_TRUE(zip_archive.get() != nullptr) << error_msg;
38   ASSERT_TRUE(error_msg.empty());
39   std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find("classes.dex", &error_msg));
40   ASSERT_TRUE(zip_entry.get() != nullptr);
41   ASSERT_TRUE(error_msg.empty());
42 
43   ScratchFile tmp;
44   ASSERT_NE(-1, tmp.GetFd());
45   std::unique_ptr<File> file(new File(DupCloexec(tmp.GetFd()), tmp.GetFilename(), false));
46   ASSERT_TRUE(file.get() != nullptr);
47   bool success = zip_entry->ExtractToFile(*file, &error_msg);
48   ASSERT_TRUE(success) << error_msg;
49   ASSERT_TRUE(error_msg.empty());
50   file.reset(nullptr);
51 
52   uint32_t computed_crc = crc32(0L, Z_NULL, 0);
53   int fd = open(tmp.GetFilename().c_str(), O_RDONLY | O_CLOEXEC);
54   ASSERT_NE(-1, fd);
55   const size_t kBufSize = 32768;
56   uint8_t buf[kBufSize];
57   while (true) {
58     ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buf, kBufSize));
59     if (bytes_read == 0) {
60       break;
61     }
62     computed_crc = crc32(computed_crc, buf, bytes_read);
63   }
64   EXPECT_EQ(zip_entry->GetCrc32(), computed_crc);
65 }
66 
67 }  // namespace art
68