1 /*
2  * Copyright (c) 2024 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 #ifndef CODE_SIGN_JIT_CODE_SIGNER_H
17 #define CODE_SIGN_JIT_CODE_SIGNER_H
18 
19 #include <queue>
20 #include <vector>
21 #include "pac_sign_ctx.h"
22 
23 namespace OHOS {
24 namespace Security {
25 namespace CodeSign {
26 using Instr = uint32_t;
27 using Byte = uint8_t;
28 
29 constexpr int32_t INSTRUCTION_SIZE = 4;
30 constexpr int32_t LOG_2_INSTRUCTION_SIZE = 2;
31 
GetIndexFromOffset(int offset)32 static inline int GetIndexFromOffset(int offset)
33 {
34     return static_cast<int>(static_cast<uint32_t>(offset) >> LOG_2_INSTRUCTION_SIZE);
35 }
36 
37 class JitCodeSignerBase {
38 public:
JitCodeSignerBase()39     JitCodeSignerBase() : tmpBuffer_(nullptr), offset_(0) {};
~JitCodeSignerBase()40     virtual ~JitCodeSignerBase() {}
41     virtual void Reset() = 0;
42     virtual void SignInstruction(Instr insn) = 0;
43     virtual void SkipNext(uint32_t n) = 0;
44     virtual int32_t PatchInstruction(int offset, Instr insn) = 0;
45     virtual int32_t ValidateCodeCopy(Instr *jitMemory, Byte *jitBuffer, int size) = 0;
46 
47     void RegisterTmpBuffer(Byte *tmpBuffer);
48     int32_t SignData(const Byte *data, uint32_t size);
49     int32_t PatchInstruction(Byte *jitBuffer, Instr insn);
50     int32_t PatchData(int offset, const Byte *const data, uint32_t size);
51     int32_t PatchData(Byte *buffer, const Byte *const data, uint32_t size);
52 
53 protected:
54     bool ConvertPatchOffsetToIndex(const int offset, int &curIndex);
55     int32_t CheckDataCopy(Instr *jitMemory, Byte *jitBuffer, int size);
56 
57 protected:
58     Byte *tmpBuffer_;
59     int offset_;
60     std::queue<Byte> willSign_;
61     std::vector<uint32_t> signTable_;
62     PACSignCtx ctx_;
63 };
64 }
65 }
66 }
67 #endif