1 /*
2  * Copyright (c) 2024 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 "playpattern_fuzzer.h"
17 
18 #include <cstddef>
19 #include <cstdint>
20 #include <cstring>
21 #include <string>
22 
23 #include "accesstoken_kit.h"
24 #include "nativetoken_kit.h"
25 #include "securec.h"
26 #include "token_setproc.h"
27 
28 #include "vibrator_agent.h"
29 
30 namespace OHOS {
31 using namespace Security::AccessToken;
32 using Security::AccessToken::AccessTokenID;
33 
34 template<class T>
GetObject(const uint8_t * data,size_t size,T & object)35 size_t GetObject(const uint8_t *data, size_t size, T &object)
36 {
37     size_t objectSize = sizeof(object);
38     if (objectSize > size) {
39         return 0;
40     }
41     errno_t ret = memcpy_s(&object, objectSize, data, objectSize);
42     if (ret != EOK) {
43         return 0;
44     }
45     return objectSize;
46 }
47 
SetUpTestCase()48 void SetUpTestCase()
49 {
50     const char **perms = new (std::nothrow) const char *[1];
51     if (perms == nullptr) {
52         return;
53     }
54     perms[0] = "ohos.permission.VIBRATE";
55     TokenInfoParams infoInstance = {
56         .dcapsNum = 0,
57         .permsNum = 1,
58         .aclsNum = 0,
59         .dcaps = nullptr,
60         .perms = perms,
61         .acls = nullptr,
62         .processName = "PlayPatternFuzzTest",
63         .aplStr = "system_core",
64     };
65     uint64_t tokenId = GetAccessTokenId(&infoInstance);
66     SetSelfTokenID(tokenId);
67     AccessTokenKit::ReloadNativeTokenInfo();
68     delete[] perms;
69 }
70 
PlayPatternFuzzTest(const uint8_t * data,size_t size)71 bool PlayPatternFuzzTest(const uint8_t *data, size_t size)
72 {
73     VibratorPattern vibratorPattern { 0 };
74     size_t startPos = 0;
75     startPos += GetObject<int32_t>(data + startPos, size - startPos, vibratorPattern.time);
76     startPos += GetObject<int32_t>(data + startPos, size - startPos, vibratorPattern.eventNum);
77     GetObject<int32_t>(data + startPos, size - startPos, vibratorPattern.patternDuration);
78     int32_t ret = OHOS::Sensors::PlayPattern(vibratorPattern);
79     return ret == 0;
80 }
81 } // namespace OHOS
82 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)83 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
84 {
85     OHOS::PlayPatternFuzzTest(data, size);
86     return 0;
87 }