1 /*
2  * Copyright (C) 2021 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 #ifndef HAP_RANDOM_ACCESS_FILE_H
16 #define HAP_RANDOM_ACCESS_FILE_H
17 
18 #include "common/export_define.h"
19 #include "common/hap_byte_buffer.h"
20 #include "util/digest_parameter.h"
21 
22 namespace OHOS {
23 namespace Security {
24 namespace Verify {
25 struct MmapInfo {
26     long long mmapPosition;
27     int32_t readMoreLen = 0;
28     int32_t mmapSize = 0;
29     char* mapAddr;
30 };
31 
32 class RandomAccessFile {
33 public:
34     DLL_EXPORT RandomAccessFile();
35     DLL_EXPORT ~RandomAccessFile();
36     DLL_EXPORT bool Init(const std::string& filePath, bool readFile = false);
37     DLL_EXPORT bool InitWithFd(const int32_t fileFd);
38     DLL_EXPORT long long GetLength() const;
39     DLL_EXPORT long long ReadFileFullyFromOffset(HapByteBuffer& buffer, long long offset);
40     DLL_EXPORT long long ReadFileFullyFromOffset(char buf[], long long offset, int32_t bufCapacity);
41     bool ReadFileFromOffsetAndDigestUpdate(const DigestParameter& digestParam, int32_t chunkSize, long long offset);
42 
43 private:
44     long long DoMMap(int32_t bufCapacity, long long offset, MmapInfo& mmapInfo);
45     bool CheckLittleEndian();
46     long long ReadFileFullyFromOffsetV2(char buf[], long long offset, int32_t bufCapacity);
47     long long ReadFileFullyFromOffsetV2(HapByteBuffer& buffer, long long offset);
48     bool ReadFileFromOffsetAndDigestUpdateV2(const DigestParameter& digestParam, int32_t chunkSize, long long offset);
49     static const int32_t FILE_OPEN_FAIL_ERROR_NUM;
50     static int32_t memoryPageSize;
51     int32_t fd = 0;
52     long long fileLength;
53     bool readFile_ = false;
54 };
55 } // namespace Verify
56 } // namespace Security
57 } // namespace OHOS
58 #endif // HAP_RANDOM_ACCESS_FILE_H
59