1 /*
2 * Copyright (c) 2022 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 "surfaceutils_fuzzer.h"
17
18 #include <securec.h>
19
20 #include "surface.h"
21 #include "surface_utils.h"
22
23 namespace OHOS {
24 namespace {
25 const uint8_t* data_ = nullptr;
26 size_t size_ = 0;
27 size_t pos;
28 }
29
30 /*
31 * describe: get data from outside untrusted data(data_) which size is according to sizeof(T)
32 * tips: only support basic type
33 */
34 template<class T>
GetData()35 T GetData()
36 {
37 T object {};
38 size_t objectSize = sizeof(object);
39 if (data_ == nullptr || objectSize > size_ - pos) {
40 return object;
41 }
42 errno_t ret = memcpy_s(&object, objectSize, data_ + pos, objectSize);
43 if (ret != EOK) {
44 return {};
45 }
46 pos += objectSize;
47 return object;
48 }
49
DoSomethingInterestingWithMyAPI(const uint8_t * data,size_t size)50 bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size)
51 {
52 if (data == nullptr) {
53 return false;
54 }
55
56 // initialize
57 data_ = data;
58 size_ = size;
59 pos = 0;
60
61 // get data
62 uint64_t uniqueId1 = GetData<uint64_t>();
63 uint64_t uniqueId2 = GetData<uint64_t>();
64 uint64_t uniqueId3 = GetData<uint64_t>();
65
66 // test
67 sptr<OHOS::Surface> cSurface = OHOS::Surface::CreateSurfaceAsConsumer();
68 sptr<OHOS::IBufferProducer> producer = cSurface->GetProducer();
69 sptr<OHOS::Surface> pSurface = Surface::CreateSurfaceAsProducer(producer);
70 SurfaceUtils* utils = SurfaceUtils::GetInstance();
71 sptr<OHOS::Surface> surface = utils->GetSurface(uniqueId1);
72 utils->Add(uniqueId1, surface);
73 utils->Add(uniqueId2, pSurface);
74 utils->Remove(uniqueId3);
75
76 return true;
77 }
78 } // namespace OHOS
79
80 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)81 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
82 {
83 /* Run your code on data */
84 OHOS::DoSomethingInterestingWithMyAPI(data, size);
85 return 0;
86 }
87
88