• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "zip_file_reader.h"
17 
18 #include <sys/stat.h>
19 
20 #include "ecmascript/platform/file.h"
21 #include "zip_file_reader_io.h"
22 #include "zip_file_reader_mem.h"
23 
24 namespace panda {
25 namespace ecmascript {
26 constexpr size_t MEM_MAX_FILE_SIZE = 1u;
27 
CreateZipFileReader(const std::string & filePath)28 std::shared_ptr<ZipFileReader> ZipFileReader::CreateZipFileReader(const std::string &filePath)
29 {
30     size_t fileSize = GetFileLen(filePath);
31     if (fileSize == 0) {
32         return nullptr;
33     }
34 
35     std::shared_ptr<ZipFileReader> result;
36     if (fileSize <= MEM_MAX_FILE_SIZE) {
37         result = std::make_shared<ZipFileReaderMem>(filePath);
38     } else {
39         result = std::make_shared<ZipFileReaderIo>(filePath);
40     }
41 
42     result->fileLen_ = fileSize;
43     if (result->init()) {
44         return result;
45     }
46     return nullptr;
47 }
48 
~ZipFileReader()49 ZipFileReader::~ZipFileReader()
50 {
51     if (fd_ >= 0 && closable_) {
52         Close(reinterpret_cast<fd_t>(fd_));
53         fd_ = -1;
54     }
55 }
56 
GetFileLen(const std::string & filePath)57 size_t ZipFileReader::GetFileLen(const std::string &filePath)
58 {
59     if (filePath.empty()) {
60         return 0;
61     }
62 
63     struct stat fileStat{};
64     if (stat(filePath.c_str(), &fileStat) == 0) {
65         return fileStat.st_size;
66     }
67 
68     return 0;
69 }
70 
init()71 bool ZipFileReader::init()
72 {
73     if (filePath_.empty()) {
74         return false;
75     }
76     fd_ = open(filePath_.c_str(), O_RDONLY);
77     if (fd_ < 0) {
78         return false;
79     }
80     FdsanExchangeOwnerTag(reinterpret_cast<fd_t>(fd_));
81     return true;
82 }
83 }
84 }