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 "utils.h"
17#include <fstream>
18#include <iomanip>
19#include "utils/logger.h"
20
21namespace panda::verifier {
22
23void GenerateModifiedAbc(const std::vector<unsigned char> &buffer, const std::string &filename)
24{
25    std::ofstream abc_file(filename, std::ios::out | std::ios::binary);
26    if (abc_file.fail()) {
27        LOG(ERROR, VERIFIER) << "Failed to open file " << filename;
28        return;
29    }
30
31    abc_file.write(reinterpret_cast<const char *>(buffer.data()), buffer.size());
32    abc_file.close();
33}
34
35void ConvertToLittleEndian(std::vector<unsigned char> &inner_id, const uint32_t &id)
36{
37    std::vector<unsigned char> bytes;
38    for (int i = 0; i < sizeof(uint32_t); ++i) {
39        unsigned char byte = static_cast<unsigned char>((id >> (i * 8)) & 0xff);
40        inner_id.push_back(byte);
41    }
42}
43
44void ModifyBuffer(std::unordered_map<uint32_t, uint32_t> &literal_map, std::vector<unsigned char> &buffer)
45{
46    for (const auto &literal : literal_map) {
47        size_t literal_id = literal.first;
48        std::vector<unsigned char> inner_id;
49        ConvertToLittleEndian(inner_id, literal.second);
50        for (size_t i = literal_id; i < buffer.size(); ++i) {
51            if (buffer[i] == inner_id[0] && buffer[i+1] == inner_id[1]) {
52                // The purpose of this modification is to break abc
53                // The abc is tampered with by setting buffer[i + 1] to buffer[i] and buffer[i + 2] to buffer[i + 1]
54                buffer[i] = buffer[i + 1];
55                buffer[i + 1] = buffer[i + 2];
56                break;
57            }
58        }
59    }
60}
61
62} // namespace panda::verifier