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 "cfcreate_fuzzer.h"
17 
18 #include <securec.h>
19 
20 #include "cf_api.h"
21 #include "cf_memory.h"
22 #include "cf_result.h"
23 
24 namespace OHOS {
CfCreateFuzzTest(const uint8_t * data,size_t size)25     bool CfCreateFuzzTest(const uint8_t* data, size_t size)
26     {
27         if (size < sizeof(CfObjectType) + sizeof(CfEncodingBlob)) {
28             return false;
29         }
30         uint8_t *tmpData = const_cast<uint8_t *>(data);
31         size_t usedSize = 0;
32         CfObjectType objType = *(reinterpret_cast<CfObjectType *>(tmpData));
33         usedSize += sizeof(CfObjectType);
34 
35         CfEncodingBlob inStream = { 0 };
36         inStream.encodingFormat = *(reinterpret_cast<enum CfEncodingFormat *>(tmpData + usedSize));
37         usedSize += sizeof(enum CfEncodingFormat);
38         inStream.len = *(reinterpret_cast<size_t *>(tmpData + usedSize));
39         usedSize += sizeof(size_t);
40         if (inStream.len > size - usedSize) {
41             return false;
42         }
43         inStream.data = static_cast<uint8_t *>(CfMalloc(inStream.len, 0));
44         if (inStream.data == nullptr) {
45             return false;
46         }
47         (void)memcpy_s(inStream.data, inStream.len, tmpData + usedSize, inStream.len);
48 
49         CfObject *object = nullptr;
50         (void)CfCreate(objType, &inStream, &object);
51         CfFree(inStream.data);
52         if (object != nullptr) {
53             object->destroy(&object);
54         }
55 
56         return true;
57     }
58 }
59 
60 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)61 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
62 {
63     /* Run your code on data */
64     OHOS::CfCreateFuzzTest(data, size);
65     return 0;
66 }
67