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_mem.h"
17 
18 #include <cstdlib>
19 #include "ability_base_log_wrapper.h"
20 #include "securec.h"
21 
22 
23 namespace OHOS {
24 namespace AbilityBase {
init()25 bool ZipFileReaderMem::init()
26 {
27     if (!ZipFileReader::init()) {
28         ABILITYBASE_LOGE("init error: %{public}s", filePath_.c_str());
29         return false;
30     }
31     posix_fadvise(fd_, 0, 0, POSIX_FADV_SEQUENTIAL);
32 
33     fileContent_.resize(fileLen_);
34     auto pos = std::string::size_type{};
35     while (true) {
36         auto const readCount = read(fd_, fileContent_.data() + pos, fileContent_.size() - pos);
37         if (readCount < 0) {
38             ABILITYBASE_LOGE("read file error: %{public}s-%{public}d", filePath_.c_str(), errno);
39             fileContent_.clear();
40             return false;
41         } else if (readCount == 0) {
42             break;
43         }
44 
45         pos += readCount;
46     }
47     return true;
48 }
49 
ReadBuffer(size_t startPos,size_t bufferSize)50 std::string ZipFileReaderMem::ReadBuffer(size_t startPos, size_t bufferSize)
51 {
52     if (startPos + bufferSize > fileContent_.length()) {
53         ABILITYBASE_LOGE("failed: %{public}s, startPos: %{public}zu, bufferSize: %{public}zu, fileLen: %{public}zu",
54             filePath_.c_str(), startPos, bufferSize, fileLen_);
55         return "";
56     }
57 
58     return fileContent_.substr(startPos, bufferSize);
59 }
60 
ReadBuffer(uint8_t * dst,size_t startPos,size_t bufferSize)61 bool ZipFileReaderMem::ReadBuffer(uint8_t *dst, size_t startPos, size_t bufferSize)
62 {
63     if (!dst || startPos + bufferSize > fileContent_.length()) {
64         ABILITYBASE_LOGE("failed: %{public}s, startPos: %{public}zu, bufferSize: %{public}zu, fileLen: %{public}zu",
65             filePath_.c_str(), startPos, bufferSize, fileLen_);
66         return false;
67     }
68 
69     if (memcpy_s(dst, bufferSize, fileContent_.data() + startPos, bufferSize) != EOK) {
70         return false;
71     }
72 
73     return true;
74 }
75 }
76 }