• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "medialibrary_mtp_coverage_fuzzer.h"
16 
17 #include <cstdint>
18 #include <string>
19 #include <fstream>
20 #include <vector>
21 #include <memory>
22 #include <fuzzer/FuzzedDataProvider.h>
23 
24 #include "ability_context_impl.h"
25 #include "system_ability_definition.h"
26 #include "iservice_registry.h"
27 #include "userfilemgr_uri.h"
28 #include "payload_data.h"
29 #include "close_session_data.h"
30 #include "media_log.h"
31 #include "media_mtp_utils.h"
32 #include "mtp_ptp_const.h"
33 #include "medialibrary_data_manager.h"
34 #include "medialibrary_unistore_manager.h"
35 #include "medialibrary_kvstore_manager.h"
36 #include "photo_album_column.h"
37 #include "header_data.h"
38 
39 #define private public
40 #include "mtp_data_utils.h"
41 #include "property.h"
42 #include "mtp_operation.h"
43 #include "mtp_medialibrary_manager.h"
44 #include "mtp_media_library.h"
45 #undef private
46 
47 namespace OHOS {
48 using namespace std;
49 using namespace Media;
50 
51 static const int32_t MAX_BYTE_VALUE = 256;
52 static const int32_t SEED_SIZE = 1024;
53 const int32_t NUM_BYTES = 1;
54 const uint32_t NORMAL_OFFSET = 10;
55 FuzzedDataProvider *provider = nullptr;
56 
57 // mtp_data_utils
58 static vector<uint16_t> MEDIA_PROP_FUZZY_CODE_VECTOR;
59 const uint16_t PROP_BASE = 0xDC00;
60 const uint16_t PROP_OFFSET = 100;
61 static string g_videoMP4Path = "/data/local/tmp/test_video_mp4.mp4";
62 
63 // mtp_operation
64 shared_ptr<MtpOperation> mtpOperation_ = nullptr;
65 static vector<uint16_t> GET_PAYLOAD_OPERATION_CODE_VECTOR;
66 
67 // mtp_medialibrary_manager
68 constexpr int FUZZ_STORAGE_MANAGER_MANAGER_ID = 5003;
69 static shared_ptr<MtpMedialibraryManager> mtpMediaManagerLib_ = MtpMedialibraryManager::GetInstance();
70 shared_ptr<Media::MediaLibraryRdbStore> rdbStore_ = nullptr;
71 static int64_t g_fileId = 0;
72 static int64_t g_albumId = 0;
73 const uint32_t MTP_PROP_OFFSET = 255;
74 static string g_fuzzThumbnailPath = "/data/local/tmp/test_fuzzy_thumbnail.thumbnail";
75 
76 // mtp_medialibrary
77 static shared_ptr<MtpMediaLibrary> mtpMediaLib_ = MtpMediaLibrary::GetInstance();
78 static string g_fuzzCopyPath = "/data/local/tmp/test_fuzzy_copy.txt";
79 static string g_fuzzCopyName = "test_fuzzy_copy.txt";
80 static string g_dirPath = "/data/local/tmp";
81 const uint16_t GALLERY_PROP_OFFSET = 255;
82 
FuzzMtpOperationContext(const uint8_t * data,size_t size)83 static MtpOperationContext FuzzMtpOperationContext(const uint8_t* data, size_t size)
84 {
85     MtpOperationContext context;
86 
87     context.operationCode = provider->ConsumeIntegral<uint32_t>();
88     context.transactionID = provider->ConsumeIntegral<uint32_t>();
89     context.devicePropertyCode = provider->ConsumeIntegral<uint32_t>();
90     context.storageID = provider->ConsumeIntegral<uint32_t>();
91     context.format = provider->ConsumeIntegral<uint16_t>();
92     context.parent = provider->ConsumeIntegral<uint32_t>();
93     context.handle = provider->ConsumeIntegral<uint32_t>();
94     context.property = provider->ConsumeIntegral<uint32_t>();
95     context.groupCode = provider->ConsumeIntegral<uint32_t>();
96     context.depth = provider->ConsumeIntegral<uint32_t>();
97     context.properStrValue = provider->ConsumeBytesAsString(NUM_BYTES);
98     context.properIntValue = provider->ConsumeIntegral<int64_t>();
99     vector<uint32_t> handles = {provider->ConsumeIntegral<uint32_t>()};
100     context.handles = make_shared<UInt32List>(handles),
101     context.name = provider->ConsumeBytesAsString(NUM_BYTES);
102     context.created = provider->ConsumeBytesAsString(NUM_BYTES);
103     context.modified = provider->ConsumeBytesAsString(NUM_BYTES);
104 
105     context.indata = provider->ConsumeBool();
106     context.storageInfoID = provider->ConsumeIntegral<uint32_t>();
107 
108     context.sessionOpen = provider->ConsumeBool();
109     context.sessionID = provider->ConsumeIntegral<uint32_t>();
110     context.tempSessionID = provider->ConsumeIntegral<uint32_t>();
111     context.eventHandle = provider->ConsumeIntegral<uint32_t>();
112     context.eventProperty = provider->ConsumeIntegral<uint32_t>();
113     return context;
114 }
115 
116 // header_data
MtpHeaderDataTest(const uint8_t * data,size_t size)117 static void MtpHeaderDataTest(const uint8_t* data, size_t size)
118 {
119     shared_ptr<MtpOperationContext> context = make_shared<MtpOperationContext>(
120         FuzzMtpOperationContext(data, size));
121     if (context == nullptr) {
122         MEDIA_ERR_LOG("context is nullptr");
123         return;
124     }
125 
126     HeaderData headerData(context);
127     uint32_t bufferSize = provider->ConsumeIntegralInRange<uint32_t>(1, PACKET_HEADER_LENGETH * 2);
128     std::vector<uint8_t> buffer(bufferSize, provider->ConsumeIntegral<uint8_t>());
129     headerData.Parser(buffer, bufferSize);
130 }
131 
132 // mtp_data_utils
MtpDataUtilsTest(const uint8_t * data,size_t size)133 static void MtpDataUtilsTest(const uint8_t* data, size_t size)
134 {
135     shared_ptr<MtpOperationContext> context = make_shared<MtpOperationContext>(
136         FuzzMtpOperationContext(data, size));
137     if (context == nullptr) {
138         MEDIA_ERR_LOG("context is nullptr");
139         return;
140     }
141     shared_ptr<vector<Property>> outProps = make_shared<vector<Property>>();
142     std::string randomString = provider->ConsumeBytesAsString(NUM_BYTES);
143     context->property = provider->ConsumeIntegralInRange<uint32_t>(MTP_PROPERTY_ALL_CODE - 1, MTP_PROPERTY_ALL_CODE);
144     MtpDataUtils::GetGalleryPropList(context, outProps, randomString);
145 
146     MtpDataUtils::IsNumber(randomString);
147 
148     std::shared_ptr<UInt16List> properties = make_shared<UInt16List>(MEDIA_PROP_FUZZY_CODE_VECTOR);
149     properties->push_back(PROP_BASE + provider->ConsumeIntegralInRange<uint16_t>(0, PROP_OFFSET));
150     uint32_t parentId = 0;
151     std::unordered_map<uint32_t, std::string> umap{
152         {provider->ConsumeIntegral<uint32_t>(), randomString}
153     };
154     outProps->clear();
155     int32_t storageId = 0;
156     MtpDataUtils::GetMtpOneRowProp(properties, parentId, umap.begin(), outProps, storageId);
157 
158     PropertyValue outPropValue;
159     uint32_t property = MEDIA_PROP_FUZZY_CODE_VECTOR.at(
160         provider->ConsumeIntegralInRange<size_t>(0, MEDIA_PROP_FUZZY_CODE_VECTOR.size() - 1));
161     MtpDataUtils::GetPropValueForVideoOfMovingPhoto(g_videoMP4Path, property, outPropValue);
162 
163     shared_ptr<unordered_map<uint32_t, std::string>> handles = make_shared<unordered_map<uint32_t, std::string>>();
164     handles->insert({1, g_videoMP4Path});
165     handles->insert({2, g_dirPath});
166     std::unordered_map<std::string, uint32_t> pathHandles = {{g_dirPath, 1}};
167     outProps->clear();
168     context->property = provider->ConsumeBool() ? MTP_PROPERTY_ALL_CODE : MTP_PROPERTY_ALL_CODE - 1;
169     context->format = provider->ConsumeBool() ? 0 : 1;
170     MtpDataUtils::GetMtpPropList(handles, pathHandles, context, outProps);
171 }
172 
173 // mtp_operation
MtpOperationTest(const uint8_t * data,size_t size)174 static void MtpOperationTest(const uint8_t* data, size_t size)
175 {
176     if (mtpOperation_ == nullptr) {
177         return;
178     }
179 
180     shared_ptr<MtpOperationContext> context = make_shared<MtpOperationContext>(
181         FuzzMtpOperationContext(data, size));
182     if (context == nullptr) {
183         MEDIA_ERR_LOG("context is nullptr");
184         return;
185     }
186     shared_ptr<PayloadData> payloadData = nullptr;
187     uint16_t containerType = COMMAND_CONTAINER_TYPE;
188     int errorCode = 0;
189 
190     context->operationCode = GET_PAYLOAD_OPERATION_CODE_VECTOR.at(
191         provider->ConsumeIntegralInRange<size_t>(0, GET_PAYLOAD_OPERATION_CODE_VECTOR.size() - 1));
192     mtpOperation_->GetPayloadData(context, payloadData, containerType, errorCode);
193 
194     auto storage = make_shared<Storage>();
195     if (storage == nullptr) {
196         MEDIA_ERR_LOG("storage is nullptr");
197         return;
198     }
199     mtpOperation_->AddStorage(storage);
200     mtpOperation_->RemoveStorage(storage);
201 
202     mtpOperation_->mtpContextPtr_->sessionOpen = provider->ConsumeBool();
203     mtpOperation_->DealRequest(context->operationCode, errorCode);
204 }
205 
InitMtpMedialibraryManager()206 static void InitMtpMedialibraryManager()
207 {
208     shared_ptr<MtpOperationContext> context = make_shared<MtpOperationContext>();
209     auto saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
210     if (saManager == nullptr) {
211         MEDIA_INFO_LOG("Get system ability mgr failed.");
212         return;
213     }
214     auto remoteObj = saManager->GetSystemAbility(FUZZ_STORAGE_MANAGER_MANAGER_ID);
215     if (remoteObj == nullptr) {
216         MEDIA_INFO_LOG("GetSystemAbility Service Failed.");
217         return;
218     }
219     sptr<IRemoteObject> token = remoteObj;
220     mtpMediaManagerLib_->Init(token, context);
221 }
222 
223 // mtp_medialibrary_manager
MtpMedialibraryManagerTest(const uint8_t * data,size_t size)224 static void MtpMedialibraryManagerTest(const uint8_t* data, size_t size)
225 {
226     shared_ptr<MtpOperationContext> context = make_shared<MtpOperationContext>(
227         FuzzMtpOperationContext(data, size));
228     if (context == nullptr) {
229         MEDIA_ERR_LOG("context is nullptr");
230         return;
231     }
232 
233     uint32_t start = g_fileId > NORMAL_OFFSET ? g_fileId - NORMAL_OFFSET : 0;
234     uint32_t handle = provider->ConsumeIntegralInRange<uint32_t>(start, g_fileId);
235     PathMap paths;
236     mtpMediaManagerLib_->GetCopyObjectPath(handle, paths);
237     mtpMediaManagerLib_->GetCopyObjectPath(COMMON_PHOTOS_OFFSET + handle, paths);
238     mtpMediaManagerLib_->GetPhotosInfoForMove(context);
239 
240     bool isHandle = provider->ConsumeBool();
241     context->handle = handle;
242     mtpMediaManagerLib_->GetAlbumInfo(context, isHandle);
243     mtpMediaManagerLib_->GetPhotosInfo(context, isHandle);
244 
245     mtpMediaManagerLib_->GetAlbumCloud();
246     uint32_t uid = provider->ConsumeIntegralInRange<uint32_t>(g_albumId, g_albumId + NORMAL_OFFSET);
247     vector<string> ownerAlbumIds = {to_string(uid)};
248     mtpMediaManagerLib_->GetAlbumCloudDisplay(ownerAlbumIds);
249 
250     std::shared_ptr<UInt32List> out = make_shared<UInt32List>();
251     mtpMediaManagerLib_->GetAllHandles(context, out);
252 
253     shared_ptr<ObjectInfo> outObjectInfo = make_shared<ObjectInfo>(0);
254     mtpMediaManagerLib_->GetObjectInfo(context, outObjectInfo);
255 
256     shared_ptr<UInt8List> thumb = make_shared<UInt8List>();
257     mtpMediaManagerLib_->GetThumbnailFromPath(g_fuzzThumbnailPath, thumb);
258 
259     int32_t id = provider->ConsumeIntegral<int32_t>();
260     std::string randomString = provider->ConsumeBytesAsString(NUM_BYTES);
261     std::string thumbSizeValue = randomString + ":" + randomString;
262     std::string dataPath = randomString + "/" + randomString + "." + randomString;
263     std::string uri = mtpMediaManagerLib_->GetThumbUri(id, thumbSizeValue, dataPath);
264 
265     context->parent = handle;
266     context->property = provider->ConsumeIntegralInRange<uint16_t>(MTP_PROPERTY_OBJECT_FORMAT_CODE,
267         MTP_PROPERTY_OBJECT_FORMAT_CODE + MTP_PROP_OFFSET);
268     uint64_t outIntVal;
269     uint128_t outLongVal;
270     string outStrVal;
271     mtpMediaManagerLib_->GetObjectPropValue(context, outIntVal, outLongVal, outStrVal);
272 
273     mtpMediaManagerLib_->Clear();
274 }
275 
276 // mtp_medialibrary
MtpMedialibraryTest(const uint8_t * data,size_t size)277 static void MtpMedialibraryTest(const uint8_t* data, size_t size)
278 {
279     shared_ptr<MtpOperationContext> context = make_shared<MtpOperationContext>(FuzzMtpOperationContext(data, size));
280     if (context == nullptr) {
281         MEDIA_ERR_LOG("context is nullptr");
282         return;
283     }
284 
285     context->handle = provider->ConsumeIntegralInRange<uint32_t>(PTP_IN_MTP_ID, PTP_IN_MTP_ID + 1);
286     std::shared_ptr<ObjectInfo> outObjectInfo = std::make_shared<ObjectInfo>(provider->ConsumeIntegral<uint32_t>());
287     std::string randomString = provider->ConsumeBytesAsString(NUM_BYTES);
288     mtpMediaLib_->GetGalleryObjectInfo(context, outObjectInfo, randomString);
289 
290     context->property = PROP_BASE + provider->ConsumeIntegralInRange<uint16_t>(1, GALLERY_PROP_OFFSET);
291     uint64_t outIntVal{0};
292     uint128_t outLongVal{0};
293     std::string outStrVal;
294     mtpMediaLib_->GetGalleryPropValue(context, outIntVal, outLongVal, outStrVal, randomString);
295 
296     context->parent =  mtpMediaLib_->AddPathToMap(g_dirPath);
297     PathMap paths = {{g_fuzzCopyPath, g_fuzzCopyName}};
298     uint32_t outObjectHandle = 0;
299     mtpMediaLib_->CopyGalleryAlbum(context, randomString, paths, outObjectHandle);
300     paths = {{g_fuzzCopyPath, randomString}};
301     mtpMediaLib_->CopyGalleryPhoto(context, paths, outObjectHandle);
302 
303     mtpMediaLib_->ErasePathInfo(context->parent, g_dirPath);
304 
305     bool realPath = provider->ConsumeBool();
306     std::string path = realPath ? g_dirPath : randomString;
307     std::shared_ptr<UInt32List> out = std::make_shared<UInt32List>();
308     mtpMediaLib_->ScanDirNoDepth(path, out);
309     std::shared_ptr<std::unordered_map<uint32_t, std::string>> outMap =
310         std::make_shared<std::unordered_map<uint32_t, std::string>>();
311     mtpMediaLib_->ScanDirWithType(path, outMap);
312     mtpMediaLib_->ScanDirTraverseWithType(g_dirPath, outMap);
313 }
314 
FuzzPhotoThumbStatus()315 static inline int32_t FuzzPhotoThumbStatus()
316 {
317     int32_t start = static_cast<int32_t>(Media::PhotoThumbStatus::DOWNLOADED);
318     int32_t end = static_cast<int32_t>(Media::PhotoThumbStatus::NOT_DOWNLOADED);
319     return provider->ConsumeIntegralInRange<int32_t>(start, end);
320 }
321 
FuzzPhotoPosition()322 static inline int32_t FuzzPhotoPosition()
323 {
324     int32_t start = static_cast<int32_t>(Media::PhotoPosition::LOCAL);
325     int32_t end = static_cast<int32_t>(Media::PhotoPosition::LOCAL_AND_CLOUD);
326     return provider->ConsumeIntegralInRange<int32_t>(start, end);
327 }
328 
FuzzDirtyType()329 static inline int32_t FuzzDirtyType()
330 {
331     int32_t start = static_cast<int32_t>(Media::DirtyType::TYPE_SYNCED);
332     int32_t end = static_cast<int32_t>(Media::DirtyType::TYPE_COPY);
333     return provider->ConsumeIntegralInRange<int32_t>(start, end);
334 }
335 
DatabaseDataInitial()336 static void DatabaseDataInitial()
337 {
338     if (rdbStore_ == nullptr) {
339         return ;
340     }
341 
342     NativeRdb::ValuesBucket albumValues;
343     albumValues.PutInt(PhotoAlbumColumns::ALBUM_SUBTYPE, provider->ConsumeIntegral<int32_t>());
344     albumValues.PutInt(PhotoAlbumColumns::ALBUM_COUNT, provider->ConsumeIntegral<int32_t>());
345     albumValues.PutInt(PhotoAlbumColumns::ALBUM_IMAGE_COUNT, provider->ConsumeIntegral<int32_t>());
346     albumValues.PutInt(PhotoAlbumColumns::ALBUM_VIDEO_COUNT, provider->ConsumeIntegral<int32_t>());
347     albumValues.PutString(PhotoAlbumColumns::ALBUM_CLOUD_ID, provider->ConsumeBytesAsString(NUM_BYTES));
348     uint32_t isLocal = 1;
349     isLocal += provider->ConsumeBool() ? 0 : 1;
350     albumValues.PutString(PhotoAlbumColumns::ALBUM_IS_LOCAL, to_string(isLocal));
351     albumValues.PutString(PhotoAlbumColumns::ALBUM_NAME, provider->ConsumeBytesAsString(NUM_BYTES));
352     albumValues.PutString(PhotoAlbumColumns::ALBUM_NAME, provider->ConsumeBytesAsString(NUM_BYTES));
353     albumValues.PutString(PhotoAlbumColumns::ALBUM_NAME, provider->ConsumeBytesAsString(NUM_BYTES));
354     g_albumId = 0;
355     rdbStore_->Insert(g_albumId, PhotoAlbumColumns::TABLE, albumValues);
356     MEDIA_INFO_LOG("albumId: %{public}lld.", g_albumId);
357 
358     NativeRdb::ValuesBucket photoValues;
359     photoValues.PutInt(PhotoColumn::PHOTO_POSITION, FuzzPhotoPosition());
360     photoValues.PutInt(PhotoColumn::PHOTO_DIRTY, FuzzDirtyType());
361     photoValues.PutInt(PhotoColumn::PHOTO_THUMB_STATUS, FuzzPhotoThumbStatus());
362     int64_t thumbnailReady = provider->ConsumeBool() ? 3 : 2;
363     photoValues.PutLong(PhotoColumn::PHOTO_THUMBNAIL_READY, thumbnailReady);
364     photoValues.PutString(MediaColumn::MEDIA_FILE_PATH, provider->ConsumeBytesAsString(NUM_BYTES));
365     photoValues.PutString(PhotoColumn::PHOTO_CLOUD_ID, provider->ConsumeBytesAsString(NUM_BYTES));
366     photoValues.PutString(PhotoColumn::PHOTO_BURST_COVER_LEVEL, "1");
367     photoValues.PutString(PhotoColumn::PHOTO_BURST_KEY, provider->ConsumeBytesAsString(NUM_BYTES));
368     int64_t trashed = provider->ConsumeBool() ? 0 : 1;
369     photoValues.PutInt(PhotoColumn::MEDIA_DATE_TRASHED, trashed);
370     photoValues.PutInt(PhotoColumn::PHOTO_OWNER_ALBUM_ID, g_albumId);
371     photoValues.PutString(PhotoColumn::MEDIA_TIME_PENDING, "0");
372     photoValues.PutString(PhotoColumn::MEDIA_HIDDEN, "0");
373     photoValues.PutString(PhotoColumn::PHOTO_IS_TEMP, to_string(false));
374     g_fileId = 0;
375     rdbStore_->Insert(g_fileId, PhotoColumn::PHOTOS_TABLE, photoValues);
376     MEDIA_INFO_LOG("fileId: %{public}lld.", g_fileId);
377 }
378 
DatabaseDataClear()379 static void DatabaseDataClear()
380 {
381     if (rdbStore_ == nullptr) {
382         return;
383     }
384 
385     std::string whereClause = PhotoAlbumColumns::ALBUM_ID + " = ? ";
386     std::vector<std::string> whereArgs = {to_string(g_albumId)};
387     int32_t deletedRows = -1;
388     int32_t ret = rdbStore_->Delete(deletedRows, PhotoAlbumColumns::TABLE, whereClause, whereArgs);
389     if (ret != E_OK) {
390         MEDIA_ERR_LOG("DeleteAlbumAsset by albumId %{public}lld Failed %{public}d", g_albumId, ret);
391     }
392 
393     whereClause = MediaColumn::MEDIA_ID + " = ? ";
394     whereArgs = {to_string(g_fileId)};
395     deletedRows = -1;
396     ret = rdbStore_->Delete(deletedRows, PhotoColumn::PHOTOS_TABLE, whereClause, whereArgs);
397     if (ret != E_OK) {
398         MEDIA_ERR_LOG("DeletePhotoAsset by fileId %{public}lld Failed %{public}d", g_fileId, ret);
399     }
400 }
401 
DatabaseTableInitial()402 static void DatabaseTableInitial()
403 {
404     if (rdbStore_ == nullptr) {
405         return ;
406     }
407 
408     vector<string> dropTableSqlList = {
409         "DROP TABLE IF EXISTS " + PhotoColumn::PHOTOS_TABLE + ";",
410         "DROP TABLE IF EXISTS " + PhotoAlbumColumns::TABLE + ";",
411     };
412     for (auto &dropTableSql : dropTableSqlList) {
413         int32_t ret = rdbStore_->ExecuteSql(dropTableSql);
414         if (ret != NativeRdb::E_OK) {
415             MEDIA_INFO_LOG("Execute sql %{public}s failed", dropTableSql.c_str());
416             return;
417         }
418         MEDIA_INFO_LOG("Execute sql %{public}s success", dropTableSql.c_str());
419     }
420 
421     vector<string> createTableSqlList = {
422         Media::PhotoColumn::CREATE_PHOTO_TABLE,
423         Media::PhotoAlbumColumns::CREATE_TABLE,
424     };
425     for (auto &createTableSql : createTableSqlList) {
426         int32_t ret = rdbStore_->ExecuteSql(createTableSql);
427         if (ret != NativeRdb::E_OK) {
428             MEDIA_INFO_LOG("Execute sql %{private}s failed", createTableSql.c_str());
429             return;
430         }
431         MEDIA_INFO_LOG("Execute sql %{private}s success", createTableSql.c_str());
432     }
433 }
434 
InitDB()435 static void InitDB()
436 {
437     auto stageContext = std::make_shared<AbilityRuntime::ContextImpl>();
438     auto abilityContextImpl = std::make_shared<AbilityRuntime::AbilityContextImpl>();
439     abilityContextImpl->SetStageContext(stageContext);
440     int32_t sceneCode = 0;
441     auto ret = Media::MediaLibraryDataManager::GetInstance()->InitMediaLibraryMgr(abilityContextImpl,
442         abilityContextImpl, sceneCode);
443     CHECK_AND_RETURN_LOG(ret == NativeRdb::E_OK, "InitMediaLibraryMgr failed, ret: %{public}d", ret);
444 
445     auto rdbStore = Media::MediaLibraryUnistoreManager::GetInstance().GetRdbStore();
446     if (rdbStore == nullptr) {
447         MEDIA_ERR_LOG("rdbStore is nullptr");
448         return;
449     }
450     rdbStore_ = rdbStore;
451     DatabaseTableInitial();
452 }
453 
AddSeed()454 static int32_t AddSeed()
455 {
456     char *seedData = new char[OHOS::SEED_SIZE];
457     for (int i = 0; i < OHOS::SEED_SIZE; i++) {
458         seedData[i] = static_cast<char>(i % MAX_BYTE_VALUE);
459     }
460 
461     std::string filename = "corpus/seed.txt";
462     std::ofstream file(filename.c_str(), std::ios::binary | std::ios::trunc);
463     if (!file) {
464         MEDIA_ERR_LOG("Cannot open file filename:%{public}s", filename.c_str());
465         delete[] seedData;
466         return Media::E_ERR;
467     }
468     file.write(seedData, OHOS::SEED_SIZE);
469     file.close();
470     delete[] seedData;
471     MEDIA_INFO_LOG("seedData has been successfully written to file filename:%{public}s", filename.c_str());
472     return Media::E_OK;
473 }
474 
VectorInitial()475 static void VectorInitial()
476 {
477     OHOS::MEDIA_PROP_FUZZY_CODE_VECTOR = {
478         MTP_PROPERTY_OBJECT_SIZE_CODE,
479         MTP_PROPERTY_OBJECT_FILE_NAME_CODE,
480         MTP_PROPERTY_DATE_MODIFIED_CODE,
481         MTP_PROPERTY_DATE_ADDED_CODE,
482         MTP_PROPERTY_STORAGE_ID_CODE
483     };
484     OHOS::GET_PAYLOAD_OPERATION_CODE_VECTOR = {
485         MTP_OPERATION_GET_DEVICE_INFO_CODE,
486         MTP_OPERATION_OPEN_SESSION_CODE,
487         MTP_OPERATION_SET_DEVICE_PROP_VALUE_CODE,
488         MTP_OPERATION_RESET_DEVICE_CODE,
489         MTP_OPERATION_CLOSE_SESSION_CODE,
490         MTP_OPERATION_GET_STORAGE_IDS_CODE,
491         MTP_OPERATION_GET_STORAGE_INFO_CODE,
492         MTP_OPERATION_GET_OBJECT_PROPS_SUPPORTED_CODE,
493         MTP_OPERATION_GET_OBJECT_HANDLES_CODE,
494         MTP_OPERATION_GET_NUM_OBJECTS_CODE,
495         MTP_OPERATION_GET_OBJECT_INFO_CODE,
496         MTP_OPERATION_GET_OBJECT_PROP_DESC_CODE,
497         MTP_OPERATION_GET_OBJECT_PROP_VALUE_CODE,
498         MTP_OPERATION_SET_OBJECT_PROP_VALUE_CODE,
499         MTP_OPERATION_GET_OBJECT_PROP_LIST_CODE,
500         MTP_OPERATION_GET_OBJECT_REFERENCES_CODE,
501         MTP_OPERATION_SET_OBJECT_REFERENCES_CODE,
502         MTP_OPERATION_DELETE_OBJECT_CODE,
503         MTP_OPERATION_MOVE_OBJECT_CODE,
504         MTP_OPERATION_COPY_OBJECT_CODE,
505         MTP_OPERATION_GET_DEVICE_PROP_DESC_CODE,
506         MTP_OPERATION_GET_DEVICE_PROP_VALUE_CODE,
507         MTP_OPERATION_RESET_DEVICE_PROP_VALUE_CODE,
508         MTP_OPERATION_GET_OBJECT_CODE,
509         MTP_OPERATION_SEND_OBJECT_CODE,
510         MTP_OPERATION_GET_THUMB_CODE,
511         MTP_OPERATION_SEND_OBJECT_INFO_CODE,
512         MTP_OPERATION_GET_PARTIAL_OBJECT_CODE,
513         MTP_OPERATION_SKIP_CODE
514     };
515 }
516 
ClearKvStore()517 static inline void ClearKvStore()
518 {
519     Media::MediaLibraryKvStoreManager::GetInstance().CloseAllKvStore();
520 }
521 } // namespace OHOS
522 
LLVMFuzzerInitialize(int * argc,char *** argv)523 extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv)
524 {
525     OHOS::VectorInitial();
526     OHOS::mtpOperation_ = std::make_shared<OHOS::MtpOperation>();
527     if (OHOS::mtpOperation_ == nullptr) {
528         return 0;
529     }
530     OHOS::mtpOperation_->Init();
531 
532     OHOS::AddSeed();
533     OHOS::InitDB();
534 
535     char buff[2] = "1";
536     int fd1 = open(OHOS::g_videoMP4Path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
537     write(fd1, buff, 1);
538     close(fd1);
539     int fd2 = open(OHOS::g_fuzzThumbnailPath.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
540     write(fd2, buff, 1);
541     close(fd2);
542     int fd3 = open(OHOS::g_fuzzCopyPath.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
543     write(fd3, buff, 1);
544     close(fd3);
545     return 0;
546 }
547 
548 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)549 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
550 {
551     /* Run your code on data */
552     if (data == nullptr) {
553         return 0;
554     }
555 
556     FuzzedDataProvider fdp(data, size);
557     OHOS::provider = &fdp;
558 
559     OHOS::MtpHeaderDataTest(data, size);
560     OHOS::DatabaseDataInitial();
561     OHOS::MtpDataUtilsTest(data, size);
562     OHOS::MtpOperationTest(data, size);
563     OHOS::InitMtpMedialibraryManager();
564     OHOS::MtpMedialibraryManagerTest(data, size);
565     OHOS::DatabaseDataClear();
566     OHOS::MtpMedialibraryTest(data, size);
567     OHOS::ClearKvStore();
568 
569     return 0;
570 }