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