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 "backupsa_fuzzer.h"
17 
18 #include <cstddef>
19 #include <cstdint>
20 #include <cstring>
21 
22 #include <climits>
23 #include "message_parcel.h"
24 #include "service_stub.h"
25 #include "service.h"
26 #include "securec.h"
27 #include "system_ability.h"
28 
29 #include "filemgmt_libhilog.h"
30 
31 using namespace OHOS::FileManagement::Backup;
32 
33 namespace OHOS {
34 constexpr size_t FOO_MAX_LEN = 1024;
35 constexpr size_t U32_AT_SIZE = 4;
36 constexpr uint8_t MAX_CALL_TRANSACTION = 24;
37 constexpr int32_t SERVICE_ID = 5203;
38 
GetU32Data(const char * ptr)39 uint32_t GetU32Data(const char* ptr)
40 {
41     // 将第0个数字左移24位,将第1个数字左移16位,将第2个数字左移8位,第3个数字不左移
42     return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | (ptr[3]);
43 }
44 
BackupSaFuzzTest(std::unique_ptr<char[]> data,size_t size)45 bool BackupSaFuzzTest(std::unique_ptr<char[]> data, size_t size)
46 {
47     sptr service = sptr(new Service(SERVICE_ID));
48     uint32_t code = GetU32Data(data.get());
49     if (code == 0) {
50         return true;
51     }
52     MessageParcel datas;
53     datas.WriteInterfaceToken(ServiceStub::GetDescriptor());
54     datas.WriteBuffer(data.get(), size);
55     datas.RewindRead(0);
56     MessageParcel reply;
57     MessageOption option;
58     service->OnRemoteRequest(code % MAX_CALL_TRANSACTION, datas, reply, option);
59     service = nullptr;
60     return true;
61 }
62 } // namespace OHOS
63 
64 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t dataSize)65 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t dataSize)
66 {
67     /* Run your code on data */
68     if (data == nullptr) {
69         return 0;
70     }
71 
72     /* Validate the length of size */
73     if (dataSize < OHOS::U32_AT_SIZE || dataSize > OHOS::FOO_MAX_LEN) {
74         return 0;
75     }
76 
77     auto str = std::make_unique<char[]>(dataSize + 1);
78     (void)memset_s(str.get(), dataSize + 1, 0x00, dataSize + 1);
79     if (memcpy_s(str.get(), dataSize, data, dataSize) != EOK) {
80         return 0;
81     }
82     OHOS::BackupSaFuzzTest(move(str), dataSize);
83     return 0;
84 }