1 /*
2 * Copyright (c) 2025 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 #include "unsubscribecommonevent_fuzzer.h"
16
17 #include "common_event_data.h"
18 #include "common_event_listener.h"
19 #include "common_event_manager_service.h"
20 #include "common_event_subscriber.h"
21 #include "refbase.h"
22 #include "fuzz_common_base.h"
23
24 #include <fuzzer/FuzzedDataProvider.h>
25 #include <string>
26 #include <vector>
27
28 using namespace OHOS::EventFwk;
29 namespace OHOS {
30 class SubscriberTest : public CommonEventSubscriber {
31 public:
SubscriberTest(const CommonEventSubscribeInfo & sp)32 explicit SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
33 {}
34
~SubscriberTest()35 ~SubscriberTest()
36 {}
37
OnReceiveEvent(const CommonEventData & data)38 virtual void OnReceiveEvent(const CommonEventData &data)
39 {}
40 };
41
DoSomethingInterestingWithMyAPI(FuzzedDataProvider * fdp)42 bool DoSomethingInterestingWithMyAPI(FuzzedDataProvider *fdp)
43 {
44 bool enabled = fdp->ConsumeBool();
45 sptr<CommonEventManagerService> service = CommonEventManagerService::GetInstance();
46 service->Init();
47
48 MatchingSkills matchingSkills;
49 matchingSkills.AddEvent(fdp->ConsumeRandomLengthString());
50 CommonEventSubscribeInfo subscribeInfo(matchingSkills);
51 int32_t userId = fdp->ConsumeIntegralInRange<int32_t>(-3, 1000);
52 if (fdp->ConsumeBool()) {
53 subscribeInfo.SetUserId(userId);
54 }
55 subscribeInfo.SetPriority(fdp->ConsumeIntegral<int32_t>());
56 std::shared_ptr<CommonEventSubscriber> subscriber = std::make_shared<SubscriberTest>(subscribeInfo);
57 int32_t funcResult = -1;
58 sptr<IRemoteObject> commonEventListener = new (std::nothrow) CommonEventListener(subscriber);
59 service->SubscribeCommonEvent(subscribeInfo, commonEventListener, fdp->ConsumeIntegral<int32_t>(), funcResult);
60
61 service->UnsubscribeCommonEvent(commonEventListener, funcResult);
62 return true;
63 }
64 }
65
66 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)67 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
68 {
69 /* Run your code on data */
70 FuzzedDataProvider fdp(data, size);
71 std::vector<std::string> permissions;
72 MockRandomToken(&fdp, permissions);
73 OHOS::DoSomethingInterestingWithMyAPI(&fdp);
74 return 0;
75 }
76