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 "diff_patch/diff_patch_interface.h"
17
18 #include <array>
19 #include <cstddef>
20 #include <cstdint>
21 #include <iostream>
22 #include <string>
23 #include <vector>
24 #include <fstream>
25 #include <cstdio>
26 #include "log/log.h"
27
28 using namespace Updater;
29 namespace OHOS {
WriteDataToFile(const char * data,size_t size,const char * filePath)30 bool WriteDataToFile(const char* data, size_t size, const char* filePath)
31 {
32 std::ofstream ofs(filePath, std::ios::app | std::ios::binary);
33 if (!ofs.is_open()) {
34 LOG(ERROR) << "open " << filePath << " failed";
35 return false;
36 }
37 ofs.write(data, size);
38 ofs.close();
39 return true;
40 }
41
FuzzApplyPatch(const uint8_t * data,size_t size)42 void FuzzApplyPatch(const uint8_t* data, size_t size)
43 {
44 bool ret = true;
45 const int magicNumSize = 4;
46 const char* bspatchPath = "/data/applyPatchfuzzBspatch";
47 const char* imgpatchPath = "/data/applyPatchfuzzImgpatch";
48 const char* oldFilePath = "/data/applyPatchfuzzOldFile";
49 const char* newFilePath = "/data/applyPatchfuzzNewFile";
50 ret &= WriteDataToFile("BSDIFF40", magicNumSize, bspatchPath);
51 ret &= WriteDataToFile(reinterpret_cast<const char*>(data), size, bspatchPath);
52 ret &= WriteDataToFile("PKGDIFF0", magicNumSize, imgpatchPath);
53 ret &= WriteDataToFile(reinterpret_cast<const char*>(data), size, imgpatchPath);
54 ret &= WriteDataToFile(reinterpret_cast<const char*>(data), size, oldFilePath);
55 if (!ret) {
56 LOG(ERROR) << "create file failed";
57 return;
58 }
59 ApplyPatch(bspatchPath, oldFilePath, newFilePath);
60 ApplyPatch(imgpatchPath, oldFilePath, newFilePath);
61 if (remove(bspatchPath) != 0 || remove(imgpatchPath) != 0 || remove(oldFilePath)) {
62 LOG(WARNING) << "Failed to delete file";
63 }
64 }
65 }
66
67 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)68 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
69 {
70 /* Run your code on data */
71 OHOS::FuzzApplyPatch(data, size);
72 return 0;
73 }
74