From 986109c975c406c5858d71384f0941108572e7ec Mon Sep 17 00:00:00 2001 From: zwtmichael Date: Sat, 22 Oct 2022 11:47:33 +0800 Subject: [PATCH 1/2] fix review commitment Signed-off-by: zwtmichael --- .../distributeddb/common/src/auto_launch.cpp | 4 ++-- .../include/communicator_aggregator.h | 4 ++-- .../communicator/src/communicator.cpp | 6 +++--- .../src/communicator_aggregator.cpp | 8 ++++---- .../communicator/src/communicator_linker.cpp | 4 ++-- .../include/single_ver_kvdb_sync_interface.h | 2 -- .../storage/src/sync_able_kvdb.cpp | 2 +- .../distributeddb/syncer/src/ability_sync.cpp | 20 +++++++++---------- .../syncer/src/generic_syncer.cpp | 2 +- .../syncer/src/single_ver_data_sync.cpp | 2 +- .../syncer/src/single_ver_kv_syncer.cpp | 2 +- ...ingle_ver_relational_sync_task_context.cpp | 2 +- .../single_ver_relational_sync_task_context.h | 2 +- .../src/single_ver_sync_state_machine.cpp | 1 + .../src/single_ver_sync_task_context.cpp | 9 +++------ .../distributeddb/syncer/src/sync_engine.cpp | 8 ++++---- .../distributeddb/syncer/src/sync_engine.h | 5 +---- 17 files changed, 38 insertions(+), 45 deletions(-) diff --git a/frameworks/libs/distributeddb/common/src/auto_launch.cpp b/frameworks/libs/distributeddb/common/src/auto_launch.cpp index 5e599fde4c1..99f999ade98 100644 --- a/frameworks/libs/distributeddb/common/src/auto_launch.cpp +++ b/frameworks/libs/distributeddb/common/src/auto_launch.cpp @@ -62,13 +62,13 @@ void AutoLaunch::SetCommunicatorAggregator(ICommunicatorAggregator *aggregator) errCode = aggregator->RegOnConnectCallback(std::bind(&AutoLaunch::OnlineCallBack, this, std::placeholders::_1, std::placeholders::_2), nullptr); if (errCode != E_OK) { - LOGW("[AutoLaunch] RegOnConnectCallback errCode:%d", errCode); + LOGE("[AutoLaunch] RegOnConnectCallback errCode:%d", errCode); } errCode = aggregator->RegCommunicatorLackCallback( std::bind(&AutoLaunch::ReceiveUnknownIdentifierCallBack, this, std::placeholders::_1, std::placeholders::_2), nullptr); if (errCode != E_OK) { - LOGW("[AutoLaunch] RegCommunicatorLackCallback errCode:%d", errCode); + LOGE("[AutoLaunch] RegCommunicatorLackCallback errCode:%d", errCode); } } diff --git a/frameworks/libs/distributeddb/communicator/include/communicator_aggregator.h b/frameworks/libs/distributeddb/communicator/include/communicator_aggregator.h index 30ca55f93cf..fbb6fe4e7ec 100644 --- a/frameworks/libs/distributeddb/communicator/include/communicator_aggregator.h +++ b/frameworks/libs/distributeddb/communicator/include/communicator_aggregator.h @@ -83,8 +83,8 @@ public: // Called by communicator to make itself really in work void ActivateCommunicator(const LabelType &commLabel); - // SerialBuffer surely is heap memory, CreateSendTask responsible for lifecycle - int CreateSendTask(const std::string &dstTarget, SerialBuffer *inBuff, FrameType inType, + // SerialBuffer surely is heap memory, ScheduleSendTask responsible for lifecycle + int ScheduleSendTask(const std::string &dstTarget, SerialBuffer *inBuff, FrameType inType, const TaskConfig &inConfig, const OnSendEnd &onEnd = nullptr); static void EnableCommunicatorNotFoundFeedback(bool isEnable); diff --git a/frameworks/libs/distributeddb/communicator/src/communicator.cpp b/frameworks/libs/distributeddb/communicator/src/communicator.cpp index e5c97f41267..d8eb960903c 100644 --- a/frameworks/libs/distributeddb/communicator/src/communicator.cpp +++ b/frameworks/libs/distributeddb/communicator/src/communicator.cpp @@ -131,7 +131,7 @@ int Communicator::SendMessage(const std::string &dstTarget, const Message *inMsg } TaskConfig taskConfig {config.nonBlock, config.timeout, inMsg->GetPriority()}; - errCode = commAggrHandle_->CreateSendTask(dstTarget, buffer, FrameType::APPLICATION_MESSAGE, taskConfig, onEnd); + errCode = commAggrHandle_->ScheduleSendTask(dstTarget, buffer, FrameType::APPLICATION_MESSAGE, taskConfig, onEnd); if (errCode == E_OK) { // if ok, free inMsg, otherwise the caller should take over inMsg delete inMsg; @@ -226,7 +226,7 @@ void Communicator::TriggerVersionNegotiation(const std::string &dstTarget) } TaskConfig config{true, 0, Priority::HIGH}; - errCode = commAggrHandle_->CreateSendTask(dstTarget, buffer, FrameType::EMPTY, config); + errCode = commAggrHandle_->ScheduleSendTask(dstTarget, buffer, FrameType::EMPTY, config); if (errCode != E_OK) { LOGE("[Comm][TrigVer] Send empty frame fail, errCode=%d", errCode); // if send fails, free buffer, otherwise buffer will be taked over by comminucator aggregator @@ -259,7 +259,7 @@ void Communicator::TriggerUnknownMessageFeedback(const std::string &dstTarget, M } TaskConfig config{true, 0, Priority::HIGH}; - errCode = commAggrHandle_->CreateSendTask(dstTarget, buffer, FrameType::APPLICATION_MESSAGE, config); + errCode = commAggrHandle_->ScheduleSendTask(dstTarget, buffer, FrameType::APPLICATION_MESSAGE, config); if (errCode != E_OK) { LOGE("[Comm][TrigFeedback] Send unknown message feedback frame fail, errCode=%d", errCode); // if send fails, free buffer, otherwise buffer will be taked over by comminucator aggregator diff --git a/frameworks/libs/distributeddb/communicator/src/communicator_aggregator.cpp b/frameworks/libs/distributeddb/communicator/src/communicator_aggregator.cpp index 7c9151c9fc2..49f4d572848 100644 --- a/frameworks/libs/distributeddb/communicator/src/communicator_aggregator.cpp +++ b/frameworks/libs/distributeddb/communicator/src/communicator_aggregator.cpp @@ -280,7 +280,7 @@ void DoOnSendEndByTaskIfNeed(const OnSendEnd &onEnd, int result) } } -int CommunicatorAggregator::CreateSendTask(const std::string &dstTarget, SerialBuffer *inBuff, +int CommunicatorAggregator::ScheduleSendTask(const std::string &dstTarget, SerialBuffer *inBuff, FrameType inType, const TaskConfig &inConfig, const OnSendEnd &onEnd) { if (inBuff == nullptr) { @@ -808,7 +808,7 @@ void CommunicatorAggregator::TriggerVersionNegotiation(const std::string &dstTar } TaskConfig config{true, 0, Priority::HIGH}; - errCode = CreateSendTask(dstTarget, buffer, FrameType::EMPTY, config); + errCode = ScheduleSendTask(dstTarget, buffer, FrameType::EMPTY, config); if (errCode != E_OK) { LOGE("[CommAggr][TrigVer] Send empty frame fail, errCode=%d", errCode); // if send fails, free buffer, otherwise buffer will be taked over by SendTaskScheduler @@ -860,10 +860,10 @@ void CommunicatorAggregator::TriggerCommunicatorNotFoundFeedback(const std::stri } TaskConfig config{true, 0, Priority::HIGH}; - errCode = CreateSendTask(dstTarget, buffer, FrameType::APPLICATION_MESSAGE, config); + errCode = ScheduleSendTask(dstTarget, buffer, FrameType::APPLICATION_MESSAGE, config); if (errCode != E_OK) { LOGE("[CommAggr][TrigNotFound] Send communicator not found feedback frame fail, errCode=%d", errCode); - // if send fails, free buffer, otherwise buffer will be taked over by CreateSendTask + // if send fails, free buffer, otherwise buffer will be taked over by ScheduleSendTask delete buffer; buffer = nullptr; } diff --git a/frameworks/libs/distributeddb/communicator/src/communicator_linker.cpp b/frameworks/libs/distributeddb/communicator/src/communicator_linker.cpp index 59a1b77950d..f0a08f24753 100644 --- a/frameworks/libs/distributeddb/communicator/src/communicator_linker.cpp +++ b/frameworks/libs/distributeddb/communicator/src/communicator_linker.cpp @@ -394,7 +394,7 @@ void CommunicatorLinker::SendLabelExchange(const std::string &toTarget, SerialBu int error = E_OK; SerialBuffer *cloneBuffer = inBuff->Clone(error); TaskConfig config{true, 0, Priority::HIGH}; - int errCode = aggregator_->CreateSendTask(toTarget, inBuff, FrameType::COMMUNICATION_LABEL_EXCHANGE, config); + int errCode = aggregator_->ScheduleSendTask(toTarget, inBuff, FrameType::COMMUNICATION_LABEL_EXCHANGE, config); if (errCode == E_OK) { // Send ok, go on to wait ack, and maybe resend if (error == E_OK) { @@ -450,7 +450,7 @@ void CommunicatorLinker::SendLabelExchangeAck(const std::string &toTarget, Seria } TaskConfig config{true, 0, Priority::HIGH}; - int errCode = aggregator_->CreateSendTask(toTarget, inBuff, FrameType::COMMUNICATION_LABEL_EXCHANGE_ACK, config); + int errCode = aggregator_->ScheduleSendTask(toTarget, inBuff, FrameType::COMMUNICATION_LABEL_EXCHANGE_ACK, config); if (errCode == E_OK) { // Send ok, finish event RefObject::DecObjRef(this); // ATTENTION: The DecObjRef should be outside entireInfoLockGuard!!! diff --git a/frameworks/libs/distributeddb/storage/include/single_ver_kvdb_sync_interface.h b/frameworks/libs/distributeddb/storage/include/single_ver_kvdb_sync_interface.h index dc9cdf29894..17da22c3edf 100644 --- a/frameworks/libs/distributeddb/storage/include/single_ver_kvdb_sync_interface.h +++ b/frameworks/libs/distributeddb/storage/include/single_ver_kvdb_sync_interface.h @@ -24,8 +24,6 @@ namespace DistributedDB { using MulDevTimeRanges = std::map>; -using MulDevSinVerKvEntry = std::map>; -using MulDevDataItems = std::map>; class SingleVerKvDBSyncInterface : public IKvDBSyncInterface { public: diff --git a/frameworks/libs/distributeddb/storage/src/sync_able_kvdb.cpp b/frameworks/libs/distributeddb/storage/src/sync_able_kvdb.cpp index 21edf7885b8..9c914924562 100644 --- a/frameworks/libs/distributeddb/storage/src/sync_able_kvdb.cpp +++ b/frameworks/libs/distributeddb/storage/src/sync_able_kvdb.cpp @@ -229,7 +229,7 @@ void SyncAbleKvDB::UserChangeHandle() return; } isNeedActive = RuntimeContext::GetInstance()->IsSyncerNeedActive(syncInterface->GetDbProperties()); - isNeedChange = (isNeedActive != isSyncNeedActive_) ? true : false; + isNeedChange = (isNeedActive != isSyncNeedActive_); // non_active to active or active to non_active if (isNeedChange) { StopSyncerWithNoLock(); // will drop userChangeListener diff --git a/frameworks/libs/distributeddb/syncer/src/ability_sync.cpp b/frameworks/libs/distributeddb/syncer/src/ability_sync.cpp index 8ce594da100..f4448794a66 100644 --- a/frameworks/libs/distributeddb/syncer/src/ability_sync.cpp +++ b/frameworks/libs/distributeddb/syncer/src/ability_sync.cpp @@ -131,12 +131,12 @@ uint32_t AbilitySyncRequestPacket::CalculateLen() const len += Parcel::GetUInt32Len(); // protocolVersion_ len += Parcel::GetIntLen(); // sendCode_ len += Parcel::GetUInt32Len(); // softwareVersion_ - uint32_t schemLen = Parcel::GetStringLen(schema_); - if (schemLen == 0) { - LOGE("[AbilitySyncRequestPacket][CalculateLen] schemLen err!"); + uint32_t schemaLen = Parcel::GetStringLen(schema_); + if (schemaLen == 0) { + LOGE("[AbilitySyncRequestPacket][CalculateLen] schemaLen err!"); return 0; } - len += schemLen; + len += schemaLen; len += Parcel::GetIntLen(); // secLabel_ len += Parcel::GetIntLen(); // secFlag_ len += Parcel::GetUInt32Len(); // schemaType_ @@ -145,7 +145,7 @@ uint32_t AbilitySyncRequestPacket::CalculateLen() const // the reason why not 8-byte align is that old version is not 8-byte align // so it is not possible to set 8-byte align for high version. if (len > INT32_MAX) { - LOGE("[AbilitySyncRequestPacket][CalculateLen] err len:%" PRIu64, len); + LOGE("[AbilitySyncRequestPacket][CalculateLen] err len:%" PRIu64, len); return 0; } return len; @@ -284,12 +284,12 @@ uint32_t AbilitySyncAckPacket::CalculateLen() const len += Parcel::GetUInt32Len(); len += Parcel::GetUInt32Len(); len += Parcel::GetIntLen(); - uint32_t schemLen = Parcel::GetStringLen(schema_); - if (schemLen == 0) { - LOGE("[AbilitySyncAckPacket][CalculateLen] schemLen err!"); + uint32_t schemaLen = Parcel::GetStringLen(schema_); + if (schemaLen == 0) { + LOGE("[AbilitySyncAckPacket][CalculateLen] schemaLen err!"); return 0; } - len += schemLen; + len += schemaLen; len += Parcel::GetIntLen(); // secLabel_ len += Parcel::GetIntLen(); // secFlag_ len += Parcel::GetUInt32Len(); // schemaType_ @@ -299,7 +299,7 @@ uint32_t AbilitySyncAckPacket::CalculateLen() const len += DbAbility::CalculateLen(dbAbility_); // dbAbility_ len += SchemaNegotiate::CalculateParcelLen(relationalSyncOpinion_); if (len > INT32_MAX) { - LOGE("[AbilitySyncAckPacket][CalculateLen] err len:%" PRIu64, len); + LOGE("[AbilitySyncAckPacket][CalculateLen] err len:%" PRIu64, len); return 0; } return len; diff --git a/frameworks/libs/distributeddb/syncer/src/generic_syncer.cpp b/frameworks/libs/distributeddb/syncer/src/generic_syncer.cpp index f4657850967..2ddb7609147 100644 --- a/frameworks/libs/distributeddb/syncer/src/generic_syncer.cpp +++ b/frameworks/libs/distributeddb/syncer/src/generic_syncer.cpp @@ -773,7 +773,7 @@ int GenericSyncer::StatusCheck() const return -E_NOT_INIT; } if (closing_) { - LOGE("[Syncer] Syncer is closing, return!"); + LOGW("[Syncer] Syncer is closing, return!"); return -E_BUSY; } return E_OK; diff --git a/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync.cpp b/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync.cpp index 291518d1f41..f454651b035 100644 --- a/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync.cpp +++ b/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync.cpp @@ -187,7 +187,7 @@ int SingleVerDataSync::TryContinueSync(SingleVerSyncTaskContext *context, const } if (!isAllDataHasSent_) { return InnerSyncStart(context); - } else if (reSendMap_.size() == 0) { + } else if (reSendMap_.empty()) { context->SetOperationStatus(SyncOperation::OP_SEND_FINISHED); InnerClearSyncStatus(); return -E_FINISHED; diff --git a/frameworks/libs/distributeddb/syncer/src/single_ver_kv_syncer.cpp b/frameworks/libs/distributeddb/syncer/src/single_ver_kv_syncer.cpp index 8164e1ccb0b..66ac3fa683c 100644 --- a/frameworks/libs/distributeddb/syncer/src/single_ver_kv_syncer.cpp +++ b/frameworks/libs/distributeddb/syncer/src/single_ver_kv_syncer.cpp @@ -49,7 +49,7 @@ void SingleVerKVSyncer::EnableAutoSync(bool enable) } if (!initialized_) { - LOGE("[Syncer] Syncer has not Init"); + LOGI("[Syncer] Syncer has not Init"); return; } diff --git a/frameworks/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.cpp b/frameworks/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.cpp index ef556385f0c..7c99d76f64a 100644 --- a/frameworks/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.cpp +++ b/frameworks/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.cpp @@ -52,7 +52,7 @@ void SingleVerRelationalSyncTaskContext::CopyTargetData(const ISyncTarget *targe deleteSyncId_ = GetDeviceId() + hexTableName; // save as deviceId + hexTableName } -void SingleVerRelationalSyncTaskContext::SetRelationalSyncStrategy(RelationalSyncStrategy strategy) +void SingleVerRelationalSyncTaskContext::SetRelationalSyncStrategy(RelationalSyncStrategy &strategy) { std::lock_guard autoLock(syncStrategyMutex_); relationalSyncStrategy_ = strategy; diff --git a/frameworks/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.h b/frameworks/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.h index 0146c42bf84..583e341a54d 100644 --- a/frameworks/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.h +++ b/frameworks/libs/distributeddb/syncer/src/single_ver_relational_sync_task_context.h @@ -31,7 +31,7 @@ public: std::string GetQuerySyncId() const override; std::string GetDeleteSyncId() const override; - void SetRelationalSyncStrategy(RelationalSyncStrategy strategy); + void SetRelationalSyncStrategy(RelationalSyncStrategy &strategy); SyncStrategy GetSyncStrategy(QuerySyncObject &querySyncObject) const override; void SetIsNeedResetAbilitySync(bool isNeedReset) override; diff --git a/frameworks/libs/distributeddb/syncer/src/single_ver_sync_state_machine.cpp b/frameworks/libs/distributeddb/syncer/src/single_ver_sync_state_machine.cpp index da1b99a2408..79c32e3ecac 100644 --- a/frameworks/libs/distributeddb/syncer/src/single_ver_sync_state_machine.cpp +++ b/frameworks/libs/distributeddb/syncer/src/single_ver_sync_state_machine.cpp @@ -179,6 +179,7 @@ int SingleVerSyncStateMachine::ReceiveMessageCallback(Message *inMsg) { int errCode = MessageCallbackPre(inMsg); if (errCode != E_OK) { + LOGE("[StateMachine] message pre check failed"); return errCode; } switch (inMsg->GetMessageId()) { diff --git a/frameworks/libs/distributeddb/syncer/src/single_ver_sync_task_context.cpp b/frameworks/libs/distributeddb/syncer/src/single_ver_sync_task_context.cpp index fd7f3f71b0d..32e0a8e246a 100644 --- a/frameworks/libs/distributeddb/syncer/src/single_ver_sync_task_context.cpp +++ b/frameworks/libs/distributeddb/syncer/src/single_ver_sync_task_context.cpp @@ -248,22 +248,19 @@ void SingleVerSyncTaskContext::ClearAllSyncTask() LOGI("[SingleVerSyncTaskContext] request taskcount=%zu, responsecount=%zu", requestTargetQueue_.size(), responseTargetQueue_.size()); while (!requestTargetQueue_.empty()) { - ISyncTarget *tmpTarget = nullptr; - tmpTarget = requestTargetQueue_.front(); + ISyncTarget *tmpTarget = requestTargetQueue_.front(); requestTargetQueue_.pop_front(); targetQueue.push_back(tmpTarget); } while (!responseTargetQueue_.empty()) { - ISyncTarget *tmpTarget = nullptr; - tmpTarget = responseTargetQueue_.front(); + ISyncTarget *tmpTarget = responseTargetQueue_.front(); responseTargetQueue_.pop_front(); delete tmpTarget; tmpTarget = nullptr; } } while (!targetQueue.empty()) { - ISyncTarget *target = nullptr; - target = targetQueue.front(); + ISyncTarget *target = targetQueue.front(); targetQueue.pop_front(); SyncOperation *tmpOperation = nullptr; target->GetSyncOperation(tmpOperation); diff --git a/frameworks/libs/distributeddb/syncer/src/sync_engine.cpp b/frameworks/libs/distributeddb/syncer/src/sync_engine.cpp index 221dcbca9c5..1ae060fcb26 100644 --- a/frameworks/libs/distributeddb/syncer/src/sync_engine.cpp +++ b/frameworks/libs/distributeddb/syncer/src/sync_engine.cpp @@ -403,7 +403,7 @@ int SyncEngine::DealMsgUtilQueueEmpty() // it will deal with the first message in queue, we should increase object reference counts and sure that resources // could be prevented from destroying by other threads. do { - ISyncTaskContext *nextContext = GetConextForMsg(inMsg->GetTarget(), errCode); + ISyncTaskContext *nextContext = GetContextForMsg(inMsg->GetTarget(), errCode); if (errCode != E_OK) { break; } @@ -420,7 +420,7 @@ int SyncEngine::DealMsgUtilQueueEmpty() return errCode; } -ISyncTaskContext *SyncEngine::GetConextForMsg(const std::string &targetDev, int &errCode) +ISyncTaskContext *SyncEngine::GetContextForMsg(const std::string &targetDev, int &errCode) { ISyncTaskContext *context = nullptr; { @@ -530,7 +530,7 @@ int SyncEngine::MessageReciveCallbackInner(const std::string &targetDev, Message } int errCode = E_OK; - ISyncTaskContext *nextContext = GetConextForMsg(targetDev, errCode); + ISyncTaskContext *nextContext = GetContextForMsg(targetDev, errCode); if (errCode != E_OK) { return errCode; } @@ -749,7 +749,7 @@ int SyncEngine::SetEqualIdentifier(const std::string &identifier, const std::vec } LOGI("[SyncEngine] set equal identifier=%s, original=%s, targetDevices=%s", DBCommon::TransferStringToHex(identifier).c_str(), label_.c_str(), - targetDevices.substr(0, targetDevices.size() - 1).c_str()); + targetDevices.substr(0, (targetDevices.size() > 0 ? targetDevices.size() - 1 : 0)).c_str()); communicatorProxy_->SetEqualCommunicator(communicator, identifier, targets); communicator->Activate(); return E_OK; diff --git a/frameworks/libs/distributeddb/syncer/src/sync_engine.h b/frameworks/libs/distributeddb/syncer/src/sync_engine.h index a7f8fad203a..40f07351e14 100644 --- a/frameworks/libs/distributeddb/syncer/src/sync_engine.h +++ b/frameworks/libs/distributeddb/syncer/src/sync_engine.h @@ -179,10 +179,7 @@ private: // Handle message in order. int ScheduleDealMsg(ISyncTaskContext *context, Message *inMsg); - // Schedule Sync Task - void ScheduleSyncTask(ISyncTaskContext *context); - - ISyncTaskContext *GetConextForMsg(const std::string &targetDev, int &errCode); + ISyncTaskContext *GetContextForMsg(const std::string &targetDev, int &errCode); ICommunicator *AllocCommunicator(const std::string &identifier, int &errCode); -- Gitee From c51af98f466857fb0d1c62c3be37b2f6e045a414 Mon Sep 17 00:00:00 2001 From: zwtmichael Date: Thu, 27 Oct 2022 20:14:54 +0800 Subject: [PATCH 2/2] add fuzz testcase Signed-off-by: zwtmichael --- frameworks/libs/distributeddb/test/BUILD.gn | 1 + .../common/distributeddb_tools_test.cpp | 45 +++ .../common/distributeddb_tools_test.h | 7 + .../delegate_fuzzer/delegate_fuzzer.cpp | 6 +- .../test/fuzztest/nbdelegate_fuzzer/BUILD.gn | 1 - .../nbdelegate_fuzzer/nbdelegate_fuzzer.cpp | 38 ++- .../test/fuzztest/sync_fuzzer/BUILD.gn | 110 +++++++ .../test/fuzztest/sync_fuzzer/corpus/init | 14 + .../test/fuzztest/sync_fuzzer/project.xml | 25 ++ .../test/fuzztest/sync_fuzzer/sync_fuzzer.cpp | 269 ++++++++++++++++++ .../test/fuzztest/sync_fuzzer/sync_fuzzer.h | 21 ++ 11 files changed, 534 insertions(+), 3 deletions(-) create mode 100644 frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/BUILD.gn create mode 100644 frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/corpus/init create mode 100644 frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/project.xml create mode 100644 frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/sync_fuzzer.cpp create mode 100644 frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/sync_fuzzer.h diff --git a/frameworks/libs/distributeddb/test/BUILD.gn b/frameworks/libs/distributeddb/test/BUILD.gn index 8bf97846c7c..0ac3823bbf7 100644 --- a/frameworks/libs/distributeddb/test/BUILD.gn +++ b/frameworks/libs/distributeddb/test/BUILD.gn @@ -820,6 +820,7 @@ group("distributeddatamgr_fuzztest") { "fuzztest/query_fuzzer:fuzztest", "fuzztest/rekey_fuzzer:fuzztest", "fuzztest/schemadelegate_fuzzer:fuzztest", + "fuzztest/sync_fuzzer:fuzztest", ] } ############################################################################### diff --git a/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.cpp b/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.cpp index c44360047a6..5559d4ebefe 100644 --- a/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.cpp +++ b/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.cpp @@ -130,6 +130,51 @@ void DistributedDBToolsTest::GetRandomKeyValue(std::vector &value, uint RAND_bytes(value.data(), randSize); } +DBStatus DistributedDBToolsTest::SyncTestWithQuery(KvStoreNbDelegate* delegate, + const std::vector& devices, SyncMode mode, + std::map& statuses, const Query &query) +{ + std::mutex syncLock; + std::condition_variable syncCondVar; + statuses.clear(); + DBStatus callStatus = delegate->Sync(devices, mode, + [&statuses, &syncLock, &syncCondVar](const std::map& statusMap) { + statuses = statusMap; + std::unique_lock innerlock(syncLock); + syncCondVar.notify_one(); + }, query, false); + std::unique_lock lock(syncLock); + syncCondVar.wait(lock, [callStatus, &statuses]() { + if (callStatus != OK) { + return true; + } + return !statuses.empty(); + }); + return callStatus; +} + +DBStatus DistributedDBToolsTest::SyncTest(KvStoreNbDelegate* delegate, const std::vector& devices, + SyncMode mode, std::map& statuses) +{ + std::mutex syncLock; + std::condition_variable syncCondVar; + statuses.clear(); + DBStatus callStatus = delegate->Sync(devices, mode, + [&statuses, &syncLock, &syncCondVar](const std::map& statusMap) { + statuses = statusMap; + std::unique_lock innerlock(syncLock); + syncCondVar.notify_one(); + }, false); + std::unique_lock lock(syncLock); + syncCondVar.wait(lock, [callStatus, &statuses]() { + if (callStatus != OK) { + return true; + } + return !statuses.empty(); + }); + return callStatus; +} + KvStoreObserverTest::KvStoreObserverTest() : callCount_(0), isCleared_(false) {} diff --git a/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.h b/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.h index 8650499911a..474250304f8 100644 --- a/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.h +++ b/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.h @@ -24,6 +24,7 @@ #include #include "db_types.h" +#include "store_types.h" #include "kv_store_changed_data.h" #include "kv_store_delegate_impl.h" #include "kv_store_delegate_manager.h" @@ -34,6 +35,8 @@ #include "query.h" namespace DistributedDBTest { +using namespace DistributedDB; + class DistributedDBToolsTest final { public: DistributedDBToolsTest() {} @@ -44,6 +47,10 @@ public: static int RemoveTestDbFiles(const std::string &dir); static int GetCurrentDir(std::string& dir); static void GetRandomKeyValue(std::vector &value, uint32_t defaultSize = 0); + static DBStatus SyncTestWithQuery(KvStoreNbDelegate* delegate, const std::vector& devices, + SyncMode mode, std::map& statuses, const Query &query); + static DBStatus SyncTest(KvStoreNbDelegate* delegate, const std::vector& devices, SyncMode mode, + std::map& statuses); }; class KvStoreObserverTest : public DistributedDB::KvStoreObserver { diff --git a/frameworks/libs/distributeddb/test/fuzztest/delegate_fuzzer/delegate_fuzzer.cpp b/frameworks/libs/distributeddb/test/fuzztest/delegate_fuzzer/delegate_fuzzer.cpp index 3d526c52b9d..877aec9330c 100644 --- a/frameworks/libs/distributeddb/test/fuzztest/delegate_fuzzer/delegate_fuzzer.cpp +++ b/frameworks/libs/distributeddb/test/fuzztest/delegate_fuzzer/delegate_fuzzer.cpp @@ -79,11 +79,15 @@ void MultiCombineFuzzer(const uint8_t* data, size_t size, KvStoreDelegate::Optio kvStoreSnapshotPtr->GetEntries(keyPrefix, [](DBStatus status, const std::vector &entries) { (void) entries.size(); }); - + kvDelegatePtr->CheckIntegrity(); + std::string tmpStoreId = kvDelegatePtr->GetStoreId(); + kvDelegatePtr->RemoveDeviceData(deviceId); + kvDelegatePtr->RemoveDeviceData(); kvDelegatePtr->DeleteBatch(keys); kvDelegatePtr->Clear(); kvDelegatePtr->UnRegisterObserver(observer); kvDelegatePtr->ReleaseKvStoreSnapshot(kvStoreSnapshotPtr); + std::string deviceId(data, data + size % 100); kvManger.CloseKvStore(kvDelegatePtr); kvManger.DeleteKvStore("distributed_delegate_test"); DistributedDBToolsTest::RemoveTestDbFiles(config.dataDir); diff --git a/frameworks/libs/distributeddb/test/fuzztest/nbdelegate_fuzzer/BUILD.gn b/frameworks/libs/distributeddb/test/fuzztest/nbdelegate_fuzzer/BUILD.gn index f7ad33321c8..e73260a66ee 100644 --- a/frameworks/libs/distributeddb/test/fuzztest/nbdelegate_fuzzer/BUILD.gn +++ b/frameworks/libs/distributeddb/test/fuzztest/nbdelegate_fuzzer/BUILD.gn @@ -61,7 +61,6 @@ ohos_fuzztest("NbDelegateFuzzTest") { "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/common/src/log_print.cpp", "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/common/src/platform_specific.cpp", "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_data_generate_unit_test.cpp", "nbdelegate_fuzzer.cpp", ] diff --git a/frameworks/libs/distributeddb/test/fuzztest/nbdelegate_fuzzer/nbdelegate_fuzzer.cpp b/frameworks/libs/distributeddb/test/fuzztest/nbdelegate_fuzzer/nbdelegate_fuzzer.cpp index 5138d498f00..e31ec3fa4a3 100644 --- a/frameworks/libs/distributeddb/test/fuzztest/nbdelegate_fuzzer/nbdelegate_fuzzer.cpp +++ b/frameworks/libs/distributeddb/test/fuzztest/nbdelegate_fuzzer/nbdelegate_fuzzer.cpp @@ -152,7 +152,29 @@ void FuzzCURD(const uint8_t* data, size_t size, KvStoreNbDelegate *kvNbDelegateP kvNbDelegatePtr->DeleteBatch(keys); kvNbDelegatePtr->UnRegisterObserver(observer); kvNbDelegatePtr->PutLocalBatch(tmp); - + kvNbDelegatePtr->DeleteLocalBatch(keys); + SecurityOption secOption; + kvNbDelegatePtr->GetSecurityOption(secOption); + kvNbDelegatePtr->CheckIntegrity(); + g_kvNbDelegatePtr->SetPushDataInterceptor( + [](InterceptedData &data, const std::string &sourceID, const std::string &targetID) { + int errCode = OK; + auto entries = data.GetEntries(); + for (size_t i = 0; i < entries.size(); i++) { + if (entries[i].key.empty() || entries[i].key.at(0) != 'A') { + continue; + } + auto newKey = entries[i].key; + newKey[0] = 'B'; + errCode = data.ModifyKey(i, newKey); + if (errCode != OK) { + break; + } + } + return errCode; + } + ); + if (!keys.empty()) { /* random deletePublic updateTimestamp 2 */ kvNbDelegatePtr->PublishLocal(keys[0], (data[0] > data[1]), (data[2] > data[1]), nullptr); @@ -162,6 +184,17 @@ void FuzzCURD(const uint8_t* data, size_t size, KvStoreNbDelegate *kvNbDelegateP kvNbDelegatePtr->RemoveDeviceData(rawString); } +void EncryptOperation(const uint8_t* data, size_t size, std::string &DirPath, KvStoreNbDelegate *kvNbDelegatePtr) +{ + CipherPassword passwd; + passwd.SetValue(data, 50); + kvNbDelegatePtr->Rekey(passwd); + std::string fileName(data + 500, data + 510); + std::string mulitExportFileName = DirPath + "/" + fileName + ".db"; + kvNbDelegatePtr->Export(mulitExportFileName, passwd); + kvNbDelegatePtr->Import(mulitExportFileName, passwd); +} + void CombineTest(const uint8_t* data, size_t size, KvStoreNbDelegate::Option &option) { static auto kvManager = KvStoreDelegateManager("APP_ID", "USER_ID"); @@ -176,6 +209,9 @@ void CombineTest(const uint8_t* data, size_t size, KvStoreNbDelegate::Option &op } }); FuzzCURD(data, size, kvNbDelegatePtr); + if (option.isEncryptedDb) { + EncryptOperation(data, size, config.dataDir, kvNbDelegatePtr); + } kvManager.CloseKvStore(kvNbDelegatePtr); kvManager.DeleteKvStore("distributed_nb_delegate_test"); DistributedDBToolsTest::RemoveTestDbFiles(config.dataDir); diff --git a/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/BUILD.gn b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/BUILD.gn new file mode 100644 index 00000000000..d772f9fb60b --- /dev/null +++ b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/BUILD.gn @@ -0,0 +1,110 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("SyncFuzzTest") { + module_out_path = "kv_store/distributeddb" + + include_dirs = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/fuzztest/common", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/unittest/common/common", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/interfaces/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/interfaces/src", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/storage/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/storage/src", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/storage/src/sqlite", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/storage/src/multiver", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/common/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/common/src", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/communicator/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/communicator/src", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/syncer/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/syncer/src", + "//commonlibrary/c_utils/base/include", + "//third_party/sqlite/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/common/include/relational", + "//third_party/jsoncpp/include/json", + "//third_party/skia/third_party/externals/spirv-headers/tools/buildHeaders/jsoncpp/dist/json", + "//third_party/skia/third_party/externals/swiftshader/third_party/SPIRV-Headers/tools/buildHeaders/jsoncpp/dist/json", + "//third_party/jsoncpp/include/json", + "//third_party/grpc/src/core/lib/json", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + fuzz_config_file = "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer" + + sources = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/common/src/db_common.cpp", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/common/src/log_print.cpp", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/common/src/platform_specific.cpp", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/fuzztest/common/distributeddb_tools_test.cpp", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/fuzztest/common/fuzzer_data.cpp", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/kv_virtual_device.cpp", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/generic_virtual_device.cpp", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.cpp", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator.cpp", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator_aggregator.cpp", + "sync_fuzzer.cpp", + ] + + defines = [ + "SQLITE_ENABLE_SNAPSHOT", + "_LARGEFILE64_SOURCE", + "_FILE_OFFSET_BITS=64", + "SQLITE_HAS_CODEC", + "SQLITE_ENABLE_JSON1", + "USING_HILOG_LOGGER", + "USE_SQLITE_SYMBOLS", + "USING_DB_JSON_EXTRACT_AUTOMATICALLY", + "LOW_LEVEL_MEM_DEV", + "JSONCPP_USE_BUILDER", + "OMIT_FLATBUFFER", + "RELATIONAL_STORE", + "SQLITE_DISTRIBUTE_RELATIONAL", + ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/jsoncpp:jsoncpp", + "//third_party/openssl:libcrypto_shared", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} + +############################################################################### + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":SyncFuzzTest", + ] +} diff --git a/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/corpus/init b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/corpus/init new file mode 100644 index 00000000000..bc977bd9738 --- /dev/null +++ b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/project.xml b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/project.xml new file mode 100644 index 00000000000..5556db1cc4f --- /dev/null +++ b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 2000 + + 30 + + 4096 + + diff --git a/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/sync_fuzzer.cpp b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/sync_fuzzer.cpp new file mode 100644 index 00000000000..0ddb207e5cc --- /dev/null +++ b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/sync_fuzzer.cpp @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sync_fuzzer.h" + +#include "db_constant.h" +#include "db_common.h" +#include "distributeddb_data_generate_unit_test.h" +#include "distributeddb_tools_test.h" +#include "fuzzer_data.h" +#include "virtual_communicator_aggregator.h" +#include "kv_store_nb_delegate.h" +#include "kv_virtual_device.h" +#include "platform_specific.h" +#include "log_print.h" + +class KvStoreSyncFuzzer { + /* Keep C++ file names the same as the class name. */ +}; + +namespace OHOS { +using namespace DistributedDB; +using namespace DistributedDBTest; + +VirtualCommunicatorAggregator* g_communicatorAggregator = nullptr; +KvVirtualDevice *g_deviceB = nullptr; +KvStoreDelegateManager g_mgr("APP_ID", "USER_ID"); +KvStoreNbDelegate* g_kvDelegatePtr = nullptr; +const std::string DEVICE_B = "deviceB"; +const std::string STORE_ID = "kv_strore_sync_test"; + +int InitEnv() +{ + g_communicatorAggregator = new (std::nothrow) VirtualCommunicatorAggregator(); + if (g_communicatorAggregator == nullptr) { + return -E_OUT_OF_MEMORY; + } + RuntimeContext::GetInstance()->SetCommunicatorAggregator(g_communicatorAggregator); + return E_OK; +} + +int FinalizeEnv() +{ + RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr); +} + +void SetUpTestcase() +{ + KvStoreNbDelegate::Option option = {true, false, false}; + g_mgr.GetKvStore("distributed_nb_delegate_test", option, + [] (DBStatus status, KvStoreNbDelegate* kvNbDelegate) { + if (status == DBStatus::OK) { + g_kvDelegatePtr = kvNbDelegate; + } + }); + g_deviceB = new (std::nothrow) KvVirtualDevice(DEVICE_B); + if (g_deviceB == nullptr) { + return; + } + VirtualSingleVerSyncDBInterface *syncInterfaceB = new (std::nothrow) VirtualSingleVerSyncDBInterface(); + if (syncInterfaceB == nullptr) { + return; + } + g_deviceB->Initialize(g_communicatorAggregator, syncInterfaceB); +} + +void TearDownTestCase() +{ + if (g_kvDelegatePtr != nullptr) { + g_mgr.CloseKvStore(g_kvDelegatePtr); + g_kvDelegatePtr = nullptr; + g_mgr.DeleteKvStore(STORE_ID); + } + if (g_deviceB != nullptr) { + delete g_deviceB; + g_deviceB = nullptr; + } +} + +std::vector CreateEntries(const uint8_t* data, size_t size, std::vector keys) +{ + std::vector entries; + // key'length is less than 1024. + auto count = static_cast(std::min(size, size_t(1024))); + for (int i = 1; i < count; i++) { + Entry entry; + entry.key = std::vector(data, data + i); + keys.push_back(entry.key); + entry.value = std::vector(data, data + size); + entries.push_back(entry); + } + return entries; +} + +void NormalSyncPush(const uint8_t* data, size_t size, bool isWithQuery = false) +{ + SetUpTestcase(); + std::vector keys; + std::vector tmp = CreateEntries(data, size, keys); + g_kvDelegatePtr->PutBatch(tmp); + std::vector devices; + devices.push_back(g_deviceB->GetDeviceId()); + std::map result; + if (isWithQuery) { + Key tmpKey = std::vector(data + 100, data + 200); + Query query = Query::Select().PrefixKey(tmpKey); + DistributedDBToolsTest::SyncTestWithQuery(g_kvDelegatePtr, devices, SYNC_MODE_PUSH_ONLY, result, query); + } else { + DistributedDBToolsTest::SyncTest(g_kvDelegatePtr, devices, SYNC_MODE_PUSH_ONLY, result); + } + TearDownTestCase(); +} + +void NormalSyncPull(const uint8_t* data, size_t size, bool isWithQuery = false) +{ + SetUpTestcase(); + std::vector keys; + std::vector tmp = CreateEntries(data, size, keys); + g_kvDelegatePtr->PutBatch(tmp); + int i = 0; + for (auto &item : tmp) { + g_deviceB->PutData(item.key, item.value, i++, 0); + } + g_kvDelegatePtr->SetRemotePushFinishedNotify( + [&pushfinishedFlag](const RemotePushNotifyInfo &info) { + EXPECT_TRUE(info.deviceId == DEVICE_B); + pushfinishedFlag = 1; + }); + + std::vector devices; + devices.push_back(g_deviceB->GetDeviceId()); + std::map result; + if (isWithQuery) { + Key tmpKey = std::vector(data + 100, data + 200); + Query query = Query::Select().PrefixKey(tmpKey); + DistributedDBToolsTest::SyncTestWithQuery(g_kvDelegatePtr, devices, SYNC_MODE_PULL_ONLY, result, query); + } else { + DistributedDBToolsTest::SyncTest(g_kvDelegatePtr, devices, SYNC_MODE_PULL_ONLY, result); + } + TearDownTestCase(); +} + +void NormalSyncPushAndPull(const uint8_t* data, size_t size, bool isWithQuery = false) +{ + SetUpTestcase(); + std::vector keys; + std::vector tmp = CreateEntries(data, size, keys); + g_kvDelegatePtr->PutBatch(tmp); + std::vector devices; + devices.push_back(g_deviceB->GetDeviceId()); + std::map result; + if (isWithQuery) { + Key tmpKey = std::vector(data + 100, data + 200); + Query query = Query::Select().PrefixKey(tmpKey); + DistributedDBToolsTest::SyncTestWithQuery(g_kvDelegatePtr, devices, SYNC_MODE_PUSH_PULL, result, query); + } else { + DistributedDBToolsTest::SyncTest(g_kvDelegatePtr, devices, SYNC_MODE_PUSH_PULL, result); + } + TearDownTestCase(); +} + +void SubscribeOperation(const uint8_t* data, size_t size) +{ + SetUpTestcase(); + std::vector devices; + devices.push_back(g_deviceB->GetDeviceId()); + Query query2 = Query::Select().EqualTo("$.field_name1", 1).Limit(20, 0); + LOGI("----begin to SubscribeRemoteQuery query2"); + g_kvDelegatePtr->SubscribeRemoteQuery(devices, nullptr, query2, true); + std::set keys; + for (int i = 0; i < 3; i++) { + Key tmpKey = std::vector(data, data + 5); + keys.insert(tmpKey); + } + Query query = Query::Select().InKeys(keys); + g_kvDelegatePtr->SubscribeRemoteQuery(devices, nullptr, query, true); + g_kvDelegatePtr->UnSubscribeRemoteQuery(devices, nullptr, query2, true); + g_kvDelegatePtr->UnSubscribeRemoteQuery(devices, nullptr, query, true); + TearDownTestCase(); +} + +void OtherOperation(const uint8_t* data, size_t size) +{ + SetUpTestcase(); + std::string tmpIdentifier(data, data + 100); + std::vector targets; + int j = 0; + for (int i = 0; i < 10; i++) { + std::string tmpStr(data + 1000 + j, data + 1000 + 30); + j = j + 30; + targets.push_back(tmpStr); + } + g_kvDelegatePtr->SetEqualIdentifier(tmpIdentifier, targets); + TearDownTestCase(); +} + +void PragmaOperation(const uint8_t* data, size_t size) +{ + SetUpTestcase(); + FuzzerData fuzzData(data, size); + bool autoSync = data[0]; + PragmaData data = static_cast(&autoSync); + DBStatus status = g_kvDelegatePtr->Pragma(AUTO_SYNC, data); + + PragmaDeviceIdentifier param1; + std::string tmpStr(data, data + 100); + param1.deviceID = tmpStr; + PragmaData input = static_cast(¶m1); + g_kvDelegatePtr->Pragma(GET_IDENTIFIER_OF_DEVICE, input); + + PragmaEntryDeviceIdentifier param2; + param2.key.assign(data + 500, data + 600); + param2.origDevice = false; + input = static_cast(¶m2); + EXPECT_EQ(g_kvDelegatePtr->Pragma(GET_DEVICE_IDENTIFIER_OF_ENTRY, input), OK); + + int size; + input = static_cast(&size); + EXPECT_EQ(g_kvDelegatePtr->Pragma(GET_QUEUED_SYNC_SIZE, input), OK); + + int limit = fuzzData.GetInt(); + input = static_cast(&limit); + EXPECT_EQ(g_kvDelegatePtr->Pragma(SET_QUEUED_SYNC_LIMIT, input), OK); + + int limit2 = 0; + PragmaData input = static_cast(&limit2); + EXPECT_EQ(g_kvDelegatePtr->Pragma(GET_QUEUED_SYNC_LIMIT, input), OK); + TearDownTestCase(); +} + +void FuzzSync(const uint8_t* data, size_t size) +{ + KvStoreConfig config; + DistributedDBToolsTest::TestDirInit(config.dataDir); + g_mgr.SetKvStoreConfig(config); + InitEnv(); + NormalSyncPush(data, size); + NormalSyncPull(data, size); + NormalSyncPushAndPull(data, size); + NormalSyncPush(data, size, true); + NormalSyncPull(data, size, true); + NormalSyncPushAndPull(data, size, true); + SubscribeOperation(data, size); + OtherOperation(data, size); + PragmaOperation(data, size); + FinalizeEnv(); + DistributedDBToolsTest::RemoveTestDbFiles(config.dataDir); +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::FuzzSync(data, size); + return 0; +} + diff --git a/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/sync_fuzzer.h b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/sync_fuzzer.h new file mode 100644 index 00000000000..40a6f49cd40 --- /dev/null +++ b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/sync_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SYNC_FUZZER_H +#define SYNC_FUZZER_H + +#define FUZZ_PROJECT_NAME "Sync_fuzzer" + +#endif // NBDELEGATE_FUZZER_H -- Gitee